babylon.no-module.max.js 4.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002930039300493005930069300793008930099301093011930129301393014930159301693017930189301993020930219302293023930249302593026930279302893029930309303193032930339303493035930369303793038930399304093041930429304393044930459304693047930489304993050930519305293053930549305593056930579305893059930609306193062930639306493065930669306793068930699307093071930729307393074930759307693077930789307993080930819308293083930849308593086930879308893089930909309193092930939309493095930969309793098930999310093101931029310393104931059310693107931089310993110931119311293113931149311593116931179311893119931209312193122931239312493125931269312793128931299313093131931329313393134931359313693137931389313993140931419314293143931449314593146931479314893149931509315193152931539315493155931569315793158931599316093161931629316393164931659316693167931689316993170931719317293173931749317593176931779317893179931809318193182931839318493185931869318793188931899319093191931929319393194931959319693197931989319993200932019320293203932049320593206932079320893209932109321193212932139321493215932169321793218932199322093221932229322393224932259322693227932289322993230932319323293233932349323593236932379323893239932409324193242932439324493245932469324793248932499325093251932529325393254932559325693257932589325993260932619326293263932649326593266932679326893269932709327193272932739327493275932769327793278932799328093281932829328393284932859328693287932889328993290932919329293293932949329593296932979329893299933009330193302933039330493305933069330793308933099331093311933129331393314933159331693317933189331993320933219332293323933249332593326933279332893329933309333193332933339333493335933369333793338933399334093341933429334393344933459334693347933489334993350933519335293353933549335593356933579335893359933609336193362933639336493365933669336793368933699337093371933729337393374933759337693377933789337993380933819338293383933849338593386933879338893389933909339193392933939339493395933969339793398933999340093401934029340393404934059340693407934089340993410934119341293413934149341593416934179341893419934209342193422934239342493425934269342793428934299343093431934329343393434934359343693437934389343993440934419344293443934449344593446934479344893449934509345193452934539345493455934569345793458934599346093461934629346393464934659346693467934689346993470934719347293473934749347593476934779347893479934809348193482934839348493485934869348793488934899349093491934929349393494934959349693497934989349993500935019350293503935049350593506935079350893509935109351193512935139351493515935169351793518935199352093521935229352393524935259352693527935289352993530935319353293533935349353593536935379353893539935409354193542935439354493545935469354793548935499355093551935529355393554935559355693557935589355993560935619356293563935649356593566935679356893569935709357193572935739357493575935769357793578935799358093581935829358393584935859358693587935889358993590935919359293593935949359593596935979359893599936009360193602936039360493605936069360793608936099361093611936129361393614936159361693617936189361993620936219362293623936249362593626936279362893629936309363193632936339363493635936369363793638936399364093641936429364393644936459364693647936489364993650936519365293653936549365593656936579365893659936609366193662936639366493665936669366793668936699367093671936729367393674936759367693677936789367993680936819368293683936849368593686936879368893689936909369193692936939369493695936969369793698936999370093701937029370393704937059370693707937089370993710937119371293713937149371593716937179371893719937209372193722937239372493725937269372793728937299373093731937329373393734937359373693737937389373993740937419374293743937449374593746937479374893749937509375193752937539375493755937569375793758937599376093761937629376393764937659376693767937689376993770937719377293773937749377593776937779377893779937809378193782937839378493785937869378793788937899379093791937929379393794937959379693797937989379993800938019380293803938049380593806938079380893809938109381193812938139381493815938169381793818938199382093821938229382393824938259382693827938289382993830938319383293833938349383593836938379383893839938409384193842938439384493845938469384793848938499385093851938529385393854938559385693857938589385993860938619386293863938649386593866938679386893869938709387193872938739387493875938769387793878938799388093881938829388393884938859388693887938889388993890938919389293893938949389593896938979389893899939009390193902939039390493905939069390793908939099391093911939129391393914939159391693917939189391993920939219392293923939249392593926939279392893929939309393193932939339393493935939369393793938939399394093941939429394393944939459394693947939489394993950939519395293953939549395593956939579395893959939609396193962939639396493965939669396793968939699397093971939729397393974939759397693977939789397993980939819398293983939849398593986939879398893989939909399193992939939399493995939969399793998939999400094001940029400394004940059400694007940089400994010940119401294013940149401594016940179401894019940209402194022940239402494025940269402794028940299403094031940329403394034940359403694037940389403994040940419404294043940449404594046940479404894049940509405194052940539405494055940569405794058940599406094061940629406394064940659406694067940689406994070940719407294073940749407594076940779407894079940809408194082940839408494085940869408794088940899409094091940929409394094940959409694097940989409994100941019410294103941049410594106941079410894109941109411194112941139411494115941169411794118941199412094121941229412394124941259412694127941289412994130941319413294133941349413594136941379413894139941409414194142941439414494145941469414794148941499415094151941529415394154941559415694157941589415994160941619416294163941649416594166941679416894169941709417194172941739417494175941769417794178941799418094181941829418394184941859418694187941889418994190941919419294193941949419594196941979419894199942009420194202942039420494205942069420794208942099421094211942129421394214942159421694217942189421994220942219422294223942249422594226942279422894229942309423194232942339423494235942369423794238942399424094241942429424394244942459424694247942489424994250942519425294253942549425594256942579425894259942609426194262942639426494265942669426794268942699427094271942729427394274942759427694277942789427994280942819428294283942849428594286942879428894289942909429194292942939429494295942969429794298942999430094301943029430394304943059430694307943089430994310943119431294313943149431594316943179431894319943209432194322943239432494325943269432794328943299433094331943329433394334943359433694337943389433994340943419434294343943449434594346943479434894349943509435194352943539435494355943569435794358943599436094361943629436394364943659436694367943689436994370943719437294373943749437594376943779437894379943809438194382943839438494385943869438794388943899439094391943929439394394943959439694397943989439994400944019440294403944049440594406944079440894409944109441194412944139441494415944169441794418944199442094421944229442394424944259442694427944289442994430944319443294433944349443594436944379443894439944409444194442944439444494445944469444794448944499445094451944529445394454944559445694457944589445994460944619446294463944649446594466944679446894469944709447194472944739447494475944769447794478944799448094481944829448394484944859448694487944889448994490944919449294493944949449594496944979449894499945009450194502945039450494505945069450794508945099451094511945129451394514945159451694517945189451994520945219452294523945249452594526945279452894529945309453194532945339453494535945369453794538945399454094541945429454394544945459454694547945489454994550945519455294553945549455594556945579455894559945609456194562945639456494565945669456794568945699457094571945729457394574945759457694577945789457994580945819458294583945849458594586945879458894589945909459194592945939459494595945969459794598945999460094601946029460394604946059460694607946089460994610946119461294613946149461594616946179461894619946209462194622946239462494625946269462794628946299463094631946329463394634946359463694637946389463994640946419464294643946449464594646946479464894649946509465194652946539465494655946569465794658946599466094661946629466394664946659466694667946689466994670946719467294673946749467594676946779467894679946809468194682946839468494685946869468794688946899469094691946929469394694946959469694697946989469994700947019470294703947049470594706947079470894709947109471194712947139471494715947169471794718947199472094721947229472394724947259472694727947289472994730947319473294733947349473594736947379473894739947409474194742947439474494745947469474794748947499475094751947529475394754947559475694757947589475994760947619476294763947649476594766947679476894769947709477194772947739477494775947769477794778947799478094781947829478394784947859478694787947889478994790947919479294793947949479594796947979479894799948009480194802948039480494805948069480794808948099481094811948129481394814948159481694817948189481994820948219482294823948249482594826948279482894829948309483194832948339483494835948369483794838948399484094841948429484394844948459484694847948489484994850948519485294853948549485594856948579485894859948609486194862948639486494865948669486794868948699487094871948729487394874948759487694877948789487994880948819488294883948849488594886948879488894889948909489194892948939489494895948969489794898948999490094901949029490394904949059490694907949089490994910949119491294913949149491594916949179491894919949209492194922949239492494925949269492794928949299493094931949329493394934949359493694937949389493994940949419494294943949449494594946949479494894949949509495194952949539495494955949569495794958949599496094961949629496394964949659496694967949689496994970949719497294973949749497594976949779497894979949809498194982949839498494985949869498794988949899499094991949929499394994949959499694997949989499995000950019500295003950049500595006950079500895009950109501195012950139501495015950169501795018950199502095021950229502395024950259502695027950289502995030950319503295033950349503595036950379503895039950409504195042950439504495045950469504795048950499505095051950529505395054950559505695057950589505995060950619506295063950649506595066950679506895069950709507195072950739507495075950769507795078950799508095081950829508395084950859508695087950889508995090950919509295093950949509595096950979509895099951009510195102951039510495105951069510795108951099511095111951129511395114951159511695117951189511995120951219512295123951249512595126951279512895129951309513195132951339513495135951369513795138951399514095141951429514395144951459514695147951489514995150951519515295153951549515595156951579515895159951609516195162951639516495165951669516795168951699517095171951729517395174951759517695177951789517995180951819518295183951849518595186951879518895189951909519195192951939519495195951969519795198951999520095201952029520395204952059520695207952089520995210952119521295213952149521595216952179521895219952209522195222952239522495225952269522795228952299523095231952329523395234952359523695237952389523995240952419524295243952449524595246952479524895249952509525195252952539525495255952569525795258952599526095261952629526395264952659526695267952689526995270952719527295273952749527595276952779527895279952809528195282952839528495285952869528795288952899529095291952929529395294952959529695297952989529995300953019530295303953049530595306953079530895309953109531195312953139531495315953169531795318953199532095321953229532395324953259532695327953289532995330953319533295333953349533595336953379533895339953409534195342953439534495345953469534795348953499535095351953529535395354953559535695357953589535995360953619536295363953649536595366953679536895369953709537195372953739537495375953769537795378953799538095381953829538395384953859538695387953889538995390953919539295393953949539595396953979539895399954009540195402954039540495405954069540795408954099541095411954129541395414954159541695417954189541995420954219542295423954249542595426954279542895429954309543195432954339543495435954369543795438954399544095441954429544395444954459544695447954489544995450954519545295453954549545595456954579545895459954609546195462954639546495465954669546795468954699547095471954729547395474954759547695477954789547995480954819548295483954849548595486954879548895489954909549195492954939549495495954969549795498954999550095501955029550395504955059550695507955089550995510955119551295513955149551595516955179551895519955209552195522955239552495525955269552795528955299553095531955329553395534955359553695537955389553995540955419554295543955449554595546955479554895549955509555195552955539555495555955569555795558955599556095561955629556395564955659556695567955689556995570955719557295573955749557595576955779557895579955809558195582955839558495585955869558795588955899559095591955929559395594955959559695597955989559995600956019560295603956049560595606956079560895609956109561195612956139561495615956169561795618956199562095621956229562395624956259562695627956289562995630956319563295633956349563595636956379563895639956409564195642956439564495645956469564795648956499565095651956529565395654956559565695657956589565995660956619566295663956649566595666956679566895669956709567195672956739567495675956769567795678956799568095681956829568395684956859568695687956889568995690956919569295693956949569595696956979569895699957009570195702957039570495705957069570795708957099571095711957129571395714957159571695717957189571995720957219572295723957249572595726957279572895729957309573195732957339573495735957369573795738957399574095741957429574395744957459574695747957489574995750957519575295753957549575595756957579575895759957609576195762957639576495765957669576795768957699577095771957729577395774957759577695777957789577995780957819578295783957849578595786957879578895789957909579195792957939579495795957969579795798957999580095801958029580395804958059580695807958089580995810958119581295813958149581595816958179581895819958209582195822958239582495825958269582795828958299583095831958329583395834958359583695837958389583995840958419584295843958449584595846958479584895849958509585195852958539585495855958569585795858958599586095861958629586395864958659586695867958689586995870958719587295873958749587595876958779587895879958809588195882958839588495885958869588795888958899589095891958929589395894958959589695897958989589995900959019590295903959049590595906959079590895909959109591195912959139591495915959169591795918959199592095921959229592395924959259592695927959289592995930959319593295933959349593595936959379593895939959409594195942959439594495945959469594795948959499595095951959529595395954959559595695957959589595995960959619596295963959649596595966959679596895969959709597195972959739597495975959769597795978959799598095981959829598395984959859598695987959889598995990959919599295993959949599595996959979599895999960009600196002960039600496005960069600796008960099601096011960129601396014960159601696017960189601996020960219602296023960249602596026960279602896029960309603196032960339603496035960369603796038960399604096041960429604396044960459604696047960489604996050960519605296053960549605596056960579605896059960609606196062960639606496065960669606796068960699607096071960729607396074960759607696077960789607996080960819608296083960849608596086960879608896089960909609196092960939609496095960969609796098960999610096101961029610396104961059610696107961089610996110961119611296113961149611596116961179611896119961209612196122961239612496125961269612796128961299613096131961329613396134961359613696137961389613996140961419614296143961449614596146961479614896149961509615196152961539615496155961569615796158961599616096161961629616396164961659616696167961689616996170961719617296173961749617596176961779617896179961809618196182961839618496185961869618796188961899619096191961929619396194961959619696197961989619996200962019620296203962049620596206962079620896209962109621196212962139621496215962169621796218962199622096221962229622396224962259622696227962289622996230962319623296233962349623596236962379623896239962409624196242962439624496245962469624796248962499625096251962529625396254962559625696257962589625996260962619626296263962649626596266962679626896269962709627196272962739627496275962769627796278962799628096281962829628396284962859628696287962889628996290962919629296293962949629596296962979629896299963009630196302963039630496305963069630796308963099631096311963129631396314963159631696317963189631996320963219632296323963249632596326963279632896329963309633196332963339633496335963369633796338963399634096341963429634396344963459634696347963489634996350963519635296353963549635596356963579635896359963609636196362963639636496365963669636796368963699637096371963729637396374963759637696377963789637996380963819638296383963849638596386963879638896389963909639196392963939639496395963969639796398963999640096401964029640396404964059640696407964089640996410964119641296413964149641596416964179641896419964209642196422964239642496425964269642796428964299643096431964329643396434964359643696437964389643996440964419644296443964449644596446964479644896449964509645196452964539645496455964569645796458964599646096461964629646396464964659646696467964689646996470964719647296473964749647596476964779647896479964809648196482964839648496485964869648796488964899649096491964929649396494964959649696497964989649996500965019650296503965049650596506965079650896509965109651196512965139651496515965169651796518965199652096521965229652396524965259652696527965289652996530965319653296533965349653596536965379653896539965409654196542965439654496545965469654796548965499655096551965529655396554965559655696557965589655996560965619656296563965649656596566965679656896569965709657196572965739657496575965769657796578965799658096581965829658396584965859658696587965889658996590965919659296593965949659596596965979659896599966009660196602966039660496605966069660796608966099661096611966129661396614966159661696617966189661996620966219662296623966249662596626966279662896629966309663196632966339663496635966369663796638966399664096641966429664396644966459664696647966489664996650966519665296653966549665596656966579665896659966609666196662966639666496665966669666796668966699667096671966729667396674966759667696677966789667996680966819668296683966849668596686966879668896689966909669196692966939669496695966969669796698966999670096701967029670396704967059670696707967089670996710967119671296713967149671596716967179671896719967209672196722967239672496725967269672796728967299673096731967329673396734967359673696737967389673996740967419674296743967449674596746967479674896749967509675196752967539675496755967569675796758967599676096761967629676396764967659676696767967689676996770967719677296773967749677596776967779677896779967809678196782967839678496785967869678796788967899679096791967929679396794967959679696797967989679996800968019680296803968049680596806968079680896809968109681196812968139681496815968169681796818968199682096821968229682396824968259682696827968289682996830968319683296833968349683596836968379683896839968409684196842968439684496845968469684796848968499685096851968529685396854968559685696857968589685996860968619686296863968649686596866968679686896869968709687196872968739687496875968769687796878968799688096881968829688396884968859688696887968889688996890968919689296893968949689596896968979689896899969009690196902969039690496905969069690796908969099691096911969129691396914969159691696917969189691996920969219692296923969249692596926969279692896929969309693196932969339693496935969369693796938969399694096941969429694396944969459694696947969489694996950969519695296953969549695596956969579695896959969609696196962969639696496965969669696796968969699697096971969729697396974969759697696977969789697996980969819698296983969849698596986969879698896989969909699196992969939699496995969969699796998969999700097001970029700397004970059700697007970089700997010970119701297013970149701597016970179701897019970209702197022970239702497025970269702797028970299703097031970329703397034970359703697037970389703997040970419704297043970449704597046970479704897049970509705197052970539705497055970569705797058970599706097061970629706397064970659706697067970689706997070970719707297073970749707597076970779707897079970809708197082970839708497085970869708797088970899709097091970929709397094970959709697097970989709997100971019710297103971049710597106971079710897109971109711197112971139711497115971169711797118971199712097121971229712397124971259712697127971289712997130971319713297133971349713597136971379713897139971409714197142971439714497145971469714797148971499715097151971529715397154971559715697157971589715997160971619716297163971649716597166971679716897169971709717197172971739717497175971769717797178971799718097181971829718397184971859718697187971889718997190971919719297193971949719597196971979719897199972009720197202972039720497205972069720797208972099721097211972129721397214972159721697217972189721997220972219722297223972249722597226972279722897229972309723197232972339723497235972369723797238972399724097241972429724397244972459724697247972489724997250972519725297253972549725597256972579725897259972609726197262972639726497265972669726797268972699727097271972729727397274972759727697277972789727997280972819728297283972849728597286972879728897289972909729197292972939729497295972969729797298972999730097301973029730397304973059730697307973089730997310973119731297313973149731597316973179731897319973209732197322973239732497325973269732797328973299733097331973329733397334973359733697337973389733997340973419734297343973449734597346973479734897349973509735197352973539735497355973569735797358973599736097361973629736397364973659736697367973689736997370973719737297373973749737597376973779737897379973809738197382973839738497385973869738797388973899739097391973929739397394973959739697397973989739997400974019740297403974049740597406974079740897409974109741197412974139741497415974169741797418974199742097421974229742397424974259742697427974289742997430974319743297433974349743597436974379743897439974409744197442974439744497445974469744797448974499745097451974529745397454974559745697457974589745997460974619746297463974649746597466974679746897469974709747197472974739747497475974769747797478974799748097481974829748397484974859748697487974889748997490974919749297493974949749597496974979749897499975009750197502975039750497505975069750797508975099751097511975129751397514975159751697517975189751997520975219752297523975249752597526975279752897529975309753197532975339753497535975369753797538975399754097541975429754397544975459754697547975489754997550975519755297553975549755597556975579755897559975609756197562975639756497565975669756797568975699757097571975729757397574975759757697577975789757997580975819758297583975849758597586975879758897589975909759197592975939759497595975969759797598975999760097601976029760397604976059760697607976089760997610976119761297613976149761597616976179761897619976209762197622976239762497625976269762797628976299763097631976329763397634976359763697637976389763997640976419764297643976449764597646976479764897649976509765197652976539765497655976569765797658976599766097661976629766397664976659766697667976689766997670976719767297673976749767597676976779767897679976809768197682976839768497685976869768797688976899769097691976929769397694976959769697697976989769997700977019770297703977049770597706977079770897709977109771197712977139771497715977169771797718977199772097721977229772397724977259772697727977289772997730977319773297733977349773597736977379773897739977409774197742977439774497745977469774797748977499775097751977529775397754977559775697757977589775997760977619776297763977649776597766977679776897769977709777197772977739777497775977769777797778977799778097781977829778397784977859778697787977889778997790977919779297793977949779597796977979779897799978009780197802978039780497805978069780797808978099781097811978129781397814978159781697817978189781997820978219782297823978249782597826978279782897829978309783197832978339783497835978369783797838978399784097841978429784397844978459784697847978489784997850978519785297853978549785597856978579785897859978609786197862978639786497865978669786797868978699787097871978729787397874978759787697877978789787997880978819788297883978849788597886978879788897889978909789197892978939789497895978969789797898978999790097901979029790397904979059790697907979089790997910979119791297913979149791597916979179791897919979209792197922979239792497925979269792797928979299793097931979329793397934979359793697937979389793997940979419794297943979449794597946979479794897949979509795197952979539795497955979569795797958979599796097961979629796397964979659796697967979689796997970979719797297973979749797597976979779797897979979809798197982979839798497985979869798797988979899799097991979929799397994979959799697997979989799998000980019800298003980049800598006980079800898009980109801198012980139801498015980169801798018980199802098021980229802398024980259802698027980289802998030980319803298033980349803598036980379803898039980409804198042980439804498045980469804798048980499805098051980529805398054980559805698057980589805998060980619806298063980649806598066980679806898069980709807198072980739807498075980769807798078980799808098081980829808398084980859808698087980889808998090980919809298093980949809598096980979809898099981009810198102981039810498105981069810798108981099811098111981129811398114981159811698117981189811998120981219812298123981249812598126981279812898129981309813198132981339813498135981369813798138981399814098141981429814398144981459814698147981489814998150981519815298153981549815598156981579815898159981609816198162981639816498165981669816798168981699817098171981729817398174981759817698177981789817998180981819818298183981849818598186981879818898189981909819198192981939819498195981969819798198981999820098201982029820398204982059820698207982089820998210982119821298213982149821598216
  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. var scene = this._mesh.getScene();
  74. for (var index = 0; index < scene.meshes.length; index++) {
  75. var otherMesh = scene.meshes[index];
  76. if (!otherMesh.material) {
  77. continue;
  78. }
  79. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  80. continue;
  81. }
  82. if (otherMesh.material.getEffect() === effect) {
  83. otherMesh.computeBonesUsingShaders = false;
  84. }
  85. else {
  86. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  87. var subMesh = _a[_i];
  88. var subMeshEffect = subMesh.effect;
  89. if (subMeshEffect === effect) {
  90. otherMesh.computeBonesUsingShaders = false;
  91. break;
  92. }
  93. }
  94. }
  95. }
  96. }
  97. else {
  98. var currentFallbacks = this._defines[this._currentRank];
  99. if (currentFallbacks) {
  100. for (var index = 0; index < currentFallbacks.length; index++) {
  101. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  102. }
  103. }
  104. this._currentRank++;
  105. }
  106. return currentDefines;
  107. };
  108. return EffectFallbacks;
  109. }());
  110. BABYLON.EffectFallbacks = EffectFallbacks;
  111. /**
  112. * Options to be used when creating an effect.
  113. */
  114. var EffectCreationOptions = /** @class */ (function () {
  115. function EffectCreationOptions() {
  116. }
  117. return EffectCreationOptions;
  118. }());
  119. BABYLON.EffectCreationOptions = EffectCreationOptions;
  120. /**
  121. * Effect containing vertex and fragment shader that can be executed on an object.
  122. */
  123. var Effect = /** @class */ (function () {
  124. /**
  125. * Instantiates an effect.
  126. * An effect can be used to create/manage/execute vertex and fragment shaders.
  127. * @param baseName Name of the effect.
  128. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  129. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  130. * @param samplers List of sampler variables that will be passed to the shader.
  131. * @param engine Engine to be used to render the effect
  132. * @param defines Define statements to be added to the shader.
  133. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  134. * @param onCompiled Callback that will be called when the shader is compiled.
  135. * @param onError Callback that will be called if an error occurs during shader compilation.
  136. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  137. */
  138. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  139. if (samplers === void 0) { samplers = null; }
  140. if (defines === void 0) { defines = null; }
  141. if (fallbacks === void 0) { fallbacks = null; }
  142. if (onCompiled === void 0) { onCompiled = null; }
  143. if (onError === void 0) { onError = null; }
  144. var _this = this;
  145. /**
  146. * Unique ID of the effect.
  147. */
  148. this.uniqueId = 0;
  149. /**
  150. * Observable that will be called when the shader is compiled.
  151. */
  152. this.onCompileObservable = new BABYLON.Observable();
  153. /**
  154. * Observable that will be called if an error occurs during shader compilation.
  155. */
  156. this.onErrorObservable = new BABYLON.Observable();
  157. /**
  158. * Observable that will be called when effect is bound.
  159. */
  160. this.onBindObservable = new BABYLON.Observable();
  161. this._uniformBuffersNames = {};
  162. this._isReady = false;
  163. this._compilationError = "";
  164. this.name = baseName;
  165. if (attributesNamesOrOptions.attributes) {
  166. var options = attributesNamesOrOptions;
  167. this._engine = uniformsNamesOrEngine;
  168. this._attributesNames = options.attributes;
  169. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  170. this._samplers = options.samplers.slice();
  171. this.defines = options.defines;
  172. this.onError = options.onError;
  173. this.onCompiled = options.onCompiled;
  174. this._fallbacks = options.fallbacks;
  175. this._indexParameters = options.indexParameters;
  176. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  177. if (options.uniformBuffersNames) {
  178. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  179. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  180. }
  181. }
  182. }
  183. else {
  184. this._engine = engine;
  185. this.defines = defines;
  186. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  187. this._samplers = samplers ? samplers.slice() : [];
  188. this._attributesNames = attributesNamesOrOptions;
  189. this.onError = onError;
  190. this.onCompiled = onCompiled;
  191. this._indexParameters = indexParameters;
  192. this._fallbacks = fallbacks;
  193. }
  194. this.uniqueId = Effect._uniqueIdSeed++;
  195. var vertexSource;
  196. var fragmentSource;
  197. if (baseName.vertexElement) {
  198. vertexSource = document.getElementById(baseName.vertexElement);
  199. if (!vertexSource) {
  200. vertexSource = baseName.vertexElement;
  201. }
  202. }
  203. else {
  204. vertexSource = baseName.vertex || baseName;
  205. }
  206. if (baseName.fragmentElement) {
  207. fragmentSource = document.getElementById(baseName.fragmentElement);
  208. if (!fragmentSource) {
  209. fragmentSource = baseName.fragmentElement;
  210. }
  211. }
  212. else {
  213. fragmentSource = baseName.fragment || baseName;
  214. }
  215. this._loadVertexShader(vertexSource, function (vertexCode) {
  216. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  217. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  218. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  219. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  220. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  221. if (baseName) {
  222. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  223. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  224. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  225. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  226. }
  227. else {
  228. _this._vertexSourceCode = migratedVertexCode;
  229. _this._fragmentSourceCode = migratedFragmentCode;
  230. }
  231. _this._prepareEffect();
  232. });
  233. });
  234. });
  235. });
  236. });
  237. });
  238. }
  239. Object.defineProperty(Effect.prototype, "key", {
  240. /**
  241. * Unique key for this effect
  242. */
  243. get: function () {
  244. return this._key;
  245. },
  246. enumerable: true,
  247. configurable: true
  248. });
  249. /**
  250. * If the effect has been compiled and prepared.
  251. * @returns if the effect is compiled and prepared.
  252. */
  253. Effect.prototype.isReady = function () {
  254. return this._isReady;
  255. };
  256. /**
  257. * The engine the effect was initialized with.
  258. * @returns the engine.
  259. */
  260. Effect.prototype.getEngine = function () {
  261. return this._engine;
  262. };
  263. /**
  264. * The compiled webGL program for the effect
  265. * @returns the webGL program.
  266. */
  267. Effect.prototype.getProgram = function () {
  268. return this._program;
  269. };
  270. /**
  271. * The set of names of attribute variables for the shader.
  272. * @returns An array of attribute names.
  273. */
  274. Effect.prototype.getAttributesNames = function () {
  275. return this._attributesNames;
  276. };
  277. /**
  278. * Returns the attribute at the given index.
  279. * @param index The index of the attribute.
  280. * @returns The location of the attribute.
  281. */
  282. Effect.prototype.getAttributeLocation = function (index) {
  283. return this._attributes[index];
  284. };
  285. /**
  286. * Returns the attribute based on the name of the variable.
  287. * @param name of the attribute to look up.
  288. * @returns the attribute location.
  289. */
  290. Effect.prototype.getAttributeLocationByName = function (name) {
  291. var index = this._attributesNames.indexOf(name);
  292. return this._attributes[index];
  293. };
  294. /**
  295. * The number of attributes.
  296. * @returns the numnber of attributes.
  297. */
  298. Effect.prototype.getAttributesCount = function () {
  299. return this._attributes.length;
  300. };
  301. /**
  302. * Gets the index of a uniform variable.
  303. * @param uniformName of the uniform to look up.
  304. * @returns the index.
  305. */
  306. Effect.prototype.getUniformIndex = function (uniformName) {
  307. return this._uniformsNames.indexOf(uniformName);
  308. };
  309. /**
  310. * Returns the attribute based on the name of the variable.
  311. * @param uniformName of the uniform to look up.
  312. * @returns the location of the uniform.
  313. */
  314. Effect.prototype.getUniform = function (uniformName) {
  315. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  316. };
  317. /**
  318. * Returns an array of sampler variable names
  319. * @returns The array of sampler variable neames.
  320. */
  321. Effect.prototype.getSamplers = function () {
  322. return this._samplers;
  323. };
  324. /**
  325. * The error from the last compilation.
  326. * @returns the error string.
  327. */
  328. Effect.prototype.getCompilationError = function () {
  329. return this._compilationError;
  330. };
  331. /**
  332. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  333. * @param func The callback to be used.
  334. */
  335. Effect.prototype.executeWhenCompiled = function (func) {
  336. if (this.isReady()) {
  337. func(this);
  338. return;
  339. }
  340. this.onCompileObservable.add(function (effect) {
  341. func(effect);
  342. });
  343. };
  344. /** @hidden */
  345. Effect.prototype._loadVertexShader = function (vertex, callback) {
  346. if (BABYLON.Tools.IsWindowObjectExist()) {
  347. // DOM element ?
  348. if (vertex instanceof HTMLElement) {
  349. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  350. callback(vertexCode);
  351. return;
  352. }
  353. }
  354. // Base64 encoded ?
  355. if (vertex.substr(0, 7) === "base64:") {
  356. var vertexBinary = window.atob(vertex.substr(7));
  357. callback(vertexBinary);
  358. return;
  359. }
  360. // Is in local store ?
  361. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  362. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  363. return;
  364. }
  365. var vertexShaderUrl;
  366. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  367. vertexShaderUrl = vertex;
  368. }
  369. else {
  370. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  371. }
  372. // Vertex shader
  373. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  374. };
  375. /** @hidden */
  376. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  377. if (BABYLON.Tools.IsWindowObjectExist()) {
  378. // DOM element ?
  379. if (fragment instanceof HTMLElement) {
  380. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  381. callback(fragmentCode);
  382. return;
  383. }
  384. }
  385. // Base64 encoded ?
  386. if (fragment.substr(0, 7) === "base64:") {
  387. var fragmentBinary = window.atob(fragment.substr(7));
  388. callback(fragmentBinary);
  389. return;
  390. }
  391. // Is in local store ?
  392. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  393. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  394. return;
  395. }
  396. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  397. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  398. return;
  399. }
  400. var fragmentShaderUrl;
  401. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  402. fragmentShaderUrl = fragment;
  403. }
  404. else {
  405. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  406. }
  407. // Fragment shader
  408. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  409. };
  410. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  411. // Rebuild shaders source code
  412. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  413. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  414. vertexCode = prefix + vertexCode;
  415. fragmentCode = prefix + fragmentCode;
  416. // Number lines of shaders source code
  417. var i = 2;
  418. var regex = /\n/gm;
  419. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  420. i = 2;
  421. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  422. // Dump shaders name and formatted source code
  423. if (this.name.vertexElement) {
  424. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  425. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  426. }
  427. else if (this.name.vertex) {
  428. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  429. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  430. }
  431. else {
  432. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  433. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  434. }
  435. };
  436. ;
  437. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  438. var preparedSourceCode = this._processPrecision(sourceCode);
  439. if (this._engine.webGLVersion == 1) {
  440. callback(preparedSourceCode);
  441. return;
  442. }
  443. // Already converted
  444. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  445. callback(preparedSourceCode.replace("#version 300 es", ""));
  446. return;
  447. }
  448. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  449. // Remove extensions
  450. // #extension GL_OES_standard_derivatives : enable
  451. // #extension GL_EXT_shader_texture_lod : enable
  452. // #extension GL_EXT_frag_depth : enable
  453. // #extension GL_EXT_draw_buffers : require
  454. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  455. var result = preparedSourceCode.replace(regex, "");
  456. // Migrate to GLSL v300
  457. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  458. result = result.replace(/attribute[ \t]/g, "in ");
  459. result = result.replace(/[ \t]attribute/g, " in");
  460. if (isFragment) {
  461. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  462. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  463. result = result.replace(/texture2D\s*\(/g, "texture(");
  464. result = result.replace(/textureCube\s*\(/g, "texture(");
  465. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  466. result = result.replace(/gl_FragColor/g, "glFragColor");
  467. result = result.replace(/gl_FragData/g, "glFragData");
  468. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  469. }
  470. callback(result);
  471. };
  472. Effect.prototype._processIncludes = function (sourceCode, callback) {
  473. var _this = this;
  474. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  475. var match = regex.exec(sourceCode);
  476. var returnValue = new String(sourceCode);
  477. while (match != null) {
  478. var includeFile = match[1];
  479. // Uniform declaration
  480. if (includeFile.indexOf("__decl__") !== -1) {
  481. includeFile = includeFile.replace(/__decl__/, "");
  482. if (this._engine.supportsUniformBuffers) {
  483. includeFile = includeFile.replace(/Vertex/, "Ubo");
  484. includeFile = includeFile.replace(/Fragment/, "Ubo");
  485. }
  486. includeFile = includeFile + "Declaration";
  487. }
  488. if (Effect.IncludesShadersStore[includeFile]) {
  489. // Substitution
  490. var includeContent = Effect.IncludesShadersStore[includeFile];
  491. if (match[2]) {
  492. var splits = match[3].split(",");
  493. for (var index = 0; index < splits.length; index += 2) {
  494. var source = new RegExp(splits[index], "g");
  495. var dest = splits[index + 1];
  496. includeContent = includeContent.replace(source, dest);
  497. }
  498. }
  499. if (match[4]) {
  500. var indexString = match[5];
  501. if (indexString.indexOf("..") !== -1) {
  502. var indexSplits = indexString.split("..");
  503. var minIndex = parseInt(indexSplits[0]);
  504. var maxIndex = parseInt(indexSplits[1]);
  505. var sourceIncludeContent = includeContent.slice(0);
  506. includeContent = "";
  507. if (isNaN(maxIndex)) {
  508. maxIndex = this._indexParameters[indexSplits[1]];
  509. }
  510. for (var i = minIndex; i < maxIndex; i++) {
  511. if (!this._engine.supportsUniformBuffers) {
  512. // Ubo replacement
  513. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  514. return p1 + "{X}";
  515. });
  516. }
  517. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  518. }
  519. }
  520. else {
  521. if (!this._engine.supportsUniformBuffers) {
  522. // Ubo replacement
  523. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  524. return p1 + "{X}";
  525. });
  526. }
  527. includeContent = includeContent.replace(/\{X\}/g, indexString);
  528. }
  529. }
  530. // Replace
  531. returnValue = returnValue.replace(match[0], includeContent);
  532. }
  533. else {
  534. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  535. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  536. Effect.IncludesShadersStore[includeFile] = fileContent;
  537. _this._processIncludes(returnValue, callback);
  538. });
  539. return;
  540. }
  541. match = regex.exec(sourceCode);
  542. }
  543. callback(returnValue);
  544. };
  545. Effect.prototype._processPrecision = function (source) {
  546. if (source.indexOf("precision highp float") === -1) {
  547. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  548. source = "precision mediump float;\n" + source;
  549. }
  550. else {
  551. source = "precision highp float;\n" + source;
  552. }
  553. }
  554. else {
  555. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  556. source = source.replace("precision highp float", "precision mediump float");
  557. }
  558. }
  559. return source;
  560. };
  561. /**
  562. * Recompiles the webGL program
  563. * @param vertexSourceCode The source code for the vertex shader.
  564. * @param fragmentSourceCode The source code for the fragment shader.
  565. * @param onCompiled Callback called when completed.
  566. * @param onError Callback called on error.
  567. */
  568. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  569. var _this = this;
  570. this._isReady = false;
  571. this._vertexSourceCodeOverride = vertexSourceCode;
  572. this._fragmentSourceCodeOverride = fragmentSourceCode;
  573. this.onError = function (effect, error) {
  574. if (onError) {
  575. onError(error);
  576. }
  577. };
  578. this.onCompiled = function () {
  579. var scenes = _this.getEngine().scenes;
  580. for (var i = 0; i < scenes.length; i++) {
  581. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  582. }
  583. if (onCompiled) {
  584. onCompiled(_this._program);
  585. }
  586. };
  587. this._fallbacks = null;
  588. this._prepareEffect();
  589. };
  590. /**
  591. * Gets the uniform locations of the the specified variable names
  592. * @param names THe names of the variables to lookup.
  593. * @returns Array of locations in the same order as variable names.
  594. */
  595. Effect.prototype.getSpecificUniformLocations = function (names) {
  596. var engine = this._engine;
  597. return engine.getUniforms(this._program, names);
  598. };
  599. /**
  600. * Prepares the effect
  601. */
  602. Effect.prototype._prepareEffect = function () {
  603. var attributesNames = this._attributesNames;
  604. var defines = this.defines;
  605. var fallbacks = this._fallbacks;
  606. this._valueCache = {};
  607. var previousProgram = this._program;
  608. try {
  609. var engine = this._engine;
  610. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  611. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  612. }
  613. else {
  614. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  615. }
  616. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  617. if (engine.supportsUniformBuffers) {
  618. for (var name in this._uniformBuffersNames) {
  619. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  620. }
  621. }
  622. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  623. this._attributes = engine.getAttributes(this._program, attributesNames);
  624. var index;
  625. for (index = 0; index < this._samplers.length; index++) {
  626. var sampler = this.getUniform(this._samplers[index]);
  627. if (sampler == null) {
  628. this._samplers.splice(index, 1);
  629. index--;
  630. }
  631. }
  632. engine.bindSamplers(this);
  633. this._compilationError = "";
  634. this._isReady = true;
  635. if (this.onCompiled) {
  636. this.onCompiled(this);
  637. }
  638. this.onCompileObservable.notifyObservers(this);
  639. this.onCompileObservable.clear();
  640. // Unbind mesh reference in fallbacks
  641. if (this._fallbacks) {
  642. this._fallbacks.unBindMesh();
  643. }
  644. if (previousProgram) {
  645. this.getEngine()._deleteProgram(previousProgram);
  646. }
  647. }
  648. catch (e) {
  649. this._compilationError = e.message;
  650. // Let's go through fallbacks then
  651. BABYLON.Tools.Error("Unable to compile effect:");
  652. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  653. return " " + uniform;
  654. }));
  655. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  656. return " " + attribute;
  657. }));
  658. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  659. BABYLON.Tools.Error("Error: " + this._compilationError);
  660. if (previousProgram) {
  661. this._program = previousProgram;
  662. this._isReady = true;
  663. if (this.onError) {
  664. this.onError(this, this._compilationError);
  665. }
  666. this.onErrorObservable.notifyObservers(this);
  667. }
  668. if (fallbacks && fallbacks.isMoreFallbacks) {
  669. BABYLON.Tools.Error("Trying next fallback.");
  670. this.defines = fallbacks.reduce(this.defines, this);
  671. this._prepareEffect();
  672. }
  673. else { // Sorry we did everything we can
  674. if (this.onError) {
  675. this.onError(this, this._compilationError);
  676. }
  677. this.onErrorObservable.notifyObservers(this);
  678. this.onErrorObservable.clear();
  679. // Unbind mesh reference in fallbacks
  680. if (this._fallbacks) {
  681. this._fallbacks.unBindMesh();
  682. }
  683. }
  684. }
  685. };
  686. Object.defineProperty(Effect.prototype, "isSupported", {
  687. /**
  688. * Checks if the effect is supported. (Must be called after compilation)
  689. */
  690. get: function () {
  691. return this._compilationError === "";
  692. },
  693. enumerable: true,
  694. configurable: true
  695. });
  696. /**
  697. * Binds a texture to the engine to be used as output of the shader.
  698. * @param channel Name of the output variable.
  699. * @param texture Texture to bind.
  700. */
  701. Effect.prototype._bindTexture = function (channel, texture) {
  702. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  703. };
  704. /**
  705. * Sets a texture on the engine to be used in the shader.
  706. * @param channel Name of the sampler variable.
  707. * @param texture Texture to set.
  708. */
  709. Effect.prototype.setTexture = function (channel, texture) {
  710. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  711. };
  712. /**
  713. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  714. * @param channel Name of the sampler variable.
  715. * @param texture Texture to set.
  716. */
  717. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  718. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  719. };
  720. /**
  721. * Sets an array of textures on the engine to be used in the shader.
  722. * @param channel Name of the variable.
  723. * @param textures Textures to set.
  724. */
  725. Effect.prototype.setTextureArray = function (channel, textures) {
  726. if (this._samplers.indexOf(channel + "Ex") === -1) {
  727. var initialPos = this._samplers.indexOf(channel);
  728. for (var index = 1; index < textures.length; index++) {
  729. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  730. }
  731. }
  732. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  733. };
  734. /**
  735. * 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)
  736. * @param channel Name of the sampler variable.
  737. * @param postProcess Post process to get the input texture from.
  738. */
  739. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  740. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  741. };
  742. /**
  743. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  744. * 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)
  745. * @param channel Name of the sampler variable.
  746. * @param postProcess Post process to get the output texture from.
  747. */
  748. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  749. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  750. };
  751. /** @hidden */
  752. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  753. var cache = this._valueCache[uniformName];
  754. var flag = matrix.updateFlag;
  755. if (cache !== undefined && cache === flag) {
  756. return false;
  757. }
  758. this._valueCache[uniformName] = flag;
  759. return true;
  760. };
  761. /** @hidden */
  762. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  763. var cache = this._valueCache[uniformName];
  764. if (!cache) {
  765. cache = [x, y];
  766. this._valueCache[uniformName] = cache;
  767. return true;
  768. }
  769. var changed = false;
  770. if (cache[0] !== x) {
  771. cache[0] = x;
  772. changed = true;
  773. }
  774. if (cache[1] !== y) {
  775. cache[1] = y;
  776. changed = true;
  777. }
  778. return changed;
  779. };
  780. /** @hidden */
  781. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  782. var cache = this._valueCache[uniformName];
  783. if (!cache) {
  784. cache = [x, y, z];
  785. this._valueCache[uniformName] = cache;
  786. return true;
  787. }
  788. var changed = false;
  789. if (cache[0] !== x) {
  790. cache[0] = x;
  791. changed = true;
  792. }
  793. if (cache[1] !== y) {
  794. cache[1] = y;
  795. changed = true;
  796. }
  797. if (cache[2] !== z) {
  798. cache[2] = z;
  799. changed = true;
  800. }
  801. return changed;
  802. };
  803. /** @hidden */
  804. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  805. var cache = this._valueCache[uniformName];
  806. if (!cache) {
  807. cache = [x, y, z, w];
  808. this._valueCache[uniformName] = cache;
  809. return true;
  810. }
  811. var changed = false;
  812. if (cache[0] !== x) {
  813. cache[0] = x;
  814. changed = true;
  815. }
  816. if (cache[1] !== y) {
  817. cache[1] = y;
  818. changed = true;
  819. }
  820. if (cache[2] !== z) {
  821. cache[2] = z;
  822. changed = true;
  823. }
  824. if (cache[3] !== w) {
  825. cache[3] = w;
  826. changed = true;
  827. }
  828. return changed;
  829. };
  830. /**
  831. * Binds a buffer to a uniform.
  832. * @param buffer Buffer to bind.
  833. * @param name Name of the uniform variable to bind to.
  834. */
  835. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  836. var bufferName = this._uniformBuffersNames[name];
  837. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  838. return;
  839. }
  840. Effect._baseCache[bufferName] = buffer;
  841. this._engine.bindUniformBufferBase(buffer, bufferName);
  842. };
  843. /**
  844. * Binds block to a uniform.
  845. * @param blockName Name of the block to bind.
  846. * @param index Index to bind.
  847. */
  848. Effect.prototype.bindUniformBlock = function (blockName, index) {
  849. this._engine.bindUniformBlock(this._program, blockName, index);
  850. };
  851. /**
  852. * Sets an interger value on a uniform variable.
  853. * @param uniformName Name of the variable.
  854. * @param value Value to be set.
  855. * @returns this effect.
  856. */
  857. Effect.prototype.setInt = function (uniformName, value) {
  858. var cache = this._valueCache[uniformName];
  859. if (cache !== undefined && cache === value)
  860. return this;
  861. this._valueCache[uniformName] = value;
  862. this._engine.setInt(this.getUniform(uniformName), value);
  863. return this;
  864. };
  865. /**
  866. * Sets an int array on a uniform variable.
  867. * @param uniformName Name of the variable.
  868. * @param array array to be set.
  869. * @returns this effect.
  870. */
  871. Effect.prototype.setIntArray = function (uniformName, array) {
  872. this._valueCache[uniformName] = null;
  873. this._engine.setIntArray(this.getUniform(uniformName), array);
  874. return this;
  875. };
  876. /**
  877. * 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)
  878. * @param uniformName Name of the variable.
  879. * @param array array to be set.
  880. * @returns this effect.
  881. */
  882. Effect.prototype.setIntArray2 = function (uniformName, array) {
  883. this._valueCache[uniformName] = null;
  884. this._engine.setIntArray2(this.getUniform(uniformName), array);
  885. return this;
  886. };
  887. /**
  888. * 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)
  889. * @param uniformName Name of the variable.
  890. * @param array array to be set.
  891. * @returns this effect.
  892. */
  893. Effect.prototype.setIntArray3 = function (uniformName, array) {
  894. this._valueCache[uniformName] = null;
  895. this._engine.setIntArray3(this.getUniform(uniformName), array);
  896. return this;
  897. };
  898. /**
  899. * 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)
  900. * @param uniformName Name of the variable.
  901. * @param array array to be set.
  902. * @returns this effect.
  903. */
  904. Effect.prototype.setIntArray4 = function (uniformName, array) {
  905. this._valueCache[uniformName] = null;
  906. this._engine.setIntArray4(this.getUniform(uniformName), array);
  907. return this;
  908. };
  909. /**
  910. * Sets an float array on a uniform variable.
  911. * @param uniformName Name of the variable.
  912. * @param array array to be set.
  913. * @returns this effect.
  914. */
  915. Effect.prototype.setFloatArray = function (uniformName, array) {
  916. this._valueCache[uniformName] = null;
  917. this._engine.setFloatArray(this.getUniform(uniformName), array);
  918. return this;
  919. };
  920. /**
  921. * 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)
  922. * @param uniformName Name of the variable.
  923. * @param array array to be set.
  924. * @returns this effect.
  925. */
  926. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  927. this._valueCache[uniformName] = null;
  928. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  929. return this;
  930. };
  931. /**
  932. * 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)
  933. * @param uniformName Name of the variable.
  934. * @param array array to be set.
  935. * @returns this effect.
  936. */
  937. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  938. this._valueCache[uniformName] = null;
  939. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  940. return this;
  941. };
  942. /**
  943. * 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)
  944. * @param uniformName Name of the variable.
  945. * @param array array to be set.
  946. * @returns this effect.
  947. */
  948. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  949. this._valueCache[uniformName] = null;
  950. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  951. return this;
  952. };
  953. /**
  954. * Sets an array on a uniform variable.
  955. * @param uniformName Name of the variable.
  956. * @param array array to be set.
  957. * @returns this effect.
  958. */
  959. Effect.prototype.setArray = function (uniformName, array) {
  960. this._valueCache[uniformName] = null;
  961. this._engine.setArray(this.getUniform(uniformName), array);
  962. return this;
  963. };
  964. /**
  965. * 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)
  966. * @param uniformName Name of the variable.
  967. * @param array array to be set.
  968. * @returns this effect.
  969. */
  970. Effect.prototype.setArray2 = function (uniformName, array) {
  971. this._valueCache[uniformName] = null;
  972. this._engine.setArray2(this.getUniform(uniformName), array);
  973. return this;
  974. };
  975. /**
  976. * 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)
  977. * @param uniformName Name of the variable.
  978. * @param array array to be set.
  979. * @returns this effect.
  980. */
  981. Effect.prototype.setArray3 = function (uniformName, array) {
  982. this._valueCache[uniformName] = null;
  983. this._engine.setArray3(this.getUniform(uniformName), array);
  984. return this;
  985. };
  986. /**
  987. * 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)
  988. * @param uniformName Name of the variable.
  989. * @param array array to be set.
  990. * @returns this effect.
  991. */
  992. Effect.prototype.setArray4 = function (uniformName, array) {
  993. this._valueCache[uniformName] = null;
  994. this._engine.setArray4(this.getUniform(uniformName), array);
  995. return this;
  996. };
  997. /**
  998. * Sets matrices on a uniform variable.
  999. * @param uniformName Name of the variable.
  1000. * @param matrices matrices to be set.
  1001. * @returns this effect.
  1002. */
  1003. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1004. if (!matrices) {
  1005. return this;
  1006. }
  1007. this._valueCache[uniformName] = null;
  1008. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1009. return this;
  1010. };
  1011. /**
  1012. * Sets matrix on a uniform variable.
  1013. * @param uniformName Name of the variable.
  1014. * @param matrix matrix to be set.
  1015. * @returns this effect.
  1016. */
  1017. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1018. if (this._cacheMatrix(uniformName, matrix)) {
  1019. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1020. }
  1021. return this;
  1022. };
  1023. /**
  1024. * 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)
  1025. * @param uniformName Name of the variable.
  1026. * @param matrix matrix to be set.
  1027. * @returns this effect.
  1028. */
  1029. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1030. this._valueCache[uniformName] = null;
  1031. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1032. return this;
  1033. };
  1034. /**
  1035. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1036. * @param uniformName Name of the variable.
  1037. * @param matrix matrix to be set.
  1038. * @returns this effect.
  1039. */
  1040. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1041. this._valueCache[uniformName] = null;
  1042. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1043. return this;
  1044. };
  1045. /**
  1046. * Sets a float on a uniform variable.
  1047. * @param uniformName Name of the variable.
  1048. * @param value value to be set.
  1049. * @returns this effect.
  1050. */
  1051. Effect.prototype.setFloat = function (uniformName, value) {
  1052. var cache = this._valueCache[uniformName];
  1053. if (cache !== undefined && cache === value)
  1054. return this;
  1055. this._valueCache[uniformName] = value;
  1056. this._engine.setFloat(this.getUniform(uniformName), value);
  1057. return this;
  1058. };
  1059. /**
  1060. * Sets a boolean on a uniform variable.
  1061. * @param uniformName Name of the variable.
  1062. * @param bool value to be set.
  1063. * @returns this effect.
  1064. */
  1065. Effect.prototype.setBool = function (uniformName, bool) {
  1066. var cache = this._valueCache[uniformName];
  1067. if (cache !== undefined && cache === bool)
  1068. return this;
  1069. this._valueCache[uniformName] = bool;
  1070. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1071. return this;
  1072. };
  1073. /**
  1074. * Sets a Vector2 on a uniform variable.
  1075. * @param uniformName Name of the variable.
  1076. * @param vector2 vector2 to be set.
  1077. * @returns this effect.
  1078. */
  1079. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1080. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1081. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1082. }
  1083. return this;
  1084. };
  1085. /**
  1086. * Sets a float2 on a uniform variable.
  1087. * @param uniformName Name of the variable.
  1088. * @param x First float in float2.
  1089. * @param y Second float in float2.
  1090. * @returns this effect.
  1091. */
  1092. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1093. if (this._cacheFloat2(uniformName, x, y)) {
  1094. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1095. }
  1096. return this;
  1097. };
  1098. /**
  1099. * Sets a Vector3 on a uniform variable.
  1100. * @param uniformName Name of the variable.
  1101. * @param vector3 Value to be set.
  1102. * @returns this effect.
  1103. */
  1104. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1105. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1106. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1107. }
  1108. return this;
  1109. };
  1110. /**
  1111. * Sets a float3 on a uniform variable.
  1112. * @param uniformName Name of the variable.
  1113. * @param x First float in float3.
  1114. * @param y Second float in float3.
  1115. * @param z Third float in float3.
  1116. * @returns this effect.
  1117. */
  1118. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1119. if (this._cacheFloat3(uniformName, x, y, z)) {
  1120. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1121. }
  1122. return this;
  1123. };
  1124. /**
  1125. * Sets a Vector4 on a uniform variable.
  1126. * @param uniformName Name of the variable.
  1127. * @param vector4 Value to be set.
  1128. * @returns this effect.
  1129. */
  1130. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1131. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1132. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1133. }
  1134. return this;
  1135. };
  1136. /**
  1137. * Sets a float4 on a uniform variable.
  1138. * @param uniformName Name of the variable.
  1139. * @param x First float in float4.
  1140. * @param y Second float in float4.
  1141. * @param z Third float in float4.
  1142. * @param w Fourth float in float4.
  1143. * @returns this effect.
  1144. */
  1145. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1146. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1147. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1148. }
  1149. return this;
  1150. };
  1151. /**
  1152. * Sets a Color3 on a uniform variable.
  1153. * @param uniformName Name of the variable.
  1154. * @param color3 Value to be set.
  1155. * @returns this effect.
  1156. */
  1157. Effect.prototype.setColor3 = function (uniformName, color3) {
  1158. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1159. this._engine.setColor3(this.getUniform(uniformName), color3);
  1160. }
  1161. return this;
  1162. };
  1163. /**
  1164. * Sets a Color4 on a uniform variable.
  1165. * @param uniformName Name of the variable.
  1166. * @param color3 Value to be set.
  1167. * @param alpha Alpha value to be set.
  1168. * @returns this effect.
  1169. */
  1170. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1171. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1172. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1173. }
  1174. return this;
  1175. };
  1176. /**
  1177. * Sets a Color4 on a uniform variable
  1178. * @param uniformName defines the name of the variable
  1179. * @param color4 defines the value to be set
  1180. * @returns this effect.
  1181. */
  1182. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1183. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1184. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1185. }
  1186. return this;
  1187. };
  1188. /**
  1189. * Resets the cache of effects.
  1190. */
  1191. Effect.ResetCache = function () {
  1192. Effect._baseCache = {};
  1193. };
  1194. Effect._uniqueIdSeed = 0;
  1195. Effect._baseCache = {};
  1196. /**
  1197. * Store of each shader (The can be looked up using effect.key)
  1198. */
  1199. Effect.ShadersStore = {};
  1200. /**
  1201. * Store of each included file for a shader (The can be looked up using effect.key)
  1202. */
  1203. Effect.IncludesShadersStore = {};
  1204. return Effect;
  1205. }());
  1206. BABYLON.Effect = Effect;
  1207. })(BABYLON || (BABYLON = {}));
  1208. //# sourceMappingURL=babylon.effect.js.map
  1209. //# sourceMappingURL=babylon.types.js.map
  1210. var BABYLON;
  1211. (function (BABYLON) {
  1212. var KeyboardEventTypes = /** @class */ (function () {
  1213. function KeyboardEventTypes() {
  1214. }
  1215. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1216. get: function () {
  1217. return KeyboardEventTypes._KEYDOWN;
  1218. },
  1219. enumerable: true,
  1220. configurable: true
  1221. });
  1222. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1223. get: function () {
  1224. return KeyboardEventTypes._KEYUP;
  1225. },
  1226. enumerable: true,
  1227. configurable: true
  1228. });
  1229. KeyboardEventTypes._KEYDOWN = 0x01;
  1230. KeyboardEventTypes._KEYUP = 0x02;
  1231. return KeyboardEventTypes;
  1232. }());
  1233. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1234. var KeyboardInfo = /** @class */ (function () {
  1235. function KeyboardInfo(type, event) {
  1236. this.type = type;
  1237. this.event = event;
  1238. }
  1239. return KeyboardInfo;
  1240. }());
  1241. BABYLON.KeyboardInfo = KeyboardInfo;
  1242. /**
  1243. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1244. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1245. */
  1246. var KeyboardInfoPre = /** @class */ (function (_super) {
  1247. __extends(KeyboardInfoPre, _super);
  1248. function KeyboardInfoPre(type, event) {
  1249. var _this = _super.call(this, type, event) || this;
  1250. _this.skipOnPointerObservable = false;
  1251. return _this;
  1252. }
  1253. return KeyboardInfoPre;
  1254. }(KeyboardInfo));
  1255. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1256. })(BABYLON || (BABYLON = {}));
  1257. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1258. var BABYLON;
  1259. (function (BABYLON) {
  1260. var PointerEventTypes = /** @class */ (function () {
  1261. function PointerEventTypes() {
  1262. }
  1263. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1264. get: function () {
  1265. return PointerEventTypes._POINTERDOWN;
  1266. },
  1267. enumerable: true,
  1268. configurable: true
  1269. });
  1270. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1271. get: function () {
  1272. return PointerEventTypes._POINTERUP;
  1273. },
  1274. enumerable: true,
  1275. configurable: true
  1276. });
  1277. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1278. get: function () {
  1279. return PointerEventTypes._POINTERMOVE;
  1280. },
  1281. enumerable: true,
  1282. configurable: true
  1283. });
  1284. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1285. get: function () {
  1286. return PointerEventTypes._POINTERWHEEL;
  1287. },
  1288. enumerable: true,
  1289. configurable: true
  1290. });
  1291. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1292. get: function () {
  1293. return PointerEventTypes._POINTERPICK;
  1294. },
  1295. enumerable: true,
  1296. configurable: true
  1297. });
  1298. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1299. get: function () {
  1300. return PointerEventTypes._POINTERTAP;
  1301. },
  1302. enumerable: true,
  1303. configurable: true
  1304. });
  1305. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1306. get: function () {
  1307. return PointerEventTypes._POINTERDOUBLETAP;
  1308. },
  1309. enumerable: true,
  1310. configurable: true
  1311. });
  1312. PointerEventTypes._POINTERDOWN = 0x01;
  1313. PointerEventTypes._POINTERUP = 0x02;
  1314. PointerEventTypes._POINTERMOVE = 0x04;
  1315. PointerEventTypes._POINTERWHEEL = 0x08;
  1316. PointerEventTypes._POINTERPICK = 0x10;
  1317. PointerEventTypes._POINTERTAP = 0x20;
  1318. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1319. return PointerEventTypes;
  1320. }());
  1321. BABYLON.PointerEventTypes = PointerEventTypes;
  1322. var PointerInfoBase = /** @class */ (function () {
  1323. function PointerInfoBase(type, event) {
  1324. this.type = type;
  1325. this.event = event;
  1326. }
  1327. return PointerInfoBase;
  1328. }());
  1329. BABYLON.PointerInfoBase = PointerInfoBase;
  1330. /**
  1331. * This class is used to store pointer related info for the onPrePointerObservable event.
  1332. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1333. */
  1334. var PointerInfoPre = /** @class */ (function (_super) {
  1335. __extends(PointerInfoPre, _super);
  1336. function PointerInfoPre(type, event, localX, localY) {
  1337. var _this = _super.call(this, type, event) || this;
  1338. _this.skipOnPointerObservable = false;
  1339. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1340. return _this;
  1341. }
  1342. return PointerInfoPre;
  1343. }(PointerInfoBase));
  1344. BABYLON.PointerInfoPre = PointerInfoPre;
  1345. /**
  1346. * This type contains all the data related to a pointer event in Babylon.js.
  1347. * 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.
  1348. */
  1349. var PointerInfo = /** @class */ (function (_super) {
  1350. __extends(PointerInfo, _super);
  1351. function PointerInfo(type, event, pickInfo) {
  1352. var _this = _super.call(this, type, event) || this;
  1353. _this.pickInfo = pickInfo;
  1354. return _this;
  1355. }
  1356. return PointerInfo;
  1357. }(PointerInfoBase));
  1358. BABYLON.PointerInfo = PointerInfo;
  1359. })(BABYLON || (BABYLON = {}));
  1360. //# sourceMappingURL=babylon.pointerEvents.js.map
  1361. var BABYLON;
  1362. (function (BABYLON) {
  1363. BABYLON.ToGammaSpace = 1 / 2.2;
  1364. BABYLON.ToLinearSpace = 2.2;
  1365. BABYLON.Epsilon = 0.001;
  1366. /**
  1367. * Class used to hold a RBG color
  1368. */
  1369. var Color3 = /** @class */ (function () {
  1370. /**
  1371. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1372. * @param r defines the red component (between 0 and 1, default is 0)
  1373. * @param g defines the green component (between 0 and 1, default is 0)
  1374. * @param b defines the blue component (between 0 and 1, default is 0)
  1375. */
  1376. function Color3(
  1377. /**
  1378. * Defines the red component (between 0 and 1, default is 0)
  1379. */
  1380. r,
  1381. /**
  1382. * Defines the green component (between 0 and 1, default is 0)
  1383. */
  1384. g,
  1385. /**
  1386. * Defines the blue component (between 0 and 1, default is 0)
  1387. */
  1388. b) {
  1389. if (r === void 0) { r = 0; }
  1390. if (g === void 0) { g = 0; }
  1391. if (b === void 0) { b = 0; }
  1392. this.r = r;
  1393. this.g = g;
  1394. this.b = b;
  1395. }
  1396. /**
  1397. * Creates a string with the Color3 current values
  1398. * @returns the string representation of the Color3 object
  1399. */
  1400. Color3.prototype.toString = function () {
  1401. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1402. };
  1403. /**
  1404. * Returns the string "Color3"
  1405. * @returns "Color3"
  1406. */
  1407. Color3.prototype.getClassName = function () {
  1408. return "Color3";
  1409. };
  1410. /**
  1411. * Compute the Color3 hash code
  1412. * @returns an unique number that can be used to hash Color3 objects
  1413. */
  1414. Color3.prototype.getHashCode = function () {
  1415. var hash = this.r || 0;
  1416. hash = (hash * 397) ^ (this.g || 0);
  1417. hash = (hash * 397) ^ (this.b || 0);
  1418. return hash;
  1419. };
  1420. // Operators
  1421. /**
  1422. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1423. * @param array defines the array where to store the r,g,b components
  1424. * @param index defines an optional index in the target array to define where to start storing values
  1425. * @returns the current Color3 object
  1426. */
  1427. Color3.prototype.toArray = function (array, index) {
  1428. if (index === undefined) {
  1429. index = 0;
  1430. }
  1431. array[index] = this.r;
  1432. array[index + 1] = this.g;
  1433. array[index + 2] = this.b;
  1434. return this;
  1435. };
  1436. /**
  1437. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1438. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1439. * @returns a new {BABYLON.Color4} object
  1440. */
  1441. Color3.prototype.toColor4 = function (alpha) {
  1442. if (alpha === void 0) { alpha = 1; }
  1443. return new Color4(this.r, this.g, this.b, alpha);
  1444. };
  1445. /**
  1446. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1447. * @returns the new array
  1448. */
  1449. Color3.prototype.asArray = function () {
  1450. var result = new Array();
  1451. this.toArray(result, 0);
  1452. return result;
  1453. };
  1454. /**
  1455. * Returns the luminance value
  1456. * @returns a float value
  1457. */
  1458. Color3.prototype.toLuminance = function () {
  1459. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1460. };
  1461. /**
  1462. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1463. * @param otherColor defines the second operand
  1464. * @returns the new Color3 object
  1465. */
  1466. Color3.prototype.multiply = function (otherColor) {
  1467. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1468. };
  1469. /**
  1470. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1471. * @param otherColor defines the second operand
  1472. * @param result defines the Color3 object where to store the result
  1473. * @returns the current Color3
  1474. */
  1475. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1476. result.r = this.r * otherColor.r;
  1477. result.g = this.g * otherColor.g;
  1478. result.b = this.b * otherColor.b;
  1479. return this;
  1480. };
  1481. /**
  1482. * Determines equality between Color3 objects
  1483. * @param otherColor defines the second operand
  1484. * @returns true if the rgb values are equal to the given ones
  1485. */
  1486. Color3.prototype.equals = function (otherColor) {
  1487. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1488. };
  1489. /**
  1490. * Determines equality between the current Color3 object and a set of r,b,g values
  1491. * @param r defines the red component to check
  1492. * @param g defines the green component to check
  1493. * @param b defines the blue component to check
  1494. * @returns true if the rgb values are equal to the given ones
  1495. */
  1496. Color3.prototype.equalsFloats = function (r, g, b) {
  1497. return this.r === r && this.g === g && this.b === b;
  1498. };
  1499. /**
  1500. * Multiplies in place each rgb value by scale
  1501. * @param scale defines the scaling factor
  1502. * @returns the updated Color3
  1503. */
  1504. Color3.prototype.scale = function (scale) {
  1505. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1506. };
  1507. /**
  1508. * Multiplies the rgb values by scale and stores the result into "result"
  1509. * @param scale defines the scaling factor
  1510. * @param result defines the Color3 object where to store the result
  1511. * @returns the unmodified current Color3
  1512. */
  1513. Color3.prototype.scaleToRef = function (scale, result) {
  1514. result.r = this.r * scale;
  1515. result.g = this.g * scale;
  1516. result.b = this.b * scale;
  1517. return this;
  1518. };
  1519. /**
  1520. * Scale the current Color3 values by a factor and add the result to a given Color3
  1521. * @param scale defines the scale factor
  1522. * @param result defines color to store the result into
  1523. * @returns the unmodified current Color3
  1524. */
  1525. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1526. result.r += this.r * scale;
  1527. result.g += this.g * scale;
  1528. result.b += this.b * scale;
  1529. return this;
  1530. };
  1531. /**
  1532. * Clamps the rgb values by the min and max values and stores the result into "result"
  1533. * @param min defines minimum clamping value (default is 0)
  1534. * @param max defines maximum clamping value (default is 1)
  1535. * @param result defines color to store the result into
  1536. * @returns the original Color3
  1537. */
  1538. Color3.prototype.clampToRef = function (min, max, result) {
  1539. if (min === void 0) { min = 0; }
  1540. if (max === void 0) { max = 1; }
  1541. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1542. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1543. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1544. return this;
  1545. };
  1546. /**
  1547. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1548. * @param otherColor defines the second operand
  1549. * @returns the new Color3
  1550. */
  1551. Color3.prototype.add = function (otherColor) {
  1552. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1553. };
  1554. /**
  1555. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1556. * @param otherColor defines the second operand
  1557. * @param result defines Color3 object to store the result into
  1558. * @returns the unmodified current Color3
  1559. */
  1560. Color3.prototype.addToRef = function (otherColor, result) {
  1561. result.r = this.r + otherColor.r;
  1562. result.g = this.g + otherColor.g;
  1563. result.b = this.b + otherColor.b;
  1564. return this;
  1565. };
  1566. /**
  1567. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1568. * @param otherColor defines the second operand
  1569. * @returns the new Color3
  1570. */
  1571. Color3.prototype.subtract = function (otherColor) {
  1572. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1573. };
  1574. /**
  1575. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1576. * @param otherColor defines the second operand
  1577. * @param result defines Color3 object to store the result into
  1578. * @returns the unmodified current Color3
  1579. */
  1580. Color3.prototype.subtractToRef = function (otherColor, result) {
  1581. result.r = this.r - otherColor.r;
  1582. result.g = this.g - otherColor.g;
  1583. result.b = this.b - otherColor.b;
  1584. return this;
  1585. };
  1586. /**
  1587. * Copy the current object
  1588. * @returns a new Color3 copied the current one
  1589. */
  1590. Color3.prototype.clone = function () {
  1591. return new Color3(this.r, this.g, this.b);
  1592. };
  1593. /**
  1594. * Copies the rgb values from the source in the current Color3
  1595. * @param source defines the source Color3 object
  1596. * @returns the updated Color3 object
  1597. */
  1598. Color3.prototype.copyFrom = function (source) {
  1599. this.r = source.r;
  1600. this.g = source.g;
  1601. this.b = source.b;
  1602. return this;
  1603. };
  1604. /**
  1605. * Updates the Color3 rgb values from the given floats
  1606. * @param r defines the red component to read from
  1607. * @param g defines the green component to read from
  1608. * @param b defines the blue component to read from
  1609. * @returns the current Color3 object
  1610. */
  1611. Color3.prototype.copyFromFloats = function (r, g, b) {
  1612. this.r = r;
  1613. this.g = g;
  1614. this.b = b;
  1615. return this;
  1616. };
  1617. /**
  1618. * Updates the Color3 rgb values from the given floats
  1619. * @param r defines the red component to read from
  1620. * @param g defines the green component to read from
  1621. * @param b defines the blue component to read from
  1622. * @returns the current Color3 object
  1623. */
  1624. Color3.prototype.set = function (r, g, b) {
  1625. return this.copyFromFloats(r, g, b);
  1626. };
  1627. /**
  1628. * Compute the Color3 hexadecimal code as a string
  1629. * @returns a string containing the hexadecimal representation of the Color3 object
  1630. */
  1631. Color3.prototype.toHexString = function () {
  1632. var intR = (this.r * 255) | 0;
  1633. var intG = (this.g * 255) | 0;
  1634. var intB = (this.b * 255) | 0;
  1635. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1636. };
  1637. /**
  1638. * Computes a new Color3 converted from the current one to linear space
  1639. * @returns a new Color3 object
  1640. */
  1641. Color3.prototype.toLinearSpace = function () {
  1642. var convertedColor = new Color3();
  1643. this.toLinearSpaceToRef(convertedColor);
  1644. return convertedColor;
  1645. };
  1646. /**
  1647. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1648. * @param convertedColor defines the Color3 object where to store the linear space version
  1649. * @returns the unmodified Color3
  1650. */
  1651. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1652. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1653. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1654. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1655. return this;
  1656. };
  1657. /**
  1658. * Computes a new Color3 converted from the current one to gamma space
  1659. * @returns a new Color3 object
  1660. */
  1661. Color3.prototype.toGammaSpace = function () {
  1662. var convertedColor = new Color3();
  1663. this.toGammaSpaceToRef(convertedColor);
  1664. return convertedColor;
  1665. };
  1666. /**
  1667. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1668. * @param convertedColor defines the Color3 object where to store the gamma space version
  1669. * @returns the unmodified Color3
  1670. */
  1671. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1672. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1673. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1674. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1675. return this;
  1676. };
  1677. // Statics
  1678. /**
  1679. * Creates a new Color3 from the string containing valid hexadecimal values
  1680. * @param hex defines a string containing valid hexadecimal values
  1681. * @returns a new Color3 object
  1682. */
  1683. Color3.FromHexString = function (hex) {
  1684. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1685. return new Color3(0, 0, 0);
  1686. }
  1687. var r = parseInt(hex.substring(1, 3), 16);
  1688. var g = parseInt(hex.substring(3, 5), 16);
  1689. var b = parseInt(hex.substring(5, 7), 16);
  1690. return Color3.FromInts(r, g, b);
  1691. };
  1692. /**
  1693. * Creates a new Vector3 from the starting index of the given array
  1694. * @param array defines the source array
  1695. * @param offset defines an offset in the source array
  1696. * @returns a new Color3 object
  1697. */
  1698. Color3.FromArray = function (array, offset) {
  1699. if (offset === void 0) { offset = 0; }
  1700. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1701. };
  1702. /**
  1703. * Creates a new Color3 from integer values (< 256)
  1704. * @param r defines the red component to read from (value between 0 and 255)
  1705. * @param g defines the green component to read from (value between 0 and 255)
  1706. * @param b defines the blue component to read from (value between 0 and 255)
  1707. * @returns a new Color3 object
  1708. */
  1709. Color3.FromInts = function (r, g, b) {
  1710. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1711. };
  1712. /**
  1713. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1714. * @param start defines the start Color3 value
  1715. * @param end defines the end Color3 value
  1716. * @param amount defines the gradient value between start and end
  1717. * @returns a new Color3 object
  1718. */
  1719. Color3.Lerp = function (start, end, amount) {
  1720. var r = start.r + ((end.r - start.r) * amount);
  1721. var g = start.g + ((end.g - start.g) * amount);
  1722. var b = start.b + ((end.b - start.b) * amount);
  1723. return new Color3(r, g, b);
  1724. };
  1725. /**
  1726. * Returns a Color3 value containing a red color
  1727. * @returns a new Color3 object
  1728. */
  1729. Color3.Red = function () { return new Color3(1, 0, 0); };
  1730. /**
  1731. * Returns a Color3 value containing a green color
  1732. * @returns a new Color3 object
  1733. */
  1734. Color3.Green = function () { return new Color3(0, 1, 0); };
  1735. /**
  1736. * Returns a Color3 value containing a blue color
  1737. * @returns a new Color3 object
  1738. */
  1739. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1740. /**
  1741. * Returns a Color3 value containing a black color
  1742. * @returns a new Color3 object
  1743. */
  1744. Color3.Black = function () { return new Color3(0, 0, 0); };
  1745. /**
  1746. * Returns a Color3 value containing a white color
  1747. * @returns a new Color3 object
  1748. */
  1749. Color3.White = function () { return new Color3(1, 1, 1); };
  1750. /**
  1751. * Returns a Color3 value containing a purple color
  1752. * @returns a new Color3 object
  1753. */
  1754. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1755. /**
  1756. * Returns a Color3 value containing a magenta color
  1757. * @returns a new Color3 object
  1758. */
  1759. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1760. /**
  1761. * Returns a Color3 value containing a yellow color
  1762. * @returns a new Color3 object
  1763. */
  1764. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1765. /**
  1766. * Returns a Color3 value containing a gray color
  1767. * @returns a new Color3 object
  1768. */
  1769. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1770. /**
  1771. * Returns a Color3 value containing a teal color
  1772. * @returns a new Color3 object
  1773. */
  1774. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1775. /**
  1776. * Returns a Color3 value containing a random color
  1777. * @returns a new Color3 object
  1778. */
  1779. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1780. return Color3;
  1781. }());
  1782. BABYLON.Color3 = Color3;
  1783. /**
  1784. * Class used to hold a RBGA color
  1785. */
  1786. var Color4 = /** @class */ (function () {
  1787. /**
  1788. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1789. * @param r defines the red component (between 0 and 1, default is 0)
  1790. * @param g defines the green component (between 0 and 1, default is 0)
  1791. * @param b defines the blue component (between 0 and 1, default is 0)
  1792. * @param a defines the alpha component (between 0 and 1, default is 1)
  1793. */
  1794. function Color4(
  1795. /**
  1796. * Defines the red component (between 0 and 1, default is 0)
  1797. */
  1798. r,
  1799. /**
  1800. * Defines the green component (between 0 and 1, default is 0)
  1801. */
  1802. g,
  1803. /**
  1804. * Defines the blue component (between 0 and 1, default is 0)
  1805. */
  1806. b,
  1807. /**
  1808. * Defines the alpha component (between 0 and 1, default is 1)
  1809. */
  1810. a) {
  1811. if (r === void 0) { r = 0; }
  1812. if (g === void 0) { g = 0; }
  1813. if (b === void 0) { b = 0; }
  1814. if (a === void 0) { a = 1; }
  1815. this.r = r;
  1816. this.g = g;
  1817. this.b = b;
  1818. this.a = a;
  1819. }
  1820. // Operators
  1821. /**
  1822. * Adds in place the given Color4 values to the current Color4 object
  1823. * @param right defines the second operand
  1824. * @returns the current updated Color4 object
  1825. */
  1826. Color4.prototype.addInPlace = function (right) {
  1827. this.r += right.r;
  1828. this.g += right.g;
  1829. this.b += right.b;
  1830. this.a += right.a;
  1831. return this;
  1832. };
  1833. /**
  1834. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1835. * @returns the new array
  1836. */
  1837. Color4.prototype.asArray = function () {
  1838. var result = new Array();
  1839. this.toArray(result, 0);
  1840. return result;
  1841. };
  1842. /**
  1843. * Stores from the starting index in the given array the Color4 successive values
  1844. * @param array defines the array where to store the r,g,b components
  1845. * @param index defines an optional index in the target array to define where to start storing values
  1846. * @returns the current Color4 object
  1847. */
  1848. Color4.prototype.toArray = function (array, index) {
  1849. if (index === undefined) {
  1850. index = 0;
  1851. }
  1852. array[index] = this.r;
  1853. array[index + 1] = this.g;
  1854. array[index + 2] = this.b;
  1855. array[index + 3] = this.a;
  1856. return this;
  1857. };
  1858. /**
  1859. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1860. * @param right defines the second operand
  1861. * @returns a new Color4 object
  1862. */
  1863. Color4.prototype.add = function (right) {
  1864. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1865. };
  1866. /**
  1867. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1868. * @param right defines the second operand
  1869. * @returns a new Color4 object
  1870. */
  1871. Color4.prototype.subtract = function (right) {
  1872. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1873. };
  1874. /**
  1875. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1876. * @param right defines the second operand
  1877. * @param result defines the Color4 object where to store the result
  1878. * @returns the current Color4 object
  1879. */
  1880. Color4.prototype.subtractToRef = function (right, result) {
  1881. result.r = this.r - right.r;
  1882. result.g = this.g - right.g;
  1883. result.b = this.b - right.b;
  1884. result.a = this.a - right.a;
  1885. return this;
  1886. };
  1887. /**
  1888. * Creates a new Color4 with the current Color4 values multiplied by scale
  1889. * @param scale defines the scaling factor to apply
  1890. * @returns a new Color4 object
  1891. */
  1892. Color4.prototype.scale = function (scale) {
  1893. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1894. };
  1895. /**
  1896. * Multiplies the current Color4 values by scale and stores the result in "result"
  1897. * @param scale defines the scaling factor to apply
  1898. * @param result defines the Color4 object where to store the result
  1899. * @returns the current unmodified Color4
  1900. */
  1901. Color4.prototype.scaleToRef = function (scale, result) {
  1902. result.r = this.r * scale;
  1903. result.g = this.g * scale;
  1904. result.b = this.b * scale;
  1905. result.a = this.a * scale;
  1906. return this;
  1907. };
  1908. /**
  1909. * Scale the current Color4 values by a factor and add the result to a given Color4
  1910. * @param scale defines the scale factor
  1911. * @param result defines the Color4 object where to store the result
  1912. * @returns the unmodified current Color4
  1913. */
  1914. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1915. result.r += this.r * scale;
  1916. result.g += this.g * scale;
  1917. result.b += this.b * scale;
  1918. result.a += this.a * scale;
  1919. return this;
  1920. };
  1921. /**
  1922. * Clamps the rgb values by the min and max values and stores the result into "result"
  1923. * @param min defines minimum clamping value (default is 0)
  1924. * @param max defines maximum clamping value (default is 1)
  1925. * @param result defines color to store the result into.
  1926. * @returns the cuurent Color4
  1927. */
  1928. Color4.prototype.clampToRef = function (min, max, result) {
  1929. if (min === void 0) { min = 0; }
  1930. if (max === void 0) { max = 1; }
  1931. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1932. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1933. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1934. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1935. return this;
  1936. };
  1937. /**
  1938. * Multipy an Color4 value by another and return a new Color4 object
  1939. * @param color defines the Color4 value to multiply by
  1940. * @returns a new Color4 object
  1941. */
  1942. Color4.prototype.multiply = function (color) {
  1943. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1944. };
  1945. /**
  1946. * Multipy a Color4 value by another and push the result in a reference value
  1947. * @param color defines the Color4 value to multiply by
  1948. * @param result defines the Color4 to fill the result in
  1949. * @returns the result Color4
  1950. */
  1951. Color4.prototype.multiplyToRef = function (color, result) {
  1952. result.r = this.r * color.r;
  1953. result.g = this.g * color.g;
  1954. result.b = this.b * color.b;
  1955. result.a = this.a * color.a;
  1956. return result;
  1957. };
  1958. /**
  1959. * Creates a string with the Color4 current values
  1960. * @returns the string representation of the Color4 object
  1961. */
  1962. Color4.prototype.toString = function () {
  1963. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1964. };
  1965. /**
  1966. * Returns the string "Color4"
  1967. * @returns "Color4"
  1968. */
  1969. Color4.prototype.getClassName = function () {
  1970. return "Color4";
  1971. };
  1972. /**
  1973. * Compute the Color4 hash code
  1974. * @returns an unique number that can be used to hash Color4 objects
  1975. */
  1976. Color4.prototype.getHashCode = function () {
  1977. var hash = this.r || 0;
  1978. hash = (hash * 397) ^ (this.g || 0);
  1979. hash = (hash * 397) ^ (this.b || 0);
  1980. hash = (hash * 397) ^ (this.a || 0);
  1981. return hash;
  1982. };
  1983. /**
  1984. * Creates a new Color4 copied from the current one
  1985. * @returns a new Color4 object
  1986. */
  1987. Color4.prototype.clone = function () {
  1988. return new Color4(this.r, this.g, this.b, this.a);
  1989. };
  1990. /**
  1991. * Copies the given Color4 values into the current one
  1992. * @param source defines the source Color4 object
  1993. * @returns the current updated Color4 object
  1994. */
  1995. Color4.prototype.copyFrom = function (source) {
  1996. this.r = source.r;
  1997. this.g = source.g;
  1998. this.b = source.b;
  1999. this.a = source.a;
  2000. return this;
  2001. };
  2002. /**
  2003. * Copies the given float values into the current one
  2004. * @param r defines the red component to read from
  2005. * @param g defines the green component to read from
  2006. * @param b defines the blue component to read from
  2007. * @param a defines the alpha component to read from
  2008. * @returns the current updated Color4 object
  2009. */
  2010. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2011. this.r = r;
  2012. this.g = g;
  2013. this.b = b;
  2014. this.a = a;
  2015. return this;
  2016. };
  2017. /**
  2018. * Copies the given float values into the current one
  2019. * @param r defines the red component to read from
  2020. * @param g defines the green component to read from
  2021. * @param b defines the blue component to read from
  2022. * @param a defines the alpha component to read from
  2023. * @returns the current updated Color4 object
  2024. */
  2025. Color4.prototype.set = function (r, g, b, a) {
  2026. return this.copyFromFloats(r, g, b, a);
  2027. };
  2028. /**
  2029. * Compute the Color4 hexadecimal code as a string
  2030. * @returns a string containing the hexadecimal representation of the Color4 object
  2031. */
  2032. Color4.prototype.toHexString = function () {
  2033. var intR = (this.r * 255) | 0;
  2034. var intG = (this.g * 255) | 0;
  2035. var intB = (this.b * 255) | 0;
  2036. var intA = (this.a * 255) | 0;
  2037. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2038. };
  2039. /**
  2040. * Computes a new Color4 converted from the current one to linear space
  2041. * @returns a new Color4 object
  2042. */
  2043. Color4.prototype.toLinearSpace = function () {
  2044. var convertedColor = new Color4();
  2045. this.toLinearSpaceToRef(convertedColor);
  2046. return convertedColor;
  2047. };
  2048. /**
  2049. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2050. * @param convertedColor defines the Color4 object where to store the linear space version
  2051. * @returns the unmodified Color4
  2052. */
  2053. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2054. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2055. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2056. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2057. convertedColor.a = this.a;
  2058. return this;
  2059. };
  2060. /**
  2061. * Computes a new Color4 converted from the current one to gamma space
  2062. * @returns a new Color4 object
  2063. */
  2064. Color4.prototype.toGammaSpace = function () {
  2065. var convertedColor = new Color4();
  2066. this.toGammaSpaceToRef(convertedColor);
  2067. return convertedColor;
  2068. };
  2069. /**
  2070. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2071. * @param convertedColor defines the Color4 object where to store the gamma space version
  2072. * @returns the unmodified Color4
  2073. */
  2074. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2075. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2076. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2077. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2078. convertedColor.a = this.a;
  2079. return this;
  2080. };
  2081. // Statics
  2082. /**
  2083. * Creates a new Color4 from the string containing valid hexadecimal values
  2084. * @param hex defines a string containing valid hexadecimal values
  2085. * @returns a new Color4 object
  2086. */
  2087. Color4.FromHexString = function (hex) {
  2088. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2089. return new Color4(0.0, 0.0, 0.0, 0.0);
  2090. }
  2091. var r = parseInt(hex.substring(1, 3), 16);
  2092. var g = parseInt(hex.substring(3, 5), 16);
  2093. var b = parseInt(hex.substring(5, 7), 16);
  2094. var a = parseInt(hex.substring(7, 9), 16);
  2095. return Color4.FromInts(r, g, b, a);
  2096. };
  2097. /**
  2098. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2099. * @param left defines the start value
  2100. * @param right defines the end value
  2101. * @param amount defines the gradient factor
  2102. * @returns a new Color4 object
  2103. */
  2104. Color4.Lerp = function (left, right, amount) {
  2105. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2106. Color4.LerpToRef(left, right, amount, result);
  2107. return result;
  2108. };
  2109. /**
  2110. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2111. * @param left defines the start value
  2112. * @param right defines the end value
  2113. * @param amount defines the gradient factor
  2114. * @param result defines the Color4 object where to store data
  2115. */
  2116. Color4.LerpToRef = function (left, right, amount, result) {
  2117. result.r = left.r + (right.r - left.r) * amount;
  2118. result.g = left.g + (right.g - left.g) * amount;
  2119. result.b = left.b + (right.b - left.b) * amount;
  2120. result.a = left.a + (right.a - left.a) * amount;
  2121. };
  2122. /**
  2123. * Creates a new Color4 from the starting index element of the given array
  2124. * @param array defines the source array to read from
  2125. * @param offset defines the offset in the source array
  2126. * @returns a new Color4 object
  2127. */
  2128. Color4.FromArray = function (array, offset) {
  2129. if (offset === void 0) { offset = 0; }
  2130. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2131. };
  2132. /**
  2133. * Creates a new Color3 from integer values (< 256)
  2134. * @param r defines the red component to read from (value between 0 and 255)
  2135. * @param g defines the green component to read from (value between 0 and 255)
  2136. * @param b defines the blue component to read from (value between 0 and 255)
  2137. * @param a defines the alpha component to read from (value between 0 and 255)
  2138. * @returns a new Color3 object
  2139. */
  2140. Color4.FromInts = function (r, g, b, a) {
  2141. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2142. };
  2143. /**
  2144. * Check the content of a given array and convert it to an array containing RGBA data
  2145. * If the original array was already containing count * 4 values then it is returned directly
  2146. * @param colors defines the array to check
  2147. * @param count defines the number of RGBA data to expect
  2148. * @returns an array containing count * 4 values (RGBA)
  2149. */
  2150. Color4.CheckColors4 = function (colors, count) {
  2151. // Check if color3 was used
  2152. if (colors.length === count * 3) {
  2153. var colors4 = [];
  2154. for (var index = 0; index < colors.length; index += 3) {
  2155. var newIndex = (index / 3) * 4;
  2156. colors4[newIndex] = colors[index];
  2157. colors4[newIndex + 1] = colors[index + 1];
  2158. colors4[newIndex + 2] = colors[index + 2];
  2159. colors4[newIndex + 3] = 1.0;
  2160. }
  2161. return colors4;
  2162. }
  2163. return colors;
  2164. };
  2165. return Color4;
  2166. }());
  2167. BABYLON.Color4 = Color4;
  2168. /**
  2169. * Class representing a vector containing 2 coordinates
  2170. */
  2171. var Vector2 = /** @class */ (function () {
  2172. /**
  2173. * Creates a new Vector2 from the given x and y coordinates
  2174. * @param x defines the first coordinate
  2175. * @param y defines the second coordinate
  2176. */
  2177. function Vector2(
  2178. /** defines the first coordinate */
  2179. x,
  2180. /** defines the second coordinate */
  2181. y) {
  2182. this.x = x;
  2183. this.y = y;
  2184. }
  2185. /**
  2186. * Gets a string with the Vector2 coordinates
  2187. * @returns a string with the Vector2 coordinates
  2188. */
  2189. Vector2.prototype.toString = function () {
  2190. return "{X: " + this.x + " Y:" + this.y + "}";
  2191. };
  2192. /**
  2193. * Gets class name
  2194. * @returns the string "Vector2"
  2195. */
  2196. Vector2.prototype.getClassName = function () {
  2197. return "Vector2";
  2198. };
  2199. /**
  2200. * Gets current vector hash code
  2201. * @returns the Vector2 hash code as a number
  2202. */
  2203. Vector2.prototype.getHashCode = function () {
  2204. var hash = this.x || 0;
  2205. hash = (hash * 397) ^ (this.y || 0);
  2206. return hash;
  2207. };
  2208. // Operators
  2209. /**
  2210. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2211. * @param array defines the source array
  2212. * @param index defines the offset in source array
  2213. * @returns the current Vector2
  2214. */
  2215. Vector2.prototype.toArray = function (array, index) {
  2216. if (index === void 0) { index = 0; }
  2217. array[index] = this.x;
  2218. array[index + 1] = this.y;
  2219. return this;
  2220. };
  2221. /**
  2222. * Copy the current vector to an array
  2223. * @returns a new array with 2 elements: the Vector2 coordinates.
  2224. */
  2225. Vector2.prototype.asArray = function () {
  2226. var result = new Array();
  2227. this.toArray(result, 0);
  2228. return result;
  2229. };
  2230. /**
  2231. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2232. * @param source defines the source Vector2
  2233. * @returns the current updated Vector2
  2234. */
  2235. Vector2.prototype.copyFrom = function (source) {
  2236. this.x = source.x;
  2237. this.y = source.y;
  2238. return this;
  2239. };
  2240. /**
  2241. * Sets the Vector2 coordinates with the given floats
  2242. * @param x defines the first coordinate
  2243. * @param y defines the second coordinate
  2244. * @returns the current updated Vector2
  2245. */
  2246. Vector2.prototype.copyFromFloats = function (x, y) {
  2247. this.x = x;
  2248. this.y = y;
  2249. return this;
  2250. };
  2251. /**
  2252. * Sets the Vector2 coordinates with the given floats
  2253. * @param x defines the first coordinate
  2254. * @param y defines the second coordinate
  2255. * @returns the current updated Vector2
  2256. */
  2257. Vector2.prototype.set = function (x, y) {
  2258. return this.copyFromFloats(x, y);
  2259. };
  2260. /**
  2261. * Add another vector with the current one
  2262. * @param otherVector defines the other vector
  2263. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2264. */
  2265. Vector2.prototype.add = function (otherVector) {
  2266. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2267. };
  2268. /**
  2269. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2270. * @param otherVector defines the other vector
  2271. * @param result defines the target vector
  2272. * @returns the unmodified current Vector2
  2273. */
  2274. Vector2.prototype.addToRef = function (otherVector, result) {
  2275. result.x = this.x + otherVector.x;
  2276. result.y = this.y + otherVector.y;
  2277. return this;
  2278. };
  2279. /**
  2280. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2281. * @param otherVector defines the other vector
  2282. * @returns the current updated Vector2
  2283. */
  2284. Vector2.prototype.addInPlace = function (otherVector) {
  2285. this.x += otherVector.x;
  2286. this.y += otherVector.y;
  2287. return this;
  2288. };
  2289. /**
  2290. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2291. * @param otherVector defines the other vector
  2292. * @returns a new Vector2
  2293. */
  2294. Vector2.prototype.addVector3 = function (otherVector) {
  2295. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2296. };
  2297. /**
  2298. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2299. * @param otherVector defines the other vector
  2300. * @returns a new Vector2
  2301. */
  2302. Vector2.prototype.subtract = function (otherVector) {
  2303. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2304. };
  2305. /**
  2306. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2307. * @param otherVector defines the other vector
  2308. * @param result defines the target vector
  2309. * @returns the unmodified current Vector2
  2310. */
  2311. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2312. result.x = this.x - otherVector.x;
  2313. result.y = this.y - otherVector.y;
  2314. return this;
  2315. };
  2316. /**
  2317. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2318. * @param otherVector defines the other vector
  2319. * @returns the current updated Vector2
  2320. */
  2321. Vector2.prototype.subtractInPlace = function (otherVector) {
  2322. this.x -= otherVector.x;
  2323. this.y -= otherVector.y;
  2324. return this;
  2325. };
  2326. /**
  2327. * Multiplies in place the current Vector2 coordinates by the given ones
  2328. * @param otherVector defines the other vector
  2329. * @returns the current updated Vector2
  2330. */
  2331. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2332. this.x *= otherVector.x;
  2333. this.y *= otherVector.y;
  2334. return this;
  2335. };
  2336. /**
  2337. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2338. * @param otherVector defines the other vector
  2339. * @returns a new Vector2
  2340. */
  2341. Vector2.prototype.multiply = function (otherVector) {
  2342. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2343. };
  2344. /**
  2345. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2346. * @param otherVector defines the other vector
  2347. * @param result defines the target vector
  2348. * @returns the unmodified current Vector2
  2349. */
  2350. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2351. result.x = this.x * otherVector.x;
  2352. result.y = this.y * otherVector.y;
  2353. return this;
  2354. };
  2355. /**
  2356. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2357. * @param x defines the first coordinate
  2358. * @param y defines the second coordinate
  2359. * @returns a new Vector2
  2360. */
  2361. Vector2.prototype.multiplyByFloats = function (x, y) {
  2362. return new Vector2(this.x * x, this.y * y);
  2363. };
  2364. /**
  2365. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2366. * @param otherVector defines the other vector
  2367. * @returns a new Vector2
  2368. */
  2369. Vector2.prototype.divide = function (otherVector) {
  2370. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2371. };
  2372. /**
  2373. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2374. * @param otherVector defines the other vector
  2375. * @param result defines the target vector
  2376. * @returns the unmodified current Vector2
  2377. */
  2378. Vector2.prototype.divideToRef = function (otherVector, result) {
  2379. result.x = this.x / otherVector.x;
  2380. result.y = this.y / otherVector.y;
  2381. return this;
  2382. };
  2383. /**
  2384. * Divides the current Vector3 coordinates by the given ones
  2385. * @param otherVector defines the other vector
  2386. * @returns the current updated Vector2
  2387. */
  2388. Vector2.prototype.divideInPlace = function (otherVector) {
  2389. return this.divideToRef(otherVector, this);
  2390. };
  2391. /**
  2392. * Gets a new Vector2 with current Vector2 negated coordinates
  2393. * @returns a new Vector2
  2394. */
  2395. Vector2.prototype.negate = function () {
  2396. return new Vector2(-this.x, -this.y);
  2397. };
  2398. /**
  2399. * Multiply the Vector2 coordinates by scale
  2400. * @param scale defines the scaling factor
  2401. * @returns the current updated Vector2
  2402. */
  2403. Vector2.prototype.scaleInPlace = function (scale) {
  2404. this.x *= scale;
  2405. this.y *= scale;
  2406. return this;
  2407. };
  2408. /**
  2409. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2410. * @param scale defines the scaling factor
  2411. * @returns a new Vector2
  2412. */
  2413. Vector2.prototype.scale = function (scale) {
  2414. var result = new Vector2(0, 0);
  2415. this.scaleToRef(scale, result);
  2416. return result;
  2417. };
  2418. /**
  2419. * Scale the current Vector2 values by a factor to a given Vector2
  2420. * @param scale defines the scale factor
  2421. * @param result defines the Vector2 object where to store the result
  2422. * @returns the unmodified current Vector2
  2423. */
  2424. Vector2.prototype.scaleToRef = function (scale, result) {
  2425. result.x = this.x * scale;
  2426. result.y = this.y * scale;
  2427. return this;
  2428. };
  2429. /**
  2430. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2431. * @param scale defines the scale factor
  2432. * @param result defines the Vector2 object where to store the result
  2433. * @returns the unmodified current Vector2
  2434. */
  2435. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2436. result.x += this.x * scale;
  2437. result.y += this.y * scale;
  2438. return this;
  2439. };
  2440. /**
  2441. * Gets a boolean if two vectors are equals
  2442. * @param otherVector defines the other vector
  2443. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2444. */
  2445. Vector2.prototype.equals = function (otherVector) {
  2446. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2447. };
  2448. /**
  2449. * Gets a boolean if two vectors are equals (using an epsilon value)
  2450. * @param otherVector defines the other vector
  2451. * @param epsilon defines the minimal distance to consider equality
  2452. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2453. */
  2454. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2455. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2456. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2457. };
  2458. // Properties
  2459. /**
  2460. * Gets the length of the vector
  2461. * @returns the vector length (float)
  2462. */
  2463. Vector2.prototype.length = function () {
  2464. return Math.sqrt(this.x * this.x + this.y * this.y);
  2465. };
  2466. /**
  2467. * Gets the vector squared length
  2468. * @returns the vector squared length (float)
  2469. */
  2470. Vector2.prototype.lengthSquared = function () {
  2471. return (this.x * this.x + this.y * this.y);
  2472. };
  2473. // Methods
  2474. /**
  2475. * Normalize the vector
  2476. * @returns the current updated Vector2
  2477. */
  2478. Vector2.prototype.normalize = function () {
  2479. var len = this.length();
  2480. if (len === 0)
  2481. return this;
  2482. var num = 1.0 / len;
  2483. this.x *= num;
  2484. this.y *= num;
  2485. return this;
  2486. };
  2487. /**
  2488. * Gets a new Vector2 copied from the Vector2
  2489. * @returns a new Vector2
  2490. */
  2491. Vector2.prototype.clone = function () {
  2492. return new Vector2(this.x, this.y);
  2493. };
  2494. // Statics
  2495. /**
  2496. * Gets a new Vector2(0, 0)
  2497. * @returns a new Vector2
  2498. */
  2499. Vector2.Zero = function () {
  2500. return new Vector2(0, 0);
  2501. };
  2502. /**
  2503. * Gets a new Vector2(1, 1)
  2504. * @returns a new Vector2
  2505. */
  2506. Vector2.One = function () {
  2507. return new Vector2(1, 1);
  2508. };
  2509. /**
  2510. * Gets a new Vector2 set from the given index element of the given array
  2511. * @param array defines the data source
  2512. * @param offset defines the offset in the data source
  2513. * @returns a new Vector2
  2514. */
  2515. Vector2.FromArray = function (array, offset) {
  2516. if (offset === void 0) { offset = 0; }
  2517. return new Vector2(array[offset], array[offset + 1]);
  2518. };
  2519. /**
  2520. * Sets "result" from the given index element of the given array
  2521. * @param array defines the data source
  2522. * @param offset defines the offset in the data source
  2523. * @param result defines the target vector
  2524. */
  2525. Vector2.FromArrayToRef = function (array, offset, result) {
  2526. result.x = array[offset];
  2527. result.y = array[offset + 1];
  2528. };
  2529. /**
  2530. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2531. * @param value1 defines 1st point of control
  2532. * @param value2 defines 2nd point of control
  2533. * @param value3 defines 3rd point of control
  2534. * @param value4 defines 4th point of control
  2535. * @param amount defines the interpolation factor
  2536. * @returns a new Vector2
  2537. */
  2538. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2539. var squared = amount * amount;
  2540. var cubed = amount * squared;
  2541. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2542. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2543. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2544. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2545. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2546. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2547. return new Vector2(x, y);
  2548. };
  2549. /**
  2550. * 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".
  2551. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2552. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2553. * @param value defines the value to clamp
  2554. * @param min defines the lower limit
  2555. * @param max defines the upper limit
  2556. * @returns a new Vector2
  2557. */
  2558. Vector2.Clamp = function (value, min, max) {
  2559. var x = value.x;
  2560. x = (x > max.x) ? max.x : x;
  2561. x = (x < min.x) ? min.x : x;
  2562. var y = value.y;
  2563. y = (y > max.y) ? max.y : y;
  2564. y = (y < min.y) ? min.y : y;
  2565. return new Vector2(x, y);
  2566. };
  2567. /**
  2568. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2569. * @param value1 defines the 1st control point
  2570. * @param tangent1 defines the outgoing tangent
  2571. * @param value2 defines the 2nd control point
  2572. * @param tangent2 defines the incoming tangent
  2573. * @param amount defines the interpolation factor
  2574. * @returns a new Vector2
  2575. */
  2576. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2577. var squared = amount * amount;
  2578. var cubed = amount * squared;
  2579. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2580. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2581. var part3 = (cubed - (2.0 * squared)) + amount;
  2582. var part4 = cubed - squared;
  2583. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2584. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2585. return new Vector2(x, y);
  2586. };
  2587. /**
  2588. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2589. * @param start defines the start vector
  2590. * @param end defines the end vector
  2591. * @param amount defines the interpolation factor
  2592. * @returns a new Vector2
  2593. */
  2594. Vector2.Lerp = function (start, end, amount) {
  2595. var x = start.x + ((end.x - start.x) * amount);
  2596. var y = start.y + ((end.y - start.y) * amount);
  2597. return new Vector2(x, y);
  2598. };
  2599. /**
  2600. * Gets the dot product of the vector "left" and the vector "right"
  2601. * @param left defines first vector
  2602. * @param right defines second vector
  2603. * @returns the dot product (float)
  2604. */
  2605. Vector2.Dot = function (left, right) {
  2606. return left.x * right.x + left.y * right.y;
  2607. };
  2608. /**
  2609. * Returns a new Vector2 equal to the normalized given vector
  2610. * @param vector defines the vector to normalize
  2611. * @returns a new Vector2
  2612. */
  2613. Vector2.Normalize = function (vector) {
  2614. var newVector = vector.clone();
  2615. newVector.normalize();
  2616. return newVector;
  2617. };
  2618. /**
  2619. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2620. * @param left defines 1st vector
  2621. * @param right defines 2nd vector
  2622. * @returns a new Vector2
  2623. */
  2624. Vector2.Minimize = function (left, right) {
  2625. var x = (left.x < right.x) ? left.x : right.x;
  2626. var y = (left.y < right.y) ? left.y : right.y;
  2627. return new Vector2(x, y);
  2628. };
  2629. /**
  2630. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2631. * @param left defines 1st vector
  2632. * @param right defines 2nd vector
  2633. * @returns a new Vector2
  2634. */
  2635. Vector2.Maximize = function (left, right) {
  2636. var x = (left.x > right.x) ? left.x : right.x;
  2637. var y = (left.y > right.y) ? left.y : right.y;
  2638. return new Vector2(x, y);
  2639. };
  2640. /**
  2641. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2642. * @param vector defines the vector to transform
  2643. * @param transformation defines the matrix to apply
  2644. * @returns a new Vector2
  2645. */
  2646. Vector2.Transform = function (vector, transformation) {
  2647. var r = Vector2.Zero();
  2648. Vector2.TransformToRef(vector, transformation, r);
  2649. return r;
  2650. };
  2651. /**
  2652. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2653. * @param vector defines the vector to transform
  2654. * @param transformation defines the matrix to apply
  2655. * @param result defines the target vector
  2656. */
  2657. Vector2.TransformToRef = function (vector, transformation, result) {
  2658. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2659. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2660. result.x = x;
  2661. result.y = y;
  2662. };
  2663. /**
  2664. * Determines if a given vector is included in a triangle
  2665. * @param p defines the vector to test
  2666. * @param p0 defines 1st triangle point
  2667. * @param p1 defines 2nd triangle point
  2668. * @param p2 defines 3rd triangle point
  2669. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2670. */
  2671. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2672. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2673. var sign = a < 0 ? -1 : 1;
  2674. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2675. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2676. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2677. };
  2678. /**
  2679. * Gets the distance between the vectors "value1" and "value2"
  2680. * @param value1 defines first vector
  2681. * @param value2 defines second vector
  2682. * @returns the distance between vectors
  2683. */
  2684. Vector2.Distance = function (value1, value2) {
  2685. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2686. };
  2687. /**
  2688. * Returns the squared distance between the vectors "value1" and "value2"
  2689. * @param value1 defines first vector
  2690. * @param value2 defines second vector
  2691. * @returns the squared distance between vectors
  2692. */
  2693. Vector2.DistanceSquared = function (value1, value2) {
  2694. var x = value1.x - value2.x;
  2695. var y = value1.y - value2.y;
  2696. return (x * x) + (y * y);
  2697. };
  2698. /**
  2699. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2700. * @param value1 defines first vector
  2701. * @param value2 defines second vector
  2702. * @returns a new Vector2
  2703. */
  2704. Vector2.Center = function (value1, value2) {
  2705. var center = value1.add(value2);
  2706. center.scaleInPlace(0.5);
  2707. return center;
  2708. };
  2709. /**
  2710. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2711. * @param p defines the middle point
  2712. * @param segA defines one point of the segment
  2713. * @param segB defines the other point of the segment
  2714. * @returns the shortest distance
  2715. */
  2716. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2717. var l2 = Vector2.DistanceSquared(segA, segB);
  2718. if (l2 === 0.0) {
  2719. return Vector2.Distance(p, segA);
  2720. }
  2721. var v = segB.subtract(segA);
  2722. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2723. var proj = segA.add(v.multiplyByFloats(t, t));
  2724. return Vector2.Distance(p, proj);
  2725. };
  2726. return Vector2;
  2727. }());
  2728. BABYLON.Vector2 = Vector2;
  2729. /**
  2730. * Classed used to store (x,y,z) vector representation
  2731. * A Vector3 is the main object used in 3D geometry
  2732. * It can represent etiher the coordinates of a point the space, either a direction
  2733. * Reminder: Babylon.js uses a left handed forward facing system
  2734. */
  2735. var Vector3 = /** @class */ (function () {
  2736. /**
  2737. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2738. * @param x defines the first coordinates (on X axis)
  2739. * @param y defines the second coordinates (on Y axis)
  2740. * @param z defines the third coordinates (on Z axis)
  2741. */
  2742. function Vector3(
  2743. /**
  2744. * Defines the first coordinates (on X axis)
  2745. */
  2746. x,
  2747. /**
  2748. * Defines the second coordinates (on Y axis)
  2749. */
  2750. y,
  2751. /**
  2752. * Defines the third coordinates (on Z axis)
  2753. */
  2754. z) {
  2755. this.x = x;
  2756. this.y = y;
  2757. this.z = z;
  2758. }
  2759. /**
  2760. * Creates a string representation of the Vector3
  2761. * @returns a string with the Vector3 coordinates.
  2762. */
  2763. Vector3.prototype.toString = function () {
  2764. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2765. };
  2766. /**
  2767. * Gets the class name
  2768. * @returns the string "Vector3"
  2769. */
  2770. Vector3.prototype.getClassName = function () {
  2771. return "Vector3";
  2772. };
  2773. /**
  2774. * Creates the Vector3 hash code
  2775. * @returns a number which tends to be unique between Vector3 instances
  2776. */
  2777. Vector3.prototype.getHashCode = function () {
  2778. var hash = this.x || 0;
  2779. hash = (hash * 397) ^ (this.y || 0);
  2780. hash = (hash * 397) ^ (this.z || 0);
  2781. return hash;
  2782. };
  2783. // Operators
  2784. /**
  2785. * Creates an array containing three elements : the coordinates of the Vector3
  2786. * @returns a new array of numbers
  2787. */
  2788. Vector3.prototype.asArray = function () {
  2789. var result = [];
  2790. this.toArray(result, 0);
  2791. return result;
  2792. };
  2793. /**
  2794. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2795. * @param array defines the destination array
  2796. * @param index defines the offset in the destination array
  2797. * @returns the current Vector3
  2798. */
  2799. Vector3.prototype.toArray = function (array, index) {
  2800. if (index === void 0) { index = 0; }
  2801. array[index] = this.x;
  2802. array[index + 1] = this.y;
  2803. array[index + 2] = this.z;
  2804. return this;
  2805. };
  2806. /**
  2807. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2808. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2809. */
  2810. Vector3.prototype.toQuaternion = function () {
  2811. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2812. };
  2813. /**
  2814. * Adds the given vector to the current Vector3
  2815. * @param otherVector defines the second operand
  2816. * @returns the current updated Vector3
  2817. */
  2818. Vector3.prototype.addInPlace = function (otherVector) {
  2819. this.x += otherVector.x;
  2820. this.y += otherVector.y;
  2821. this.z += otherVector.z;
  2822. return this;
  2823. };
  2824. /**
  2825. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2826. * @param otherVector defines the second operand
  2827. * @returns the resulting Vector3
  2828. */
  2829. Vector3.prototype.add = function (otherVector) {
  2830. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2831. };
  2832. /**
  2833. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2834. * @param otherVector defines the second operand
  2835. * @param result defines the Vector3 object where to store the result
  2836. * @returns the current Vector3
  2837. */
  2838. Vector3.prototype.addToRef = function (otherVector, result) {
  2839. result.x = this.x + otherVector.x;
  2840. result.y = this.y + otherVector.y;
  2841. result.z = this.z + otherVector.z;
  2842. return this;
  2843. };
  2844. /**
  2845. * Subtract the given vector from the current Vector3
  2846. * @param otherVector defines the second operand
  2847. * @returns the current updated Vector3
  2848. */
  2849. Vector3.prototype.subtractInPlace = function (otherVector) {
  2850. this.x -= otherVector.x;
  2851. this.y -= otherVector.y;
  2852. this.z -= otherVector.z;
  2853. return this;
  2854. };
  2855. /**
  2856. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2857. * @param otherVector defines the second operand
  2858. * @returns the resulting Vector3
  2859. */
  2860. Vector3.prototype.subtract = function (otherVector) {
  2861. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2862. };
  2863. /**
  2864. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2865. * @param otherVector defines the second operand
  2866. * @param result defines the Vector3 object where to store the result
  2867. * @returns the current Vector3
  2868. */
  2869. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2870. result.x = this.x - otherVector.x;
  2871. result.y = this.y - otherVector.y;
  2872. result.z = this.z - otherVector.z;
  2873. return this;
  2874. };
  2875. /**
  2876. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2877. * @param x defines the x coordinate of the operand
  2878. * @param y defines the y coordinate of the operand
  2879. * @param z defines the z coordinate of the operand
  2880. * @returns the resulting Vector3
  2881. */
  2882. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2883. return new Vector3(this.x - x, this.y - y, this.z - z);
  2884. };
  2885. /**
  2886. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2887. * @param x defines the x coordinate of the operand
  2888. * @param y defines the y coordinate of the operand
  2889. * @param z defines the z coordinate of the operand
  2890. * @param result defines the Vector3 object where to store the result
  2891. * @returns the current Vector3
  2892. */
  2893. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2894. result.x = this.x - x;
  2895. result.y = this.y - y;
  2896. result.z = this.z - z;
  2897. return this;
  2898. };
  2899. /**
  2900. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2901. * @returns a new Vector3
  2902. */
  2903. Vector3.prototype.negate = function () {
  2904. return new Vector3(-this.x, -this.y, -this.z);
  2905. };
  2906. /**
  2907. * Multiplies the Vector3 coordinates by the float "scale"
  2908. * @param scale defines the multiplier factor
  2909. * @returns the current updated Vector3
  2910. */
  2911. Vector3.prototype.scaleInPlace = function (scale) {
  2912. this.x *= scale;
  2913. this.y *= scale;
  2914. this.z *= scale;
  2915. return this;
  2916. };
  2917. /**
  2918. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2919. * @param scale defines the multiplier factor
  2920. * @returns a new Vector3
  2921. */
  2922. Vector3.prototype.scale = function (scale) {
  2923. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2924. };
  2925. /**
  2926. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2927. * @param scale defines the multiplier factor
  2928. * @param result defines the Vector3 object where to store the result
  2929. * @returns the current Vector3
  2930. */
  2931. Vector3.prototype.scaleToRef = function (scale, result) {
  2932. result.x = this.x * scale;
  2933. result.y = this.y * scale;
  2934. result.z = this.z * scale;
  2935. return this;
  2936. };
  2937. /**
  2938. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2939. * @param scale defines the scale factor
  2940. * @param result defines the Vector3 object where to store the result
  2941. * @returns the unmodified current Vector3
  2942. */
  2943. Vector3.prototype.scaleAndAddToRef = 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. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2951. * @param otherVector defines the second operand
  2952. * @returns true if both vectors are equals
  2953. */
  2954. Vector3.prototype.equals = function (otherVector) {
  2955. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2956. };
  2957. /**
  2958. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2959. * @param otherVector defines the second operand
  2960. * @param epsilon defines the minimal distance to define values as equals
  2961. * @returns true if both vectors are distant less than epsilon
  2962. */
  2963. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2964. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2965. 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);
  2966. };
  2967. /**
  2968. * Returns true if the current Vector3 coordinates equals the given floats
  2969. * @param x defines the x coordinate of the operand
  2970. * @param y defines the y coordinate of the operand
  2971. * @param z defines the z coordinate of the operand
  2972. * @returns true if both vectors are equals
  2973. */
  2974. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2975. return this.x === x && this.y === y && this.z === z;
  2976. };
  2977. /**
  2978. * Multiplies the current Vector3 coordinates by the given ones
  2979. * @param otherVector defines the second operand
  2980. * @returns the current updated Vector3
  2981. */
  2982. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2983. this.x *= otherVector.x;
  2984. this.y *= otherVector.y;
  2985. this.z *= otherVector.z;
  2986. return this;
  2987. };
  2988. /**
  2989. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  2990. * @param otherVector defines the second operand
  2991. * @returns the new Vector3
  2992. */
  2993. Vector3.prototype.multiply = function (otherVector) {
  2994. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2995. };
  2996. /**
  2997. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  2998. * @param otherVector defines the second operand
  2999. * @param result defines the Vector3 object where to store the result
  3000. * @returns the current Vector3
  3001. */
  3002. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3003. result.x = this.x * otherVector.x;
  3004. result.y = this.y * otherVector.y;
  3005. result.z = this.z * otherVector.z;
  3006. return this;
  3007. };
  3008. /**
  3009. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3010. * @param x defines the x coordinate of the operand
  3011. * @param y defines the y coordinate of the operand
  3012. * @param z defines the z coordinate of the operand
  3013. * @returns the new Vector3
  3014. */
  3015. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3016. return new Vector3(this.x * x, this.y * y, this.z * z);
  3017. };
  3018. /**
  3019. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3020. * @param otherVector defines the second operand
  3021. * @returns the new Vector3
  3022. */
  3023. Vector3.prototype.divide = function (otherVector) {
  3024. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3025. };
  3026. /**
  3027. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3028. * @param otherVector defines the second operand
  3029. * @param result defines the Vector3 object where to store the result
  3030. * @returns the current Vector3
  3031. */
  3032. Vector3.prototype.divideToRef = function (otherVector, result) {
  3033. result.x = this.x / otherVector.x;
  3034. result.y = this.y / otherVector.y;
  3035. result.z = this.z / otherVector.z;
  3036. return this;
  3037. };
  3038. /**
  3039. * Divides the current Vector3 coordinates by the given ones.
  3040. * @param otherVector defines the second operand
  3041. * @returns the current updated Vector3
  3042. */
  3043. Vector3.prototype.divideInPlace = function (otherVector) {
  3044. return this.divideToRef(otherVector, this);
  3045. };
  3046. /**
  3047. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3048. * @param other defines the second operand
  3049. * @returns the current updated Vector3
  3050. */
  3051. Vector3.prototype.minimizeInPlace = function (other) {
  3052. if (other.x < this.x)
  3053. this.x = other.x;
  3054. if (other.y < this.y)
  3055. this.y = other.y;
  3056. if (other.z < this.z)
  3057. this.z = other.z;
  3058. return this;
  3059. };
  3060. /**
  3061. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3062. * @param other defines the second operand
  3063. * @returns the current updated Vector3
  3064. */
  3065. Vector3.prototype.maximizeInPlace = function (other) {
  3066. if (other.x > this.x)
  3067. this.x = other.x;
  3068. if (other.y > this.y)
  3069. this.y = other.y;
  3070. if (other.z > this.z)
  3071. this.z = other.z;
  3072. return this;
  3073. };
  3074. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3075. /**
  3076. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3077. */
  3078. get: function () {
  3079. var absX = Math.abs(this.x);
  3080. var absY = Math.abs(this.y);
  3081. if (absX !== absY) {
  3082. return true;
  3083. }
  3084. var absZ = Math.abs(this.z);
  3085. if (absX !== absZ) {
  3086. return true;
  3087. }
  3088. if (absY !== absZ) {
  3089. return true;
  3090. }
  3091. return false;
  3092. },
  3093. enumerable: true,
  3094. configurable: true
  3095. });
  3096. // Properties
  3097. /**
  3098. * Gets the length of the Vector3
  3099. * @returns the length of the Vecto3
  3100. */
  3101. Vector3.prototype.length = function () {
  3102. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3103. };
  3104. /**
  3105. * Gets the squared length of the Vector3
  3106. * @returns squared length of the Vector3
  3107. */
  3108. Vector3.prototype.lengthSquared = function () {
  3109. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3110. };
  3111. /**
  3112. * Normalize the current Vector3.
  3113. * Please note that this is an in place operation.
  3114. * @returns the current updated Vector3
  3115. */
  3116. Vector3.prototype.normalize = function () {
  3117. var len = this.length();
  3118. if (len === 0 || len === 1.0)
  3119. return this;
  3120. var num = 1.0 / len;
  3121. this.x *= num;
  3122. this.y *= num;
  3123. this.z *= num;
  3124. return this;
  3125. };
  3126. /**
  3127. * Normalize the current Vector3 to a new vector
  3128. * @returns the new Vector3
  3129. */
  3130. Vector3.prototype.normalizeToNew = function () {
  3131. var normalized = new Vector3(0, 0, 0);
  3132. this.normalizeToRef(normalized);
  3133. return normalized;
  3134. };
  3135. /**
  3136. * Normalize the current Vector3 to the reference
  3137. * @param reference define the Vector3 to update
  3138. * @returns the updated Vector3
  3139. */
  3140. Vector3.prototype.normalizeToRef = function (reference) {
  3141. var len = this.length();
  3142. if (len === 0 || len === 1.0) {
  3143. reference.set(this.x, this.y, this.z);
  3144. return reference;
  3145. }
  3146. var scale = 1.0 / len;
  3147. this.scaleToRef(scale, reference);
  3148. return reference;
  3149. };
  3150. /**
  3151. * Creates a new Vector3 copied from the current Vector3
  3152. * @returns the new Vector3
  3153. */
  3154. Vector3.prototype.clone = function () {
  3155. return new Vector3(this.x, this.y, this.z);
  3156. };
  3157. /**
  3158. * Copies the given vector coordinates to the current Vector3 ones
  3159. * @param source defines the source Vector3
  3160. * @returns the current updated Vector3
  3161. */
  3162. Vector3.prototype.copyFrom = function (source) {
  3163. this.x = source.x;
  3164. this.y = source.y;
  3165. this.z = source.z;
  3166. return this;
  3167. };
  3168. /**
  3169. * Copies the given floats to the current Vector3 coordinates
  3170. * @param x defines the x coordinate of the operand
  3171. * @param y defines the y coordinate of the operand
  3172. * @param z defines the z coordinate of the operand
  3173. * @returns the current updated Vector3
  3174. */
  3175. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3176. this.x = x;
  3177. this.y = y;
  3178. this.z = z;
  3179. return this;
  3180. };
  3181. /**
  3182. * Copies the given floats to the current Vector3 coordinates
  3183. * @param x defines the x coordinate of the operand
  3184. * @param y defines the y coordinate of the operand
  3185. * @param z defines the z coordinate of the operand
  3186. * @returns the current updated Vector3
  3187. */
  3188. Vector3.prototype.set = function (x, y, z) {
  3189. return this.copyFromFloats(x, y, z);
  3190. };
  3191. // Statics
  3192. /**
  3193. * Get the clip factor between two vectors
  3194. * @param vector0 defines the first operand
  3195. * @param vector1 defines the second operand
  3196. * @param axis defines the axis to use
  3197. * @param size defines the size along the axis
  3198. * @returns the clip factor
  3199. */
  3200. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3201. var d0 = Vector3.Dot(vector0, axis) - size;
  3202. var d1 = Vector3.Dot(vector1, axis) - size;
  3203. var s = d0 / (d0 - d1);
  3204. return s;
  3205. };
  3206. /**
  3207. * Get angle between two vectors
  3208. * @param vector0 angle between vector0 and vector1
  3209. * @param vector1 angle between vector0 and vector1
  3210. * @param normal direction of the normal
  3211. * @return the angle between vector0 and vector1
  3212. */
  3213. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3214. var v0 = vector0.clone().normalize();
  3215. var v1 = vector1.clone().normalize();
  3216. var dot = Vector3.Dot(v0, v1);
  3217. var n = Vector3.Cross(v0, v1);
  3218. if (Vector3.Dot(n, normal) > 0) {
  3219. return Math.acos(dot);
  3220. }
  3221. return -Math.acos(dot);
  3222. };
  3223. /**
  3224. * Returns a new Vector3 set from the index "offset" of the given array
  3225. * @param array defines the source array
  3226. * @param offset defines the offset in the source array
  3227. * @returns the new Vector3
  3228. */
  3229. Vector3.FromArray = function (array, offset) {
  3230. if (!offset) {
  3231. offset = 0;
  3232. }
  3233. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3234. };
  3235. /**
  3236. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3237. * This function is deprecated. Use FromArray instead
  3238. * @param array defines the source array
  3239. * @param offset defines the offset in the source array
  3240. * @returns the new Vector3
  3241. */
  3242. Vector3.FromFloatArray = function (array, offset) {
  3243. return Vector3.FromArray(array, offset);
  3244. };
  3245. /**
  3246. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3247. * @param array defines the source array
  3248. * @param offset defines the offset in the source array
  3249. * @param result defines the Vector3 where to store the result
  3250. */
  3251. Vector3.FromArrayToRef = function (array, offset, result) {
  3252. result.x = array[offset];
  3253. result.y = array[offset + 1];
  3254. result.z = array[offset + 2];
  3255. };
  3256. /**
  3257. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3258. * This function is deprecated. Use FromArrayToRef instead.
  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.FromFloatArrayToRef = function (array, offset, result) {
  3264. return Vector3.FromArrayToRef(array, offset, result);
  3265. };
  3266. /**
  3267. * Sets the given vector "result" with the given floats.
  3268. * @param x defines the x coordinate of the source
  3269. * @param y defines the y coordinate of the source
  3270. * @param z defines the z coordinate of the source
  3271. * @param result defines the Vector3 where to store the result
  3272. */
  3273. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3274. result.x = x;
  3275. result.y = y;
  3276. result.z = z;
  3277. };
  3278. /**
  3279. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3280. * @returns a new empty Vector3
  3281. */
  3282. Vector3.Zero = function () {
  3283. return new Vector3(0.0, 0.0, 0.0);
  3284. };
  3285. /**
  3286. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3287. * @returns a new unit Vector3
  3288. */
  3289. Vector3.One = function () {
  3290. return new Vector3(1.0, 1.0, 1.0);
  3291. };
  3292. /**
  3293. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3294. * @returns a new up Vector3
  3295. */
  3296. Vector3.Up = function () {
  3297. return new Vector3(0.0, 1.0, 0.0);
  3298. };
  3299. /**
  3300. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3301. * @returns a new forward Vector3
  3302. */
  3303. Vector3.Forward = function () {
  3304. return new Vector3(0.0, 0.0, 1.0);
  3305. };
  3306. /**
  3307. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3308. * @returns a new right Vector3
  3309. */
  3310. Vector3.Right = function () {
  3311. return new Vector3(1.0, 0.0, 0.0);
  3312. };
  3313. /**
  3314. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3315. * @returns a new left Vector3
  3316. */
  3317. Vector3.Left = function () {
  3318. return new Vector3(-1.0, 0.0, 0.0);
  3319. };
  3320. /**
  3321. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3322. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3323. * @param vector defines the Vector3 to transform
  3324. * @param transformation defines the transformation matrix
  3325. * @returns the transformed Vector3
  3326. */
  3327. Vector3.TransformCoordinates = function (vector, transformation) {
  3328. var result = Vector3.Zero();
  3329. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3330. return result;
  3331. };
  3332. /**
  3333. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3334. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3335. * @param vector defines the Vector3 to transform
  3336. * @param transformation defines the transformation matrix
  3337. * @param result defines the Vector3 where to store the result
  3338. */
  3339. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3340. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3341. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3342. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3343. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3344. result.x = x / w;
  3345. result.y = y / w;
  3346. result.z = z / w;
  3347. };
  3348. /**
  3349. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3350. * This method computes tranformed coordinates only, not transformed direction vectors
  3351. * @param x define the x coordinate of the source vector
  3352. * @param y define the y coordinate of the source vector
  3353. * @param z define the z coordinate of the source vector
  3354. * @param transformation defines the transformation matrix
  3355. * @param result defines the Vector3 where to store the result
  3356. */
  3357. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3358. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3359. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3360. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3361. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3362. result.x = rx / rw;
  3363. result.y = ry / rw;
  3364. result.z = rz / rw;
  3365. };
  3366. /**
  3367. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3368. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3369. * @param vector defines the Vector3 to transform
  3370. * @param transformation defines the transformation matrix
  3371. * @returns the new Vector3
  3372. */
  3373. Vector3.TransformNormal = function (vector, transformation) {
  3374. var result = Vector3.Zero();
  3375. Vector3.TransformNormalToRef(vector, transformation, result);
  3376. return result;
  3377. };
  3378. /**
  3379. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3380. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3381. * @param vector defines the Vector3 to transform
  3382. * @param transformation defines the transformation matrix
  3383. * @param result defines the Vector3 where to store the result
  3384. */
  3385. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3386. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3387. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3388. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3389. result.x = x;
  3390. result.y = y;
  3391. result.z = z;
  3392. };
  3393. /**
  3394. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3395. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3396. * @param x define the x coordinate of the source vector
  3397. * @param y define the y coordinate of the source vector
  3398. * @param z define the z coordinate of the source vector
  3399. * @param transformation defines the transformation matrix
  3400. * @param result defines the Vector3 where to store the result
  3401. */
  3402. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3403. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3404. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3405. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3406. };
  3407. /**
  3408. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3409. * @param value1 defines the first control point
  3410. * @param value2 defines the second control point
  3411. * @param value3 defines the third control point
  3412. * @param value4 defines the fourth control point
  3413. * @param amount defines the amount on the spline to use
  3414. * @returns the new Vector3
  3415. */
  3416. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3417. var squared = amount * amount;
  3418. var cubed = amount * squared;
  3419. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3420. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3421. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3422. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3423. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3424. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3425. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3426. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3427. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3428. return new Vector3(x, y, z);
  3429. };
  3430. /**
  3431. * 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"
  3432. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3433. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3434. * @param value defines the current value
  3435. * @param min defines the lower range value
  3436. * @param max defines the upper range value
  3437. * @returns the new Vector3
  3438. */
  3439. Vector3.Clamp = function (value, min, max) {
  3440. var x = value.x;
  3441. x = (x > max.x) ? max.x : x;
  3442. x = (x < min.x) ? min.x : x;
  3443. var y = value.y;
  3444. y = (y > max.y) ? max.y : y;
  3445. y = (y < min.y) ? min.y : y;
  3446. var z = value.z;
  3447. z = (z > max.z) ? max.z : z;
  3448. z = (z < min.z) ? min.z : z;
  3449. return new Vector3(x, y, z);
  3450. };
  3451. /**
  3452. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3453. * @param value1 defines the first control point
  3454. * @param tangent1 defines the first tangent vector
  3455. * @param value2 defines the second control point
  3456. * @param tangent2 defines the second tangent vector
  3457. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3458. * @returns the new Vector3
  3459. */
  3460. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3461. var squared = amount * amount;
  3462. var cubed = amount * squared;
  3463. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3464. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3465. var part3 = (cubed - (2.0 * squared)) + amount;
  3466. var part4 = cubed - squared;
  3467. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3468. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3469. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3470. return new Vector3(x, y, z);
  3471. };
  3472. /**
  3473. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3474. * @param start defines the start value
  3475. * @param end defines the end value
  3476. * @param amount max defines amount between both (between 0 and 1)
  3477. * @returns the new Vector3
  3478. */
  3479. Vector3.Lerp = function (start, end, amount) {
  3480. var result = new Vector3(0, 0, 0);
  3481. Vector3.LerpToRef(start, end, amount, result);
  3482. return result;
  3483. };
  3484. /**
  3485. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3486. * @param start defines the start value
  3487. * @param end defines the end value
  3488. * @param amount max defines amount between both (between 0 and 1)
  3489. * @param result defines the Vector3 where to store the result
  3490. */
  3491. Vector3.LerpToRef = function (start, end, amount, result) {
  3492. result.x = start.x + ((end.x - start.x) * amount);
  3493. result.y = start.y + ((end.y - start.y) * amount);
  3494. result.z = start.z + ((end.z - start.z) * amount);
  3495. };
  3496. /**
  3497. * Returns the dot product (float) between the vectors "left" and "right"
  3498. * @param left defines the left operand
  3499. * @param right defines the right operand
  3500. * @returns the dot product
  3501. */
  3502. Vector3.Dot = function (left, right) {
  3503. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3504. };
  3505. /**
  3506. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3507. * The cross product is then orthogonal to both "left" and "right"
  3508. * @param left defines the left operand
  3509. * @param right defines the right operand
  3510. * @returns the cross product
  3511. */
  3512. Vector3.Cross = function (left, right) {
  3513. var result = Vector3.Zero();
  3514. Vector3.CrossToRef(left, right, result);
  3515. return result;
  3516. };
  3517. /**
  3518. * Sets the given vector "result" with the cross product of "left" and "right"
  3519. * The cross product is then orthogonal to both "left" and "right"
  3520. * @param left defines the left operand
  3521. * @param right defines the right operand
  3522. * @param result defines the Vector3 where to store the result
  3523. */
  3524. Vector3.CrossToRef = function (left, right, result) {
  3525. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3526. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3527. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3528. result.copyFrom(MathTmp.Vector3[0]);
  3529. };
  3530. /**
  3531. * Returns a new Vector3 as the normalization of the given vector
  3532. * @param vector defines the Vector3 to normalize
  3533. * @returns the new Vector3
  3534. */
  3535. Vector3.Normalize = function (vector) {
  3536. var result = Vector3.Zero();
  3537. Vector3.NormalizeToRef(vector, result);
  3538. return result;
  3539. };
  3540. /**
  3541. * Sets the given vector "result" with the normalization of the given first vector
  3542. * @param vector defines the Vector3 to normalize
  3543. * @param result defines the Vector3 where to store the result
  3544. */
  3545. Vector3.NormalizeToRef = function (vector, result) {
  3546. result.copyFrom(vector);
  3547. result.normalize();
  3548. };
  3549. /**
  3550. * Project a Vector3 onto screen space
  3551. * @param vector defines the Vector3 to project
  3552. * @param world defines the world matrix to use
  3553. * @param transform defines the transform (view x projection) matrix to use
  3554. * @param viewport defines the screen viewport to use
  3555. * @returns the new Vector3
  3556. */
  3557. Vector3.Project = function (vector, world, transform, viewport) {
  3558. var cw = viewport.width;
  3559. var ch = viewport.height;
  3560. var cx = viewport.x;
  3561. var cy = viewport.y;
  3562. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3563. 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);
  3564. var matrix = MathTmp.Matrix[0];
  3565. world.multiplyToRef(transform, matrix);
  3566. matrix.multiplyToRef(viewportMatrix, matrix);
  3567. return Vector3.TransformCoordinates(vector, matrix);
  3568. };
  3569. /**
  3570. * Unproject from screen space to object space
  3571. * @param source defines the screen space Vector3 to use
  3572. * @param viewportWidth defines the current width of the viewport
  3573. * @param viewportHeight defines the current height of the viewport
  3574. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3575. * @param transform defines the transform (view x projection) matrix to use
  3576. * @returns the new Vector3
  3577. */
  3578. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3579. var matrix = MathTmp.Matrix[0];
  3580. world.multiplyToRef(transform, matrix);
  3581. matrix.invert();
  3582. source.x = source.x / viewportWidth * 2 - 1;
  3583. source.y = -(source.y / viewportHeight * 2 - 1);
  3584. var vector = Vector3.TransformCoordinates(source, matrix);
  3585. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3586. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3587. vector = vector.scale(1.0 / num);
  3588. }
  3589. return vector;
  3590. };
  3591. /**
  3592. * Unproject from screen space to object space
  3593. * @param source defines the screen space Vector3 to use
  3594. * @param viewportWidth defines the current width of the viewport
  3595. * @param viewportHeight defines the current height of the viewport
  3596. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3597. * @param view defines the view matrix to use
  3598. * @param projection defines the projection matrix to use
  3599. * @returns the new Vector3
  3600. */
  3601. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3602. var result = Vector3.Zero();
  3603. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3604. return result;
  3605. };
  3606. /**
  3607. * Unproject from screen space to object space
  3608. * @param source defines the screen space Vector3 to use
  3609. * @param viewportWidth defines the current width of the viewport
  3610. * @param viewportHeight defines the current height of the viewport
  3611. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3612. * @param view defines the view matrix to use
  3613. * @param projection defines the projection matrix to use
  3614. * @param result defines the Vector3 where to store the result
  3615. */
  3616. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3617. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3618. };
  3619. /**
  3620. * Unproject from screen space to object space
  3621. * @param sourceX defines the screen space x coordinate to use
  3622. * @param sourceY defines the screen space y coordinate to use
  3623. * @param sourceZ defines the screen space z coordinate to use
  3624. * @param viewportWidth defines the current width of the viewport
  3625. * @param viewportHeight defines the current height of the viewport
  3626. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3627. * @param view defines the view matrix to use
  3628. * @param projection defines the projection matrix to use
  3629. * @param result defines the Vector3 where to store the result
  3630. */
  3631. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3632. var matrix = MathTmp.Matrix[0];
  3633. world.multiplyToRef(view, matrix);
  3634. matrix.multiplyToRef(projection, matrix);
  3635. matrix.invert();
  3636. var screenSource = MathTmp.Vector3[0];
  3637. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3638. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3639. screenSource.z = 2 * sourceZ - 1.0;
  3640. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3641. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3642. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3643. result.scaleInPlace(1.0 / num);
  3644. }
  3645. };
  3646. /**
  3647. * Gets the minimal coordinate values between two Vector3
  3648. * @param left defines the first operand
  3649. * @param right defines the second operand
  3650. * @returns the new Vector3
  3651. */
  3652. Vector3.Minimize = function (left, right) {
  3653. var min = left.clone();
  3654. min.minimizeInPlace(right);
  3655. return min;
  3656. };
  3657. /**
  3658. * Gets the maximal coordinate values between two Vector3
  3659. * @param left defines the first operand
  3660. * @param right defines the second operand
  3661. * @returns the new Vector3
  3662. */
  3663. Vector3.Maximize = function (left, right) {
  3664. var max = left.clone();
  3665. max.maximizeInPlace(right);
  3666. return max;
  3667. };
  3668. /**
  3669. * Returns the distance between the vectors "value1" and "value2"
  3670. * @param value1 defines the first operand
  3671. * @param value2 defines the second operand
  3672. * @returns the distance
  3673. */
  3674. Vector3.Distance = function (value1, value2) {
  3675. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3676. };
  3677. /**
  3678. * Returns the squared distance between the vectors "value1" and "value2"
  3679. * @param value1 defines the first operand
  3680. * @param value2 defines the second operand
  3681. * @returns the squared distance
  3682. */
  3683. Vector3.DistanceSquared = function (value1, value2) {
  3684. var x = value1.x - value2.x;
  3685. var y = value1.y - value2.y;
  3686. var z = value1.z - value2.z;
  3687. return (x * x) + (y * y) + (z * z);
  3688. };
  3689. /**
  3690. * Returns a new Vector3 located at the center between "value1" and "value2"
  3691. * @param value1 defines the first operand
  3692. * @param value2 defines the second operand
  3693. * @returns the new Vector3
  3694. */
  3695. Vector3.Center = function (value1, value2) {
  3696. var center = value1.add(value2);
  3697. center.scaleInPlace(0.5);
  3698. return center;
  3699. };
  3700. /**
  3701. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3702. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3703. * to something in order to rotate it from its local system to the given target system
  3704. * Note: axis1, axis2 and axis3 are normalized during this operation
  3705. * @param axis1 defines the first axis
  3706. * @param axis2 defines the second axis
  3707. * @param axis3 defines the third axis
  3708. * @returns a new Vector3
  3709. */
  3710. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3711. var rotation = Vector3.Zero();
  3712. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3713. return rotation;
  3714. };
  3715. /**
  3716. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3717. * @param axis1 defines the first axis
  3718. * @param axis2 defines the second axis
  3719. * @param axis3 defines the third axis
  3720. * @param ref defines the Vector3 where to store the result
  3721. */
  3722. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3723. var quat = MathTmp.Quaternion[0];
  3724. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3725. quat.toEulerAnglesToRef(ref);
  3726. };
  3727. return Vector3;
  3728. }());
  3729. BABYLON.Vector3 = Vector3;
  3730. //Vector4 class created for EulerAngle class conversion to Quaternion
  3731. var Vector4 = /** @class */ (function () {
  3732. /**
  3733. * Creates a Vector4 object from the given floats.
  3734. */
  3735. function Vector4(x, y, z, w) {
  3736. this.x = x;
  3737. this.y = y;
  3738. this.z = z;
  3739. this.w = w;
  3740. }
  3741. /**
  3742. * Returns the string with the Vector4 coordinates.
  3743. */
  3744. Vector4.prototype.toString = function () {
  3745. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3746. };
  3747. /**
  3748. * Returns the string "Vector4".
  3749. */
  3750. Vector4.prototype.getClassName = function () {
  3751. return "Vector4";
  3752. };
  3753. /**
  3754. * Returns the Vector4 hash code.
  3755. */
  3756. Vector4.prototype.getHashCode = function () {
  3757. var hash = this.x || 0;
  3758. hash = (hash * 397) ^ (this.y || 0);
  3759. hash = (hash * 397) ^ (this.z || 0);
  3760. hash = (hash * 397) ^ (this.w || 0);
  3761. return hash;
  3762. };
  3763. // Operators
  3764. /**
  3765. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3766. */
  3767. Vector4.prototype.asArray = function () {
  3768. var result = new Array();
  3769. this.toArray(result, 0);
  3770. return result;
  3771. };
  3772. /**
  3773. * Populates the given array from the given index with the Vector4 coordinates.
  3774. * Returns the Vector4.
  3775. */
  3776. Vector4.prototype.toArray = function (array, index) {
  3777. if (index === undefined) {
  3778. index = 0;
  3779. }
  3780. array[index] = this.x;
  3781. array[index + 1] = this.y;
  3782. array[index + 2] = this.z;
  3783. array[index + 3] = this.w;
  3784. return this;
  3785. };
  3786. /**
  3787. * Adds the given vector to the current Vector4.
  3788. * Returns the updated Vector4.
  3789. */
  3790. Vector4.prototype.addInPlace = function (otherVector) {
  3791. this.x += otherVector.x;
  3792. this.y += otherVector.y;
  3793. this.z += otherVector.z;
  3794. this.w += otherVector.w;
  3795. return this;
  3796. };
  3797. /**
  3798. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3799. */
  3800. Vector4.prototype.add = function (otherVector) {
  3801. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3802. };
  3803. /**
  3804. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3805. * Returns the current Vector4.
  3806. */
  3807. Vector4.prototype.addToRef = function (otherVector, result) {
  3808. result.x = this.x + otherVector.x;
  3809. result.y = this.y + otherVector.y;
  3810. result.z = this.z + otherVector.z;
  3811. result.w = this.w + otherVector.w;
  3812. return this;
  3813. };
  3814. /**
  3815. * Subtract in place the given vector from the current Vector4.
  3816. * Returns the updated Vector4.
  3817. */
  3818. Vector4.prototype.subtractInPlace = function (otherVector) {
  3819. this.x -= otherVector.x;
  3820. this.y -= otherVector.y;
  3821. this.z -= otherVector.z;
  3822. this.w -= otherVector.w;
  3823. return this;
  3824. };
  3825. /**
  3826. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3827. */
  3828. Vector4.prototype.subtract = function (otherVector) {
  3829. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3830. };
  3831. /**
  3832. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3833. * Returns the current Vector4.
  3834. */
  3835. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3836. result.x = this.x - otherVector.x;
  3837. result.y = this.y - otherVector.y;
  3838. result.z = this.z - otherVector.z;
  3839. result.w = this.w - otherVector.w;
  3840. return this;
  3841. };
  3842. /**
  3843. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3844. */
  3845. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3846. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3847. };
  3848. /**
  3849. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3850. * Returns the current Vector4.
  3851. */
  3852. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3853. result.x = this.x - x;
  3854. result.y = this.y - y;
  3855. result.z = this.z - z;
  3856. result.w = this.w - w;
  3857. return this;
  3858. };
  3859. /**
  3860. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3861. */
  3862. Vector4.prototype.negate = function () {
  3863. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3864. };
  3865. /**
  3866. * Multiplies the current Vector4 coordinates by scale (float).
  3867. * Returns the updated Vector4.
  3868. */
  3869. Vector4.prototype.scaleInPlace = function (scale) {
  3870. this.x *= scale;
  3871. this.y *= scale;
  3872. this.z *= scale;
  3873. this.w *= scale;
  3874. return this;
  3875. };
  3876. /**
  3877. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3878. */
  3879. Vector4.prototype.scale = function (scale) {
  3880. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3881. };
  3882. /**
  3883. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3884. * Returns the current Vector4.
  3885. */
  3886. Vector4.prototype.scaleToRef = function (scale, result) {
  3887. result.x = this.x * scale;
  3888. result.y = this.y * scale;
  3889. result.z = this.z * scale;
  3890. result.w = this.w * scale;
  3891. return this;
  3892. };
  3893. /**
  3894. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3895. * @param scale defines the scale factor
  3896. * @param result defines the Vector4 object where to store the result
  3897. * @returns the unmodified current Vector4
  3898. */
  3899. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3900. result.x += this.x * scale;
  3901. result.y += this.y * scale;
  3902. result.z += this.z * scale;
  3903. result.w += this.w * scale;
  3904. return this;
  3905. };
  3906. /**
  3907. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3908. */
  3909. Vector4.prototype.equals = function (otherVector) {
  3910. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3911. };
  3912. /**
  3913. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3914. */
  3915. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3916. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3917. return otherVector
  3918. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3919. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3920. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3921. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3922. };
  3923. /**
  3924. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3925. */
  3926. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3927. return this.x === x && this.y === y && this.z === z && this.w === w;
  3928. };
  3929. /**
  3930. * Multiplies in place the current Vector4 by the given one.
  3931. * Returns the updated Vector4.
  3932. */
  3933. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3934. this.x *= otherVector.x;
  3935. this.y *= otherVector.y;
  3936. this.z *= otherVector.z;
  3937. this.w *= otherVector.w;
  3938. return this;
  3939. };
  3940. /**
  3941. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3942. */
  3943. Vector4.prototype.multiply = function (otherVector) {
  3944. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3945. };
  3946. /**
  3947. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3948. * Returns the current Vector4.
  3949. */
  3950. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3951. result.x = this.x * otherVector.x;
  3952. result.y = this.y * otherVector.y;
  3953. result.z = this.z * otherVector.z;
  3954. result.w = this.w * otherVector.w;
  3955. return this;
  3956. };
  3957. /**
  3958. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3959. */
  3960. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3961. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3962. };
  3963. /**
  3964. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3965. */
  3966. Vector4.prototype.divide = function (otherVector) {
  3967. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3968. };
  3969. /**
  3970. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3971. * Returns the current Vector4.
  3972. */
  3973. Vector4.prototype.divideToRef = function (otherVector, result) {
  3974. result.x = this.x / otherVector.x;
  3975. result.y = this.y / otherVector.y;
  3976. result.z = this.z / otherVector.z;
  3977. result.w = this.w / otherVector.w;
  3978. return this;
  3979. };
  3980. /**
  3981. * Divides the current Vector3 coordinates by the given ones.
  3982. * @returns the updated Vector3.
  3983. */
  3984. Vector4.prototype.divideInPlace = function (otherVector) {
  3985. return this.divideToRef(otherVector, this);
  3986. };
  3987. /**
  3988. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  3989. * @param other defines the second operand
  3990. * @returns the current updated Vector4
  3991. */
  3992. Vector4.prototype.minimizeInPlace = function (other) {
  3993. if (other.x < this.x)
  3994. this.x = other.x;
  3995. if (other.y < this.y)
  3996. this.y = other.y;
  3997. if (other.z < this.z)
  3998. this.z = other.z;
  3999. if (other.w < this.w)
  4000. this.w = other.w;
  4001. return this;
  4002. };
  4003. /**
  4004. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4005. * @param other defines the second operand
  4006. * @returns the current updated Vector4
  4007. */
  4008. Vector4.prototype.maximizeInPlace = function (other) {
  4009. if (other.x > this.x)
  4010. this.x = other.x;
  4011. if (other.y > this.y)
  4012. this.y = other.y;
  4013. if (other.z > this.z)
  4014. this.z = other.z;
  4015. if (other.w > this.w)
  4016. this.w = other.w;
  4017. return this;
  4018. };
  4019. // Properties
  4020. /**
  4021. * Returns the Vector4 length (float).
  4022. */
  4023. Vector4.prototype.length = function () {
  4024. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4025. };
  4026. /**
  4027. * Returns the Vector4 squared length (float).
  4028. */
  4029. Vector4.prototype.lengthSquared = function () {
  4030. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4031. };
  4032. // Methods
  4033. /**
  4034. * Normalizes in place the Vector4.
  4035. * Returns the updated Vector4.
  4036. */
  4037. Vector4.prototype.normalize = function () {
  4038. var len = this.length();
  4039. if (len === 0)
  4040. return this;
  4041. var num = 1.0 / len;
  4042. this.x *= num;
  4043. this.y *= num;
  4044. this.z *= num;
  4045. this.w *= num;
  4046. return this;
  4047. };
  4048. /**
  4049. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4050. */
  4051. Vector4.prototype.toVector3 = function () {
  4052. return new Vector3(this.x, this.y, this.z);
  4053. };
  4054. /**
  4055. * Returns a new Vector4 copied from the current one.
  4056. */
  4057. Vector4.prototype.clone = function () {
  4058. return new Vector4(this.x, this.y, this.z, this.w);
  4059. };
  4060. /**
  4061. * Updates the current Vector4 with the given one coordinates.
  4062. * Returns the updated Vector4.
  4063. */
  4064. Vector4.prototype.copyFrom = function (source) {
  4065. this.x = source.x;
  4066. this.y = source.y;
  4067. this.z = source.z;
  4068. this.w = source.w;
  4069. return this;
  4070. };
  4071. /**
  4072. * Updates the current Vector4 coordinates with the given floats.
  4073. * Returns the updated Vector4.
  4074. */
  4075. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4076. this.x = x;
  4077. this.y = y;
  4078. this.z = z;
  4079. this.w = w;
  4080. return this;
  4081. };
  4082. /**
  4083. * Updates the current Vector4 coordinates with the given floats.
  4084. * Returns the updated Vector4.
  4085. */
  4086. Vector4.prototype.set = function (x, y, z, w) {
  4087. return this.copyFromFloats(x, y, z, w);
  4088. };
  4089. // Statics
  4090. /**
  4091. * Returns a new Vector4 set from the starting index of the given array.
  4092. */
  4093. Vector4.FromArray = function (array, offset) {
  4094. if (!offset) {
  4095. offset = 0;
  4096. }
  4097. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4098. };
  4099. /**
  4100. * Updates the given vector "result" from the starting index of the given array.
  4101. */
  4102. Vector4.FromArrayToRef = function (array, offset, result) {
  4103. result.x = array[offset];
  4104. result.y = array[offset + 1];
  4105. result.z = array[offset + 2];
  4106. result.w = array[offset + 3];
  4107. };
  4108. /**
  4109. * Updates the given vector "result" from the starting index of the given Float32Array.
  4110. */
  4111. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4112. Vector4.FromArrayToRef(array, offset, result);
  4113. };
  4114. /**
  4115. * Updates the given vector "result" coordinates from the given floats.
  4116. */
  4117. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4118. result.x = x;
  4119. result.y = y;
  4120. result.z = z;
  4121. result.w = w;
  4122. };
  4123. /**
  4124. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4125. */
  4126. Vector4.Zero = function () {
  4127. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4128. };
  4129. /**
  4130. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4131. */
  4132. Vector4.One = function () {
  4133. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4134. };
  4135. /**
  4136. * Returns a new normalized Vector4 from the given one.
  4137. */
  4138. Vector4.Normalize = function (vector) {
  4139. var result = Vector4.Zero();
  4140. Vector4.NormalizeToRef(vector, result);
  4141. return result;
  4142. };
  4143. /**
  4144. * Updates the given vector "result" from the normalization of the given one.
  4145. */
  4146. Vector4.NormalizeToRef = function (vector, result) {
  4147. result.copyFrom(vector);
  4148. result.normalize();
  4149. };
  4150. Vector4.Minimize = function (left, right) {
  4151. var min = left.clone();
  4152. min.minimizeInPlace(right);
  4153. return min;
  4154. };
  4155. Vector4.Maximize = function (left, right) {
  4156. var max = left.clone();
  4157. max.maximizeInPlace(right);
  4158. return max;
  4159. };
  4160. /**
  4161. * Returns the distance (float) between the vectors "value1" and "value2".
  4162. */
  4163. Vector4.Distance = function (value1, value2) {
  4164. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4165. };
  4166. /**
  4167. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4168. */
  4169. Vector4.DistanceSquared = function (value1, value2) {
  4170. var x = value1.x - value2.x;
  4171. var y = value1.y - value2.y;
  4172. var z = value1.z - value2.z;
  4173. var w = value1.w - value2.w;
  4174. return (x * x) + (y * y) + (z * z) + (w * w);
  4175. };
  4176. /**
  4177. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4178. */
  4179. Vector4.Center = function (value1, value2) {
  4180. var center = value1.add(value2);
  4181. center.scaleInPlace(0.5);
  4182. return center;
  4183. };
  4184. /**
  4185. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4186. * This methods computes transformed normalized direction vectors only.
  4187. */
  4188. Vector4.TransformNormal = function (vector, transformation) {
  4189. var result = Vector4.Zero();
  4190. Vector4.TransformNormalToRef(vector, transformation, result);
  4191. return result;
  4192. };
  4193. /**
  4194. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4195. * This methods computes transformed normalized direction vectors only.
  4196. */
  4197. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4198. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4199. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4200. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4201. result.x = x;
  4202. result.y = y;
  4203. result.z = z;
  4204. result.w = vector.w;
  4205. };
  4206. /**
  4207. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4208. * This methods computes transformed normalized direction vectors only.
  4209. */
  4210. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4211. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4212. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4213. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4214. result.w = w;
  4215. };
  4216. return Vector4;
  4217. }());
  4218. BABYLON.Vector4 = Vector4;
  4219. var Size = /** @class */ (function () {
  4220. /**
  4221. * Creates a Size object from the given width and height (floats).
  4222. */
  4223. function Size(width, height) {
  4224. this.width = width;
  4225. this.height = height;
  4226. }
  4227. // Returns a string with the Size width and height.
  4228. Size.prototype.toString = function () {
  4229. return "{W: " + this.width + ", H: " + this.height + "}";
  4230. };
  4231. /**
  4232. * Returns the string "Size"
  4233. */
  4234. Size.prototype.getClassName = function () {
  4235. return "Size";
  4236. };
  4237. /**
  4238. * Returns the Size hash code.
  4239. */
  4240. Size.prototype.getHashCode = function () {
  4241. var hash = this.width || 0;
  4242. hash = (hash * 397) ^ (this.height || 0);
  4243. return hash;
  4244. };
  4245. /**
  4246. * Updates the current size from the given one.
  4247. * Returns the updated Size.
  4248. */
  4249. Size.prototype.copyFrom = function (src) {
  4250. this.width = src.width;
  4251. this.height = src.height;
  4252. };
  4253. /**
  4254. * Updates in place the current Size from the given floats.
  4255. * Returns the updated Size.
  4256. */
  4257. Size.prototype.copyFromFloats = function (width, height) {
  4258. this.width = width;
  4259. this.height = height;
  4260. return this;
  4261. };
  4262. /**
  4263. * Updates in place the current Size from the given floats.
  4264. * Returns the updated Size.
  4265. */
  4266. Size.prototype.set = function (width, height) {
  4267. return this.copyFromFloats(width, height);
  4268. };
  4269. /**
  4270. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4271. */
  4272. Size.prototype.multiplyByFloats = function (w, h) {
  4273. return new Size(this.width * w, this.height * h);
  4274. };
  4275. /**
  4276. * Returns a new Size copied from the given one.
  4277. */
  4278. Size.prototype.clone = function () {
  4279. return new Size(this.width, this.height);
  4280. };
  4281. /**
  4282. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4283. */
  4284. Size.prototype.equals = function (other) {
  4285. if (!other) {
  4286. return false;
  4287. }
  4288. return (this.width === other.width) && (this.height === other.height);
  4289. };
  4290. Object.defineProperty(Size.prototype, "surface", {
  4291. /**
  4292. * Returns the surface of the Size : width * height (float).
  4293. */
  4294. get: function () {
  4295. return this.width * this.height;
  4296. },
  4297. enumerable: true,
  4298. configurable: true
  4299. });
  4300. /**
  4301. * Returns a new Size set to (0.0, 0.0)
  4302. */
  4303. Size.Zero = function () {
  4304. return new Size(0.0, 0.0);
  4305. };
  4306. /**
  4307. * Returns a new Size set as the addition result of the current Size and the given one.
  4308. */
  4309. Size.prototype.add = function (otherSize) {
  4310. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4311. return r;
  4312. };
  4313. /**
  4314. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4315. */
  4316. Size.prototype.subtract = function (otherSize) {
  4317. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4318. return r;
  4319. };
  4320. /**
  4321. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4322. */
  4323. Size.Lerp = function (start, end, amount) {
  4324. var w = start.width + ((end.width - start.width) * amount);
  4325. var h = start.height + ((end.height - start.height) * amount);
  4326. return new Size(w, h);
  4327. };
  4328. return Size;
  4329. }());
  4330. BABYLON.Size = Size;
  4331. /**
  4332. * Class used to store quaternion data
  4333. * @see https://en.wikipedia.org/wiki/Quaternion
  4334. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4335. */
  4336. var Quaternion = /** @class */ (function () {
  4337. /**
  4338. * Creates a new Quaternion from the given floats
  4339. * @param x defines the first component (0 by default)
  4340. * @param y defines the second component (0 by default)
  4341. * @param z defines the third component (0 by default)
  4342. * @param w defines the fourth component (1.0 by default)
  4343. */
  4344. function Quaternion(
  4345. /** defines the first component (0 by default) */
  4346. x,
  4347. /** defines the second component (0 by default) */
  4348. y,
  4349. /** defines the third component (0 by default) */
  4350. z,
  4351. /** defines the fourth component (1.0 by default) */
  4352. w) {
  4353. if (x === void 0) { x = 0.0; }
  4354. if (y === void 0) { y = 0.0; }
  4355. if (z === void 0) { z = 0.0; }
  4356. if (w === void 0) { w = 1.0; }
  4357. this.x = x;
  4358. this.y = y;
  4359. this.z = z;
  4360. this.w = w;
  4361. }
  4362. /**
  4363. * Gets a string representation for the current quaternion
  4364. * @returns a string with the Quaternion coordinates
  4365. */
  4366. Quaternion.prototype.toString = function () {
  4367. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4368. };
  4369. /**
  4370. * Gets the class name of the quaternion
  4371. * @returns the string "Quaternion"
  4372. */
  4373. Quaternion.prototype.getClassName = function () {
  4374. return "Quaternion";
  4375. };
  4376. /**
  4377. * Gets a hash code for this quaternion
  4378. * @returns the quaternion hash code
  4379. */
  4380. Quaternion.prototype.getHashCode = function () {
  4381. var hash = this.x || 0;
  4382. hash = (hash * 397) ^ (this.y || 0);
  4383. hash = (hash * 397) ^ (this.z || 0);
  4384. hash = (hash * 397) ^ (this.w || 0);
  4385. return hash;
  4386. };
  4387. /**
  4388. * Copy the quaternion to an array
  4389. * @returns a new array populated with 4 elements from the quaternion coordinates
  4390. */
  4391. Quaternion.prototype.asArray = function () {
  4392. return [this.x, this.y, this.z, this.w];
  4393. };
  4394. /**
  4395. * Check if two quaternions are equals
  4396. * @param otherQuaternion defines the second operand
  4397. * @return true if the current quaternion and the given one coordinates are strictly equals
  4398. */
  4399. Quaternion.prototype.equals = function (otherQuaternion) {
  4400. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4401. };
  4402. /**
  4403. * Clone the current quaternion
  4404. * @returns a new quaternion copied from the current one
  4405. */
  4406. Quaternion.prototype.clone = function () {
  4407. return new Quaternion(this.x, this.y, this.z, this.w);
  4408. };
  4409. /**
  4410. * Copy a quaternion to the current one
  4411. * @param other defines the other quaternion
  4412. * @returns the updated current quaternion
  4413. */
  4414. Quaternion.prototype.copyFrom = function (other) {
  4415. this.x = other.x;
  4416. this.y = other.y;
  4417. this.z = other.z;
  4418. this.w = other.w;
  4419. return this;
  4420. };
  4421. /**
  4422. * Updates the current quaternion with the given float coordinates
  4423. * @param x defines the x coordinate
  4424. * @param y defines the y coordinate
  4425. * @param z defines the z coordinate
  4426. * @param w defines the w coordinate
  4427. * @returns the updated current quaternion
  4428. */
  4429. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4430. this.x = x;
  4431. this.y = y;
  4432. this.z = z;
  4433. this.w = w;
  4434. return this;
  4435. };
  4436. /**
  4437. * Updates the current quaternion from the given float coordinates
  4438. * @param x defines the x coordinate
  4439. * @param y defines the y coordinate
  4440. * @param z defines the z coordinate
  4441. * @param w defines the w coordinate
  4442. * @returns the updated current quaternion
  4443. */
  4444. Quaternion.prototype.set = function (x, y, z, w) {
  4445. return this.copyFromFloats(x, y, z, w);
  4446. };
  4447. /**
  4448. * Adds two quaternions
  4449. * @param other defines the second operand
  4450. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4451. */
  4452. Quaternion.prototype.add = function (other) {
  4453. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4454. };
  4455. /**
  4456. * Add a quaternion to the current one
  4457. * @param other defines the quaternion to add
  4458. * @returns the current quaternion
  4459. */
  4460. Quaternion.prototype.addInPlace = function (other) {
  4461. this.x += other.x;
  4462. this.y += other.y;
  4463. this.z += other.z;
  4464. this.w += other.w;
  4465. return this;
  4466. };
  4467. /**
  4468. * Subtract two quaternions
  4469. * @param other defines the second operand
  4470. * @returns a new quaternion as the subtraction result of the given one from the current one
  4471. */
  4472. Quaternion.prototype.subtract = function (other) {
  4473. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4474. };
  4475. /**
  4476. * Multiplies the current quaternion by a scale factor
  4477. * @param value defines the scale factor
  4478. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4479. */
  4480. Quaternion.prototype.scale = function (value) {
  4481. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4482. };
  4483. /**
  4484. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4485. * @param scale defines the scale factor
  4486. * @param result defines the Quaternion object where to store the result
  4487. * @returns the unmodified current quaternion
  4488. */
  4489. Quaternion.prototype.scaleToRef = function (scale, result) {
  4490. result.x = this.x * scale;
  4491. result.y = this.y * scale;
  4492. result.z = this.z * scale;
  4493. result.w = this.w * scale;
  4494. return this;
  4495. };
  4496. /**
  4497. * Multiplies in place the current quaternion by a scale factor
  4498. * @param value defines the scale factor
  4499. * @returns the current modified quaternion
  4500. */
  4501. Quaternion.prototype.scaleInPlace = function (value) {
  4502. this.x *= value;
  4503. this.y *= value;
  4504. this.z *= value;
  4505. this.w *= value;
  4506. return this;
  4507. };
  4508. /**
  4509. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4510. * @param scale defines the scale factor
  4511. * @param result defines the Quaternion object where to store the result
  4512. * @returns the unmodified current quaternion
  4513. */
  4514. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4515. result.x += this.x * scale;
  4516. result.y += this.y * scale;
  4517. result.z += this.z * scale;
  4518. result.w += this.w * scale;
  4519. return this;
  4520. };
  4521. /**
  4522. * Multiplies two quaternions
  4523. * @param q1 defines the second operand
  4524. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4525. */
  4526. Quaternion.prototype.multiply = function (q1) {
  4527. var result = new Quaternion(0, 0, 0, 1.0);
  4528. this.multiplyToRef(q1, result);
  4529. return result;
  4530. };
  4531. /**
  4532. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4533. * @param q1 defines the second operand
  4534. * @param result defines the target quaternion
  4535. * @returns the current quaternion
  4536. */
  4537. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4538. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4539. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4540. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4541. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4542. result.copyFromFloats(x, y, z, w);
  4543. return this;
  4544. };
  4545. /**
  4546. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4547. * @param q1 defines the second operand
  4548. * @returns the currentupdated quaternion
  4549. */
  4550. Quaternion.prototype.multiplyInPlace = function (q1) {
  4551. this.multiplyToRef(q1, this);
  4552. return this;
  4553. };
  4554. /**
  4555. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4556. * @param ref defines the target quaternion
  4557. * @returns the current quaternion
  4558. */
  4559. Quaternion.prototype.conjugateToRef = function (ref) {
  4560. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4561. return this;
  4562. };
  4563. /**
  4564. * Conjugates in place (1-q) the current quaternion
  4565. * @returns the current updated quaternion
  4566. */
  4567. Quaternion.prototype.conjugateInPlace = function () {
  4568. this.x *= -1;
  4569. this.y *= -1;
  4570. this.z *= -1;
  4571. return this;
  4572. };
  4573. /**
  4574. * Conjugates in place (1-q) the current quaternion
  4575. * @returns a new quaternion
  4576. */
  4577. Quaternion.prototype.conjugate = function () {
  4578. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4579. return result;
  4580. };
  4581. /**
  4582. * Gets length of current quaternion
  4583. * @returns the quaternion length (float)
  4584. */
  4585. Quaternion.prototype.length = function () {
  4586. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4587. };
  4588. /**
  4589. * Normalize in place the current quaternion
  4590. * @returns the current updated quaternion
  4591. */
  4592. Quaternion.prototype.normalize = function () {
  4593. var length = 1.0 / this.length();
  4594. this.x *= length;
  4595. this.y *= length;
  4596. this.z *= length;
  4597. this.w *= length;
  4598. return this;
  4599. };
  4600. /**
  4601. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4602. * @param order is a reserved parameter and is ignore for now
  4603. * @returns a new Vector3 containing the Euler angles
  4604. */
  4605. Quaternion.prototype.toEulerAngles = function (order) {
  4606. if (order === void 0) { order = "YZX"; }
  4607. var result = Vector3.Zero();
  4608. this.toEulerAnglesToRef(result, order);
  4609. return result;
  4610. };
  4611. /**
  4612. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4613. * @param result defines the vector which will be filled with the Euler angles
  4614. * @param order is a reserved parameter and is ignore for now
  4615. * @returns the current unchanged quaternion
  4616. */
  4617. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4618. if (order === void 0) { order = "YZX"; }
  4619. var qz = this.z;
  4620. var qx = this.x;
  4621. var qy = this.y;
  4622. var qw = this.w;
  4623. var sqw = qw * qw;
  4624. var sqz = qz * qz;
  4625. var sqx = qx * qx;
  4626. var sqy = qy * qy;
  4627. var zAxisY = qy * qz - qx * qw;
  4628. var limit = .4999999;
  4629. if (zAxisY < -limit) {
  4630. result.y = 2 * Math.atan2(qy, qw);
  4631. result.x = Math.PI / 2;
  4632. result.z = 0;
  4633. }
  4634. else if (zAxisY > limit) {
  4635. result.y = 2 * Math.atan2(qy, qw);
  4636. result.x = -Math.PI / 2;
  4637. result.z = 0;
  4638. }
  4639. else {
  4640. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4641. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4642. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4643. }
  4644. return this;
  4645. };
  4646. /**
  4647. * Updates the given rotation matrix with the current quaternion values
  4648. * @param result defines the target matrix
  4649. * @returns the current unchanged quaternion
  4650. */
  4651. Quaternion.prototype.toRotationMatrix = function (result) {
  4652. var xx = this.x * this.x;
  4653. var yy = this.y * this.y;
  4654. var zz = this.z * this.z;
  4655. var xy = this.x * this.y;
  4656. var zw = this.z * this.w;
  4657. var zx = this.z * this.x;
  4658. var yw = this.y * this.w;
  4659. var yz = this.y * this.z;
  4660. var xw = this.x * this.w;
  4661. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4662. result.m[1] = 2.0 * (xy + zw);
  4663. result.m[2] = 2.0 * (zx - yw);
  4664. result.m[3] = 0;
  4665. result.m[4] = 2.0 * (xy - zw);
  4666. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4667. result.m[6] = 2.0 * (yz + xw);
  4668. result.m[7] = 0;
  4669. result.m[8] = 2.0 * (zx + yw);
  4670. result.m[9] = 2.0 * (yz - xw);
  4671. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4672. result.m[11] = 0;
  4673. result.m[12] = 0;
  4674. result.m[13] = 0;
  4675. result.m[14] = 0;
  4676. result.m[15] = 1.0;
  4677. result._markAsUpdated();
  4678. return this;
  4679. };
  4680. /**
  4681. * Updates the current quaternion from the given rotation matrix values
  4682. * @param matrix defines the source matrix
  4683. * @returns the current updated quaternion
  4684. */
  4685. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4686. Quaternion.FromRotationMatrixToRef(matrix, this);
  4687. return this;
  4688. };
  4689. // Statics
  4690. /**
  4691. * Creates a new quaternion from a rotation matrix
  4692. * @param matrix defines the source matrix
  4693. * @returns a new quaternion created from the given rotation matrix values
  4694. */
  4695. Quaternion.FromRotationMatrix = function (matrix) {
  4696. var result = new Quaternion();
  4697. Quaternion.FromRotationMatrixToRef(matrix, result);
  4698. return result;
  4699. };
  4700. /**
  4701. * Updates the given quaternion with the given rotation matrix values
  4702. * @param matrix defines the source matrix
  4703. * @param result defines the target quaternion
  4704. */
  4705. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4706. var data = matrix.m;
  4707. var m11 = data[0], m12 = data[4], m13 = data[8];
  4708. var m21 = data[1], m22 = data[5], m23 = data[9];
  4709. var m31 = data[2], m32 = data[6], m33 = data[10];
  4710. var trace = m11 + m22 + m33;
  4711. var s;
  4712. if (trace > 0) {
  4713. s = 0.5 / Math.sqrt(trace + 1.0);
  4714. result.w = 0.25 / s;
  4715. result.x = (m32 - m23) * s;
  4716. result.y = (m13 - m31) * s;
  4717. result.z = (m21 - m12) * s;
  4718. }
  4719. else if (m11 > m22 && m11 > m33) {
  4720. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4721. result.w = (m32 - m23) / s;
  4722. result.x = 0.25 * s;
  4723. result.y = (m12 + m21) / s;
  4724. result.z = (m13 + m31) / s;
  4725. }
  4726. else if (m22 > m33) {
  4727. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4728. result.w = (m13 - m31) / s;
  4729. result.x = (m12 + m21) / s;
  4730. result.y = 0.25 * s;
  4731. result.z = (m23 + m32) / s;
  4732. }
  4733. else {
  4734. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4735. result.w = (m21 - m12) / s;
  4736. result.x = (m13 + m31) / s;
  4737. result.y = (m23 + m32) / s;
  4738. result.z = 0.25 * s;
  4739. }
  4740. };
  4741. /**
  4742. * Creates an empty quaternion
  4743. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4744. */
  4745. Quaternion.Zero = function () {
  4746. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4747. };
  4748. /**
  4749. * Inverse a given quaternion
  4750. * @param q defines the source quaternion
  4751. * @returns a new quaternion as the inverted current quaternion
  4752. */
  4753. Quaternion.Inverse = function (q) {
  4754. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4755. };
  4756. /**
  4757. * Creates an identity quaternion
  4758. * @returns the identity quaternion
  4759. */
  4760. Quaternion.Identity = function () {
  4761. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4762. };
  4763. /**
  4764. * Gets a boolean indicating if the given quaternion is identity
  4765. * @param quaternion defines the quaternion to check
  4766. * @returns true if the quaternion is identity
  4767. */
  4768. Quaternion.IsIdentity = function (quaternion) {
  4769. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4770. };
  4771. /**
  4772. * Creates a quaternion from a rotation around an axis
  4773. * @param axis defines the axis to use
  4774. * @param angle defines the angle to use
  4775. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4776. */
  4777. Quaternion.RotationAxis = function (axis, angle) {
  4778. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4779. };
  4780. /**
  4781. * Creates a rotation around an axis and stores it into the given quaternion
  4782. * @param axis defines the axis to use
  4783. * @param angle defines the angle to use
  4784. * @param result defines the target quaternion
  4785. * @returns the target quaternion
  4786. */
  4787. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4788. var sin = Math.sin(angle / 2);
  4789. axis.normalize();
  4790. result.w = Math.cos(angle / 2);
  4791. result.x = axis.x * sin;
  4792. result.y = axis.y * sin;
  4793. result.z = axis.z * sin;
  4794. return result;
  4795. };
  4796. /**
  4797. * Creates a new quaternion from data stored into an array
  4798. * @param array defines the data source
  4799. * @param offset defines the offset in the source array where the data starts
  4800. * @returns a new quaternion
  4801. */
  4802. Quaternion.FromArray = function (array, offset) {
  4803. if (!offset) {
  4804. offset = 0;
  4805. }
  4806. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4807. };
  4808. /**
  4809. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4810. * @param yaw defines the rotation around Y axis
  4811. * @param pitch defines the rotation around X axis
  4812. * @param roll defines the rotation around Z axis
  4813. * @returns the new quaternion
  4814. */
  4815. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4816. var q = new Quaternion();
  4817. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4818. return q;
  4819. };
  4820. /**
  4821. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4822. * @param yaw defines the rotation around Y axis
  4823. * @param pitch defines the rotation around X axis
  4824. * @param roll defines the rotation around Z axis
  4825. * @param result defines the target quaternion
  4826. */
  4827. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4828. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4829. var halfRoll = roll * 0.5;
  4830. var halfPitch = pitch * 0.5;
  4831. var halfYaw = yaw * 0.5;
  4832. var sinRoll = Math.sin(halfRoll);
  4833. var cosRoll = Math.cos(halfRoll);
  4834. var sinPitch = Math.sin(halfPitch);
  4835. var cosPitch = Math.cos(halfPitch);
  4836. var sinYaw = Math.sin(halfYaw);
  4837. var cosYaw = Math.cos(halfYaw);
  4838. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4839. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4840. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4841. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4842. };
  4843. /**
  4844. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4845. * @param alpha defines the rotation around first axis
  4846. * @param beta defines the rotation around second axis
  4847. * @param gamma defines the rotation around third axis
  4848. * @returns the new quaternion
  4849. */
  4850. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4851. var result = new Quaternion();
  4852. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4853. return result;
  4854. };
  4855. /**
  4856. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4857. * @param alpha defines the rotation around first axis
  4858. * @param beta defines the rotation around second axis
  4859. * @param gamma defines the rotation around third axis
  4860. * @param result defines the target quaternion
  4861. */
  4862. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4863. // Produces a quaternion from Euler angles in the z-x-z orientation
  4864. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4865. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4866. var halfBeta = beta * 0.5;
  4867. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4868. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4869. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4870. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4871. };
  4872. /**
  4873. * 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)
  4874. * @param axis1 defines the first axis
  4875. * @param axis2 defines the second axis
  4876. * @param axis3 defines the third axis
  4877. * @returns the new quaternion
  4878. */
  4879. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4880. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4881. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4882. return quat;
  4883. };
  4884. /**
  4885. * 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
  4886. * @param axis1 defines the first axis
  4887. * @param axis2 defines the second axis
  4888. * @param axis3 defines the third axis
  4889. * @param ref defines the target quaternion
  4890. */
  4891. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4892. var rotMat = MathTmp.Matrix[0];
  4893. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4894. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4895. };
  4896. /**
  4897. * Interpolates between two quaternions
  4898. * @param left defines first quaternion
  4899. * @param right defines second quaternion
  4900. * @param amount defines the gradient to use
  4901. * @returns the new interpolated quaternion
  4902. */
  4903. Quaternion.Slerp = function (left, right, amount) {
  4904. var result = Quaternion.Identity();
  4905. Quaternion.SlerpToRef(left, right, amount, result);
  4906. return result;
  4907. };
  4908. /**
  4909. * Interpolates between two quaternions and stores it into a target quaternion
  4910. * @param left defines first quaternion
  4911. * @param right defines second quaternion
  4912. * @param amount defines the gradient to use
  4913. * @param result defines the target quaternion
  4914. */
  4915. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4916. var num2;
  4917. var num3;
  4918. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4919. var flag = false;
  4920. if (num4 < 0) {
  4921. flag = true;
  4922. num4 = -num4;
  4923. }
  4924. if (num4 > 0.999999) {
  4925. num3 = 1 - amount;
  4926. num2 = flag ? -amount : amount;
  4927. }
  4928. else {
  4929. var num5 = Math.acos(num4);
  4930. var num6 = (1.0 / Math.sin(num5));
  4931. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4932. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4933. }
  4934. result.x = (num3 * left.x) + (num2 * right.x);
  4935. result.y = (num3 * left.y) + (num2 * right.y);
  4936. result.z = (num3 * left.z) + (num2 * right.z);
  4937. result.w = (num3 * left.w) + (num2 * right.w);
  4938. };
  4939. /**
  4940. * Interpolate between two quaternions using Hermite interpolation
  4941. * @param value1 defines first quaternion
  4942. * @param tangent1 defines the incoming tangent
  4943. * @param value2 defines second quaternion
  4944. * @param tangent2 defines the outgoing tangent
  4945. * @param amount defines the target quaternion
  4946. * @returns the new interpolated quaternion
  4947. */
  4948. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4949. var squared = amount * amount;
  4950. var cubed = amount * squared;
  4951. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4952. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4953. var part3 = (cubed - (2.0 * squared)) + amount;
  4954. var part4 = cubed - squared;
  4955. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4956. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4957. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4958. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4959. return new Quaternion(x, y, z, w);
  4960. };
  4961. return Quaternion;
  4962. }());
  4963. BABYLON.Quaternion = Quaternion;
  4964. /**
  4965. * Class used to store matrix data (4x4)
  4966. */
  4967. var Matrix = /** @class */ (function () {
  4968. /**
  4969. * Creates an empty matrix (filled with zeros)
  4970. */
  4971. function Matrix() {
  4972. this._isIdentity = false;
  4973. this._isIdentityDirty = true;
  4974. /**
  4975. * Gets or sets the internal data of the matrix
  4976. */
  4977. this.m = new Float32Array(16);
  4978. this._markAsUpdated();
  4979. }
  4980. /** @hidden */
  4981. Matrix.prototype._markAsUpdated = function () {
  4982. this.updateFlag = Matrix._updateFlagSeed++;
  4983. this._isIdentityDirty = true;
  4984. };
  4985. // Properties
  4986. /**
  4987. * Check if the current matrix is indentity
  4988. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  4989. * @returns true is the matrix is the identity matrix
  4990. */
  4991. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4992. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4993. if (this._isIdentityDirty) {
  4994. this._isIdentityDirty = false;
  4995. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4996. this._isIdentity = false;
  4997. }
  4998. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4999. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5000. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5001. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5002. this._isIdentity = false;
  5003. }
  5004. else {
  5005. this._isIdentity = true;
  5006. }
  5007. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5008. this._isIdentity = false;
  5009. }
  5010. }
  5011. return this._isIdentity;
  5012. };
  5013. /**
  5014. * Gets the determinant of the matrix
  5015. * @returns the matrix determinant
  5016. */
  5017. Matrix.prototype.determinant = function () {
  5018. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5019. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5020. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5021. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5022. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5023. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5024. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5025. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5026. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5027. };
  5028. // Methods
  5029. /**
  5030. * Returns the matrix as a Float32Array
  5031. * @returns the matrix underlying array
  5032. */
  5033. Matrix.prototype.toArray = function () {
  5034. return this.m;
  5035. };
  5036. /**
  5037. * Returns the matrix as a Float32Array
  5038. * @returns the matrix underlying array.
  5039. */
  5040. Matrix.prototype.asArray = function () {
  5041. return this.toArray();
  5042. };
  5043. /**
  5044. * Inverts the current matrix in place
  5045. * @returns the current inverted matrix
  5046. */
  5047. Matrix.prototype.invert = function () {
  5048. this.invertToRef(this);
  5049. return this;
  5050. };
  5051. /**
  5052. * Sets all the matrix elements to zero
  5053. * @returns the current matrix
  5054. */
  5055. Matrix.prototype.reset = function () {
  5056. for (var index = 0; index < 16; index++) {
  5057. this.m[index] = 0.0;
  5058. }
  5059. this._markAsUpdated();
  5060. return this;
  5061. };
  5062. /**
  5063. * Adds the current matrix with a second one
  5064. * @param other defines the matrix to add
  5065. * @returns a new matrix as the addition of the current matrix and the given one
  5066. */
  5067. Matrix.prototype.add = function (other) {
  5068. var result = new Matrix();
  5069. this.addToRef(other, result);
  5070. return result;
  5071. };
  5072. /**
  5073. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5074. * @param other defines the matrix to add
  5075. * @param result defines the target matrix
  5076. * @returns the current matrix
  5077. */
  5078. Matrix.prototype.addToRef = function (other, result) {
  5079. for (var index = 0; index < 16; index++) {
  5080. result.m[index] = this.m[index] + other.m[index];
  5081. }
  5082. result._markAsUpdated();
  5083. return this;
  5084. };
  5085. /**
  5086. * Adds in place the given matrix to the current matrix
  5087. * @param other defines the second operand
  5088. * @returns the current updated matrix
  5089. */
  5090. Matrix.prototype.addToSelf = function (other) {
  5091. for (var index = 0; index < 16; index++) {
  5092. this.m[index] += other.m[index];
  5093. }
  5094. this._markAsUpdated();
  5095. return this;
  5096. };
  5097. /**
  5098. * Sets the given matrix to the current inverted Matrix
  5099. * @param other defines the target matrix
  5100. * @returns the unmodified current matrix
  5101. */
  5102. Matrix.prototype.invertToRef = function (other) {
  5103. var l1 = this.m[0];
  5104. var l2 = this.m[1];
  5105. var l3 = this.m[2];
  5106. var l4 = this.m[3];
  5107. var l5 = this.m[4];
  5108. var l6 = this.m[5];
  5109. var l7 = this.m[6];
  5110. var l8 = this.m[7];
  5111. var l9 = this.m[8];
  5112. var l10 = this.m[9];
  5113. var l11 = this.m[10];
  5114. var l12 = this.m[11];
  5115. var l13 = this.m[12];
  5116. var l14 = this.m[13];
  5117. var l15 = this.m[14];
  5118. var l16 = this.m[15];
  5119. var l17 = (l11 * l16) - (l12 * l15);
  5120. var l18 = (l10 * l16) - (l12 * l14);
  5121. var l19 = (l10 * l15) - (l11 * l14);
  5122. var l20 = (l9 * l16) - (l12 * l13);
  5123. var l21 = (l9 * l15) - (l11 * l13);
  5124. var l22 = (l9 * l14) - (l10 * l13);
  5125. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5126. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5127. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5128. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5129. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5130. var l28 = (l7 * l16) - (l8 * l15);
  5131. var l29 = (l6 * l16) - (l8 * l14);
  5132. var l30 = (l6 * l15) - (l7 * l14);
  5133. var l31 = (l5 * l16) - (l8 * l13);
  5134. var l32 = (l5 * l15) - (l7 * l13);
  5135. var l33 = (l5 * l14) - (l6 * l13);
  5136. var l34 = (l7 * l12) - (l8 * l11);
  5137. var l35 = (l6 * l12) - (l8 * l10);
  5138. var l36 = (l6 * l11) - (l7 * l10);
  5139. var l37 = (l5 * l12) - (l8 * l9);
  5140. var l38 = (l5 * l11) - (l7 * l9);
  5141. var l39 = (l5 * l10) - (l6 * l9);
  5142. other.m[0] = l23 * l27;
  5143. other.m[4] = l24 * l27;
  5144. other.m[8] = l25 * l27;
  5145. other.m[12] = l26 * l27;
  5146. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5147. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5148. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5149. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5150. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5151. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5152. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5153. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5154. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5155. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5156. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5157. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5158. other._markAsUpdated();
  5159. return this;
  5160. };
  5161. /**
  5162. * Inserts the translation vector (using 3 floats) in the current matrix
  5163. * @param x defines the 1st component of the translation
  5164. * @param y defines the 2nd component of the translation
  5165. * @param z defines the 3rd component of the translation
  5166. * @returns the current updated matrix
  5167. */
  5168. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5169. this.m[12] = x;
  5170. this.m[13] = y;
  5171. this.m[14] = z;
  5172. this._markAsUpdated();
  5173. return this;
  5174. };
  5175. /**
  5176. * Inserts the translation vector in the current matrix
  5177. * @param vector3 defines the translation to insert
  5178. * @returns the current updated matrix
  5179. */
  5180. Matrix.prototype.setTranslation = function (vector3) {
  5181. this.m[12] = vector3.x;
  5182. this.m[13] = vector3.y;
  5183. this.m[14] = vector3.z;
  5184. this._markAsUpdated();
  5185. return this;
  5186. };
  5187. /**
  5188. * Gets the translation value of the current matrix
  5189. * @returns a new Vector3 as the extracted translation from the matrix
  5190. */
  5191. Matrix.prototype.getTranslation = function () {
  5192. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5193. };
  5194. /**
  5195. * Fill a Vector3 with the extracted translation from the matrix
  5196. * @param result defines the Vector3 where to store the translation
  5197. * @returns the current matrix
  5198. */
  5199. Matrix.prototype.getTranslationToRef = function (result) {
  5200. result.x = this.m[12];
  5201. result.y = this.m[13];
  5202. result.z = this.m[14];
  5203. return this;
  5204. };
  5205. /**
  5206. * Remove rotation and scaling part from the matrix
  5207. * @returns the updated matrix
  5208. */
  5209. Matrix.prototype.removeRotationAndScaling = function () {
  5210. this.setRowFromFloats(0, 1, 0, 0, 0);
  5211. this.setRowFromFloats(1, 0, 1, 0, 0);
  5212. this.setRowFromFloats(2, 0, 0, 1, 0);
  5213. return this;
  5214. };
  5215. /**
  5216. * Multiply two matrices
  5217. * @param other defines the second operand
  5218. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5219. */
  5220. Matrix.prototype.multiply = function (other) {
  5221. var result = new Matrix();
  5222. this.multiplyToRef(other, result);
  5223. return result;
  5224. };
  5225. /**
  5226. * Copy the current matrix from the given one
  5227. * @param other defines the source matrix
  5228. * @returns the current updated matrix
  5229. */
  5230. Matrix.prototype.copyFrom = function (other) {
  5231. for (var index = 0; index < 16; index++) {
  5232. this.m[index] = other.m[index];
  5233. }
  5234. this._markAsUpdated();
  5235. return this;
  5236. };
  5237. /**
  5238. * Populates the given array from the starting index with the current matrix values
  5239. * @param array defines the target array
  5240. * @param offset defines the offset in the target array where to start storing values
  5241. * @returns the current matrix
  5242. */
  5243. Matrix.prototype.copyToArray = function (array, offset) {
  5244. if (offset === void 0) { offset = 0; }
  5245. for (var index = 0; index < 16; index++) {
  5246. array[offset + index] = this.m[index];
  5247. }
  5248. return this;
  5249. };
  5250. /**
  5251. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5252. * @param other defines the second operand
  5253. * @param result defines the matrix where to store the multiplication
  5254. * @returns the current matrix
  5255. */
  5256. Matrix.prototype.multiplyToRef = function (other, result) {
  5257. this.multiplyToArray(other, result.m, 0);
  5258. result._markAsUpdated();
  5259. return this;
  5260. };
  5261. /**
  5262. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5263. * @param other defines the second operand
  5264. * @param result defines the array where to store the multiplication
  5265. * @param offset defines the offset in the target array where to start storing values
  5266. * @returns the current matrix
  5267. */
  5268. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5269. var tm0 = this.m[0];
  5270. var tm1 = this.m[1];
  5271. var tm2 = this.m[2];
  5272. var tm3 = this.m[3];
  5273. var tm4 = this.m[4];
  5274. var tm5 = this.m[5];
  5275. var tm6 = this.m[6];
  5276. var tm7 = this.m[7];
  5277. var tm8 = this.m[8];
  5278. var tm9 = this.m[9];
  5279. var tm10 = this.m[10];
  5280. var tm11 = this.m[11];
  5281. var tm12 = this.m[12];
  5282. var tm13 = this.m[13];
  5283. var tm14 = this.m[14];
  5284. var tm15 = this.m[15];
  5285. var om0 = other.m[0];
  5286. var om1 = other.m[1];
  5287. var om2 = other.m[2];
  5288. var om3 = other.m[3];
  5289. var om4 = other.m[4];
  5290. var om5 = other.m[5];
  5291. var om6 = other.m[6];
  5292. var om7 = other.m[7];
  5293. var om8 = other.m[8];
  5294. var om9 = other.m[9];
  5295. var om10 = other.m[10];
  5296. var om11 = other.m[11];
  5297. var om12 = other.m[12];
  5298. var om13 = other.m[13];
  5299. var om14 = other.m[14];
  5300. var om15 = other.m[15];
  5301. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5302. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5303. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5304. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5305. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5306. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5307. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5308. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5309. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5310. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5311. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5312. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5313. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5314. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5315. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5316. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5317. return this;
  5318. };
  5319. /**
  5320. * Check equality between this matrix and a second one
  5321. * @param value defines the second matrix to compare
  5322. * @returns true is the current matrix and the given one values are strictly equal
  5323. */
  5324. Matrix.prototype.equals = function (value) {
  5325. return value &&
  5326. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5327. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5328. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5329. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5330. };
  5331. /**
  5332. * Clone the current matrix
  5333. * @returns a new matrix from the current matrix
  5334. */
  5335. Matrix.prototype.clone = function () {
  5336. 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]);
  5337. };
  5338. /**
  5339. * Returns the name of the current matrix class
  5340. * @returns the string "Matrix"
  5341. */
  5342. Matrix.prototype.getClassName = function () {
  5343. return "Matrix";
  5344. };
  5345. /**
  5346. * Gets the hash code of the current matrix
  5347. * @returns the hash code
  5348. */
  5349. Matrix.prototype.getHashCode = function () {
  5350. var hash = this.m[0] || 0;
  5351. for (var i = 1; i < 16; i++) {
  5352. hash = (hash * 397) ^ (this.m[i] || 0);
  5353. }
  5354. return hash;
  5355. };
  5356. /**
  5357. * Decomposes the current Matrix into a translation, rotation and scaling components
  5358. * @param scale defines the scale vector3 given as a reference to update
  5359. * @param rotation defines the rotation quaternion given as a reference to update
  5360. * @param translation defines the translation vector3 given as a reference to update
  5361. * @returns true if operation was successful
  5362. */
  5363. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5364. if (translation) {
  5365. translation.x = this.m[12];
  5366. translation.y = this.m[13];
  5367. translation.z = this.m[14];
  5368. }
  5369. scale = scale || MathTmp.Vector3[0];
  5370. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5371. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5372. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5373. if (this.determinant() <= 0) {
  5374. scale.y *= -1;
  5375. }
  5376. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5377. if (rotation) {
  5378. rotation.x = 0;
  5379. rotation.y = 0;
  5380. rotation.z = 0;
  5381. rotation.w = 1;
  5382. }
  5383. return false;
  5384. }
  5385. if (rotation) {
  5386. 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]);
  5387. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5388. }
  5389. return true;
  5390. };
  5391. /**
  5392. * Gets specific row of the matrix
  5393. * @param index defines the number of the row to get
  5394. * @returns the index-th row of the current matrix as a new Vector4
  5395. */
  5396. Matrix.prototype.getRow = function (index) {
  5397. if (index < 0 || index > 3) {
  5398. return null;
  5399. }
  5400. var i = index * 4;
  5401. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5402. };
  5403. /**
  5404. * Sets the index-th row of the current matrix to the vector4 values
  5405. * @param index defines the number of the row to set
  5406. * @param row defines the target vector4
  5407. * @returns the updated current matrix
  5408. */
  5409. Matrix.prototype.setRow = function (index, row) {
  5410. if (index < 0 || index > 3) {
  5411. return this;
  5412. }
  5413. var i = index * 4;
  5414. this.m[i + 0] = row.x;
  5415. this.m[i + 1] = row.y;
  5416. this.m[i + 2] = row.z;
  5417. this.m[i + 3] = row.w;
  5418. this._markAsUpdated();
  5419. return this;
  5420. };
  5421. /**
  5422. * Compute the transpose of the matrix
  5423. * @returns the new transposed matrix
  5424. */
  5425. Matrix.prototype.transpose = function () {
  5426. return Matrix.Transpose(this);
  5427. };
  5428. /**
  5429. * Compute the transpose of the matrix and store it in a given matrix
  5430. * @param result defines the target matrix
  5431. * @returns the current matrix
  5432. */
  5433. Matrix.prototype.transposeToRef = function (result) {
  5434. Matrix.TransposeToRef(this, result);
  5435. return this;
  5436. };
  5437. /**
  5438. * Sets the index-th row of the current matrix with the given 4 x float values
  5439. * @param index defines the row index
  5440. * @param x defines the x component to set
  5441. * @param y defines the y component to set
  5442. * @param z defines the z component to set
  5443. * @param w defines the w component to set
  5444. * @returns the updated current matrix
  5445. */
  5446. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5447. if (index < 0 || index > 3) {
  5448. return this;
  5449. }
  5450. var i = index * 4;
  5451. this.m[i + 0] = x;
  5452. this.m[i + 1] = y;
  5453. this.m[i + 2] = z;
  5454. this.m[i + 3] = w;
  5455. this._markAsUpdated();
  5456. return this;
  5457. };
  5458. /**
  5459. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5460. * @param scale defines the scale factor
  5461. * @returns a new matrix
  5462. */
  5463. Matrix.prototype.scale = function (scale) {
  5464. var result = new Matrix();
  5465. this.scaleToRef(scale, result);
  5466. return result;
  5467. };
  5468. /**
  5469. * Scale the current matrix values by a factor to a given result matrix
  5470. * @param scale defines the scale factor
  5471. * @param result defines the matrix to store the result
  5472. * @returns the current matrix
  5473. */
  5474. Matrix.prototype.scaleToRef = function (scale, result) {
  5475. for (var index = 0; index < 16; index++) {
  5476. result.m[index] = this.m[index] * scale;
  5477. }
  5478. result._markAsUpdated();
  5479. return this;
  5480. };
  5481. /**
  5482. * Scale the current matrix values by a factor and add the result to a given matrix
  5483. * @param scale defines the scale factor
  5484. * @param result defines the Matrix to store the result
  5485. * @returns the current matrix
  5486. */
  5487. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5488. for (var index = 0; index < 16; index++) {
  5489. result.m[index] += this.m[index] * scale;
  5490. }
  5491. result._markAsUpdated();
  5492. return this;
  5493. };
  5494. /**
  5495. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5496. * @param ref matrix to store the result
  5497. */
  5498. Matrix.prototype.toNormalMatrix = function (ref) {
  5499. this.invertToRef(ref);
  5500. ref.transpose();
  5501. var m = ref.m;
  5502. 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);
  5503. };
  5504. /**
  5505. * Gets only rotation part of the current matrix
  5506. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5507. */
  5508. Matrix.prototype.getRotationMatrix = function () {
  5509. var result = Matrix.Identity();
  5510. this.getRotationMatrixToRef(result);
  5511. return result;
  5512. };
  5513. /**
  5514. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5515. * @param result defines the target matrix to store data to
  5516. * @returns the current matrix
  5517. */
  5518. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5519. var m = this.m;
  5520. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5521. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5522. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5523. if (this.determinant() <= 0) {
  5524. sy *= -1;
  5525. }
  5526. if (sx === 0 || sy === 0 || sz === 0) {
  5527. Matrix.IdentityToRef(result);
  5528. }
  5529. else {
  5530. 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);
  5531. }
  5532. return this;
  5533. };
  5534. // Statics
  5535. /**
  5536. * Creates a matrix from an array
  5537. * @param array defines the source array
  5538. * @param offset defines an offset in the source array
  5539. * @returns a new Matrix set from the starting index of the given array
  5540. */
  5541. Matrix.FromArray = function (array, offset) {
  5542. var result = new Matrix();
  5543. if (!offset) {
  5544. offset = 0;
  5545. }
  5546. Matrix.FromArrayToRef(array, offset, result);
  5547. return result;
  5548. };
  5549. /**
  5550. * Copy the content of an array into a given matrix
  5551. * @param array defines the source array
  5552. * @param offset defines an offset in the source array
  5553. * @param result defines the target matrix
  5554. */
  5555. Matrix.FromArrayToRef = function (array, offset, result) {
  5556. for (var index = 0; index < 16; index++) {
  5557. result.m[index] = array[index + offset];
  5558. }
  5559. result._markAsUpdated();
  5560. };
  5561. /**
  5562. * Stores an array into a matrix after having multiplied each component by a given factor
  5563. * @param array defines the source array
  5564. * @param offset defines the offset in the source array
  5565. * @param scale defines the scaling factor
  5566. * @param result defines the target matrix
  5567. */
  5568. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5569. for (var index = 0; index < 16; index++) {
  5570. result.m[index] = array[index + offset] * scale;
  5571. }
  5572. result._markAsUpdated();
  5573. };
  5574. /**
  5575. * Stores a list of values (16) inside a given matrix
  5576. * @param initialM11 defines 1st value of 1st row
  5577. * @param initialM12 defines 2nd value of 1st row
  5578. * @param initialM13 defines 3rd value of 1st row
  5579. * @param initialM14 defines 4th value of 1st row
  5580. * @param initialM21 defines 1st value of 2nd row
  5581. * @param initialM22 defines 2nd value of 2nd row
  5582. * @param initialM23 defines 3rd value of 2nd row
  5583. * @param initialM24 defines 4th value of 2nd row
  5584. * @param initialM31 defines 1st value of 3rd row
  5585. * @param initialM32 defines 2nd value of 3rd row
  5586. * @param initialM33 defines 3rd value of 3rd row
  5587. * @param initialM34 defines 4th value of 3rd row
  5588. * @param initialM41 defines 1st value of 4th row
  5589. * @param initialM42 defines 2nd value of 4th row
  5590. * @param initialM43 defines 3rd value of 4th row
  5591. * @param initialM44 defines 4th value of 4th row
  5592. * @param result defines the target matrix
  5593. */
  5594. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5595. result.m[0] = initialM11;
  5596. result.m[1] = initialM12;
  5597. result.m[2] = initialM13;
  5598. result.m[3] = initialM14;
  5599. result.m[4] = initialM21;
  5600. result.m[5] = initialM22;
  5601. result.m[6] = initialM23;
  5602. result.m[7] = initialM24;
  5603. result.m[8] = initialM31;
  5604. result.m[9] = initialM32;
  5605. result.m[10] = initialM33;
  5606. result.m[11] = initialM34;
  5607. result.m[12] = initialM41;
  5608. result.m[13] = initialM42;
  5609. result.m[14] = initialM43;
  5610. result.m[15] = initialM44;
  5611. result._markAsUpdated();
  5612. };
  5613. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5614. /**
  5615. * Gets an identity matrix that must not be updated
  5616. */
  5617. get: function () {
  5618. return Matrix._identityReadOnly;
  5619. },
  5620. enumerable: true,
  5621. configurable: true
  5622. });
  5623. /**
  5624. * Creates new matrix from a list of values (16)
  5625. * @param initialM11 defines 1st value of 1st row
  5626. * @param initialM12 defines 2nd value of 1st row
  5627. * @param initialM13 defines 3rd value of 1st row
  5628. * @param initialM14 defines 4th value of 1st row
  5629. * @param initialM21 defines 1st value of 2nd row
  5630. * @param initialM22 defines 2nd value of 2nd row
  5631. * @param initialM23 defines 3rd value of 2nd row
  5632. * @param initialM24 defines 4th value of 2nd row
  5633. * @param initialM31 defines 1st value of 3rd row
  5634. * @param initialM32 defines 2nd value of 3rd row
  5635. * @param initialM33 defines 3rd value of 3rd row
  5636. * @param initialM34 defines 4th value of 3rd row
  5637. * @param initialM41 defines 1st value of 4th row
  5638. * @param initialM42 defines 2nd value of 4th row
  5639. * @param initialM43 defines 3rd value of 4th row
  5640. * @param initialM44 defines 4th value of 4th row
  5641. * @returns the new matrix
  5642. */
  5643. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5644. var result = new Matrix();
  5645. result.m[0] = initialM11;
  5646. result.m[1] = initialM12;
  5647. result.m[2] = initialM13;
  5648. result.m[3] = initialM14;
  5649. result.m[4] = initialM21;
  5650. result.m[5] = initialM22;
  5651. result.m[6] = initialM23;
  5652. result.m[7] = initialM24;
  5653. result.m[8] = initialM31;
  5654. result.m[9] = initialM32;
  5655. result.m[10] = initialM33;
  5656. result.m[11] = initialM34;
  5657. result.m[12] = initialM41;
  5658. result.m[13] = initialM42;
  5659. result.m[14] = initialM43;
  5660. result.m[15] = initialM44;
  5661. return result;
  5662. };
  5663. /**
  5664. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5665. * @param scale defines the scale vector3
  5666. * @param rotation defines the rotation quaternion
  5667. * @param translation defines the translation vector3
  5668. * @returns a new matrix
  5669. */
  5670. Matrix.Compose = function (scale, rotation, translation) {
  5671. var result = Matrix.Identity();
  5672. Matrix.ComposeToRef(scale, rotation, translation, result);
  5673. return result;
  5674. };
  5675. /**
  5676. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5677. * @param scale defines the scale vector3
  5678. * @param rotation defines the rotation quaternion
  5679. * @param translation defines the translation vector3
  5680. * @param result defines the target matrix
  5681. */
  5682. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5683. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5684. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5685. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5686. result.setTranslation(translation);
  5687. };
  5688. /**
  5689. * Creates a new identity matrix
  5690. * @returns a new identity matrix
  5691. */
  5692. Matrix.Identity = function () {
  5693. 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);
  5694. };
  5695. /**
  5696. * Creates a new identity matrix and stores the result in a given matrix
  5697. * @param result defines the target matrix
  5698. */
  5699. Matrix.IdentityToRef = function (result) {
  5700. 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);
  5701. };
  5702. /**
  5703. * Creates a new zero matrix
  5704. * @returns a new zero matrix
  5705. */
  5706. Matrix.Zero = function () {
  5707. 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);
  5708. };
  5709. /**
  5710. * Creates a new rotation matrix for "angle" radians around the X axis
  5711. * @param angle defines the angle (in radians) to use
  5712. * @return the new matrix
  5713. */
  5714. Matrix.RotationX = function (angle) {
  5715. var result = new Matrix();
  5716. Matrix.RotationXToRef(angle, result);
  5717. return result;
  5718. };
  5719. /**
  5720. * Creates a new matrix as the invert of a given matrix
  5721. * @param source defines the source matrix
  5722. * @returns the new matrix
  5723. */
  5724. Matrix.Invert = function (source) {
  5725. var result = new Matrix();
  5726. source.invertToRef(result);
  5727. return result;
  5728. };
  5729. /**
  5730. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5731. * @param angle defines the angle (in radians) to use
  5732. * @param result defines the target matrix
  5733. */
  5734. Matrix.RotationXToRef = function (angle, result) {
  5735. var s = Math.sin(angle);
  5736. var c = Math.cos(angle);
  5737. result.m[0] = 1.0;
  5738. result.m[15] = 1.0;
  5739. result.m[5] = c;
  5740. result.m[10] = c;
  5741. result.m[9] = -s;
  5742. result.m[6] = s;
  5743. result.m[1] = 0.0;
  5744. result.m[2] = 0.0;
  5745. result.m[3] = 0.0;
  5746. result.m[4] = 0.0;
  5747. result.m[7] = 0.0;
  5748. result.m[8] = 0.0;
  5749. result.m[11] = 0.0;
  5750. result.m[12] = 0.0;
  5751. result.m[13] = 0.0;
  5752. result.m[14] = 0.0;
  5753. result._markAsUpdated();
  5754. };
  5755. /**
  5756. * Creates a new rotation matrix for "angle" radians around the Y axis
  5757. * @param angle defines the angle (in radians) to use
  5758. * @return the new matrix
  5759. */
  5760. Matrix.RotationY = function (angle) {
  5761. var result = new Matrix();
  5762. Matrix.RotationYToRef(angle, result);
  5763. return result;
  5764. };
  5765. /**
  5766. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5767. * @param angle defines the angle (in radians) to use
  5768. * @param result defines the target matrix
  5769. */
  5770. Matrix.RotationYToRef = function (angle, result) {
  5771. var s = Math.sin(angle);
  5772. var c = Math.cos(angle);
  5773. result.m[5] = 1.0;
  5774. result.m[15] = 1.0;
  5775. result.m[0] = c;
  5776. result.m[2] = -s;
  5777. result.m[8] = s;
  5778. result.m[10] = c;
  5779. result.m[1] = 0.0;
  5780. result.m[3] = 0.0;
  5781. result.m[4] = 0.0;
  5782. result.m[6] = 0.0;
  5783. result.m[7] = 0.0;
  5784. result.m[9] = 0.0;
  5785. result.m[11] = 0.0;
  5786. result.m[12] = 0.0;
  5787. result.m[13] = 0.0;
  5788. result.m[14] = 0.0;
  5789. result._markAsUpdated();
  5790. };
  5791. /**
  5792. * Creates a new rotation matrix for "angle" radians around the Z axis
  5793. * @param angle defines the angle (in radians) to use
  5794. * @return the new matrix
  5795. */
  5796. Matrix.RotationZ = function (angle) {
  5797. var result = new Matrix();
  5798. Matrix.RotationZToRef(angle, result);
  5799. return result;
  5800. };
  5801. /**
  5802. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5803. * @param angle defines the angle (in radians) to use
  5804. * @param result defines the target matrix
  5805. */
  5806. Matrix.RotationZToRef = function (angle, result) {
  5807. var s = Math.sin(angle);
  5808. var c = Math.cos(angle);
  5809. result.m[10] = 1.0;
  5810. result.m[15] = 1.0;
  5811. result.m[0] = c;
  5812. result.m[1] = s;
  5813. result.m[4] = -s;
  5814. result.m[5] = c;
  5815. result.m[2] = 0.0;
  5816. result.m[3] = 0.0;
  5817. result.m[6] = 0.0;
  5818. result.m[7] = 0.0;
  5819. result.m[8] = 0.0;
  5820. result.m[9] = 0.0;
  5821. result.m[11] = 0.0;
  5822. result.m[12] = 0.0;
  5823. result.m[13] = 0.0;
  5824. result.m[14] = 0.0;
  5825. result._markAsUpdated();
  5826. };
  5827. /**
  5828. * Creates a new rotation matrix for "angle" radians around the given axis
  5829. * @param axis defines the axis to use
  5830. * @param angle defines the angle (in radians) to use
  5831. * @return the new matrix
  5832. */
  5833. Matrix.RotationAxis = function (axis, angle) {
  5834. var result = Matrix.Zero();
  5835. Matrix.RotationAxisToRef(axis, angle, result);
  5836. return result;
  5837. };
  5838. /**
  5839. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5840. * @param axis defines the axis to use
  5841. * @param angle defines the angle (in radians) to use
  5842. * @param result defines the target matrix
  5843. */
  5844. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5845. var s = Math.sin(-angle);
  5846. var c = Math.cos(-angle);
  5847. var c1 = 1 - c;
  5848. axis.normalize();
  5849. result.m[0] = (axis.x * axis.x) * c1 + c;
  5850. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5851. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5852. result.m[3] = 0.0;
  5853. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5854. result.m[5] = (axis.y * axis.y) * c1 + c;
  5855. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5856. result.m[7] = 0.0;
  5857. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5858. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5859. result.m[10] = (axis.z * axis.z) * c1 + c;
  5860. result.m[11] = 0.0;
  5861. result.m[15] = 1.0;
  5862. result._markAsUpdated();
  5863. };
  5864. /**
  5865. * Creates a rotation matrix
  5866. * @param yaw defines the yaw angle in radians (Y axis)
  5867. * @param pitch defines the pitch angle in radians (X axis)
  5868. * @param roll defines the roll angle in radians (X axis)
  5869. * @returns the new rotation matrix
  5870. */
  5871. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5872. var result = new Matrix();
  5873. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5874. return result;
  5875. };
  5876. /**
  5877. * Creates a rotation matrix and stores it in a given matrix
  5878. * @param yaw defines the yaw angle in radians (Y axis)
  5879. * @param pitch defines the pitch angle in radians (X axis)
  5880. * @param roll defines the roll angle in radians (X axis)
  5881. * @param result defines the target matrix
  5882. */
  5883. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5884. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5885. this._tempQuaternion.toRotationMatrix(result);
  5886. };
  5887. /**
  5888. * Creates a scaling matrix
  5889. * @param x defines the scale factor on X axis
  5890. * @param y defines the scale factor on Y axis
  5891. * @param z defines the scale factor on Z axis
  5892. * @returns the new matrix
  5893. */
  5894. Matrix.Scaling = function (x, y, z) {
  5895. var result = Matrix.Zero();
  5896. Matrix.ScalingToRef(x, y, z, result);
  5897. return result;
  5898. };
  5899. /**
  5900. * Creates a scaling matrix and stores it in a given matrix
  5901. * @param x defines the scale factor on X axis
  5902. * @param y defines the scale factor on Y axis
  5903. * @param z defines the scale factor on Z axis
  5904. * @param result defines the target matrix
  5905. */
  5906. Matrix.ScalingToRef = function (x, y, z, result) {
  5907. result.m[0] = x;
  5908. result.m[1] = 0.0;
  5909. result.m[2] = 0.0;
  5910. result.m[3] = 0.0;
  5911. result.m[4] = 0.0;
  5912. result.m[5] = y;
  5913. result.m[6] = 0.0;
  5914. result.m[7] = 0.0;
  5915. result.m[8] = 0.0;
  5916. result.m[9] = 0.0;
  5917. result.m[10] = z;
  5918. result.m[11] = 0.0;
  5919. result.m[12] = 0.0;
  5920. result.m[13] = 0.0;
  5921. result.m[14] = 0.0;
  5922. result.m[15] = 1.0;
  5923. result._markAsUpdated();
  5924. };
  5925. /**
  5926. * Creates a translation matrix
  5927. * @param x defines the translation on X axis
  5928. * @param y defines the translation on Y axis
  5929. * @param z defines the translationon Z axis
  5930. * @returns the new matrix
  5931. */
  5932. Matrix.Translation = function (x, y, z) {
  5933. var result = Matrix.Identity();
  5934. Matrix.TranslationToRef(x, y, z, result);
  5935. return result;
  5936. };
  5937. /**
  5938. * Creates a translation matrix and stores it in a given matrix
  5939. * @param x defines the translation on X axis
  5940. * @param y defines the translation on Y axis
  5941. * @param z defines the translationon Z axis
  5942. * @param result defines the target matrix
  5943. */
  5944. Matrix.TranslationToRef = function (x, y, z, result) {
  5945. 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);
  5946. };
  5947. /**
  5948. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5949. * @param startValue defines the start value
  5950. * @param endValue defines the end value
  5951. * @param gradient defines the gradient factor
  5952. * @returns the new matrix
  5953. */
  5954. Matrix.Lerp = function (startValue, endValue, gradient) {
  5955. var result = Matrix.Zero();
  5956. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5957. return result;
  5958. };
  5959. /**
  5960. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5961. * @param startValue defines the start value
  5962. * @param endValue defines the end value
  5963. * @param gradient defines the gradient factor
  5964. * @param result defines the Matrix object where to store data
  5965. */
  5966. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5967. for (var index = 0; index < 16; index++) {
  5968. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5969. }
  5970. result._markAsUpdated();
  5971. };
  5972. /**
  5973. * Builds a new matrix whose values are computed by:
  5974. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5975. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5976. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5977. * @param startValue defines the first matrix
  5978. * @param endValue defines the second matrix
  5979. * @param gradient defines the gradient between the two matrices
  5980. * @returns the new matrix
  5981. */
  5982. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5983. var result = Matrix.Zero();
  5984. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  5985. return result;
  5986. };
  5987. /**
  5988. * Update a matrix to values which are computed by:
  5989. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5990. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5991. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5992. * @param startValue defines the first matrix
  5993. * @param endValue defines the second matrix
  5994. * @param gradient defines the gradient between the two matrices
  5995. * @param result defines the target matrix
  5996. */
  5997. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  5998. var startScale = MathTmp.Vector3[0];
  5999. var startRotation = MathTmp.Quaternion[0];
  6000. var startTranslation = MathTmp.Vector3[1];
  6001. startValue.decompose(startScale, startRotation, startTranslation);
  6002. var endScale = MathTmp.Vector3[2];
  6003. var endRotation = MathTmp.Quaternion[1];
  6004. var endTranslation = MathTmp.Vector3[3];
  6005. endValue.decompose(endScale, endRotation, endTranslation);
  6006. var resultScale = MathTmp.Vector3[4];
  6007. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6008. var resultRotation = MathTmp.Quaternion[2];
  6009. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6010. var resultTranslation = MathTmp.Vector3[5];
  6011. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6012. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6013. };
  6014. /**
  6015. * 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"
  6016. * This function works in left handed mode
  6017. * @param eye defines the final position of the entity
  6018. * @param target defines where the entity should look at
  6019. * @param up defines the up vector for the entity
  6020. * @returns the new matrix
  6021. */
  6022. Matrix.LookAtLH = function (eye, target, up) {
  6023. var result = Matrix.Zero();
  6024. Matrix.LookAtLHToRef(eye, target, up, result);
  6025. return result;
  6026. };
  6027. /**
  6028. * 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".
  6029. * This function works in left handed mode
  6030. * @param eye defines the final position of the entity
  6031. * @param target defines where the entity should look at
  6032. * @param up defines the up vector for the entity
  6033. * @param result defines the target matrix
  6034. */
  6035. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6036. // Z axis
  6037. target.subtractToRef(eye, this._zAxis);
  6038. this._zAxis.normalize();
  6039. // X axis
  6040. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6041. if (this._xAxis.lengthSquared() === 0) {
  6042. this._xAxis.x = 1.0;
  6043. }
  6044. else {
  6045. this._xAxis.normalize();
  6046. }
  6047. // Y axis
  6048. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6049. this._yAxis.normalize();
  6050. // Eye angles
  6051. var ex = -Vector3.Dot(this._xAxis, eye);
  6052. var ey = -Vector3.Dot(this._yAxis, eye);
  6053. var ez = -Vector3.Dot(this._zAxis, eye);
  6054. 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);
  6055. };
  6056. /**
  6057. * 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"
  6058. * This function works in right handed mode
  6059. * @param eye defines the final position of the entity
  6060. * @param target defines where the entity should look at
  6061. * @param up defines the up vector for the entity
  6062. * @returns the new matrix
  6063. */
  6064. Matrix.LookAtRH = function (eye, target, up) {
  6065. var result = Matrix.Zero();
  6066. Matrix.LookAtRHToRef(eye, target, up, result);
  6067. return result;
  6068. };
  6069. /**
  6070. * 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".
  6071. * This function works in right handed mode
  6072. * @param eye defines the final position of the entity
  6073. * @param target defines where the entity should look at
  6074. * @param up defines the up vector for the entity
  6075. * @param result defines the target matrix
  6076. */
  6077. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6078. // Z axis
  6079. eye.subtractToRef(target, this._zAxis);
  6080. this._zAxis.normalize();
  6081. // X axis
  6082. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6083. if (this._xAxis.lengthSquared() === 0) {
  6084. this._xAxis.x = 1.0;
  6085. }
  6086. else {
  6087. this._xAxis.normalize();
  6088. }
  6089. // Y axis
  6090. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6091. this._yAxis.normalize();
  6092. // Eye angles
  6093. var ex = -Vector3.Dot(this._xAxis, eye);
  6094. var ey = -Vector3.Dot(this._yAxis, eye);
  6095. var ez = -Vector3.Dot(this._zAxis, eye);
  6096. 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);
  6097. };
  6098. /**
  6099. * Create a left-handed orthographic projection matrix
  6100. * @param width defines the viewport width
  6101. * @param height defines the viewport height
  6102. * @param znear defines the near clip plane
  6103. * @param zfar defines the far clip plane
  6104. * @returns a new matrix as a left-handed orthographic projection matrix
  6105. */
  6106. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6107. var matrix = Matrix.Zero();
  6108. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6109. return matrix;
  6110. };
  6111. /**
  6112. * Store a left-handed orthographic projection to a given matrix
  6113. * @param width defines the viewport width
  6114. * @param height defines the viewport height
  6115. * @param znear defines the near clip plane
  6116. * @param zfar defines the far clip plane
  6117. * @param result defines the target matrix
  6118. */
  6119. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6120. var n = znear;
  6121. var f = zfar;
  6122. var a = 2.0 / width;
  6123. var b = 2.0 / height;
  6124. var c = 2.0 / (f - n);
  6125. var d = -(f + n) / (f - n);
  6126. 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);
  6127. };
  6128. /**
  6129. * Create a left-handed orthographic projection matrix
  6130. * @param left defines the viewport left coordinate
  6131. * @param right defines the viewport right coordinate
  6132. * @param bottom defines the viewport bottom coordinate
  6133. * @param top defines the viewport top coordinate
  6134. * @param znear defines the near clip plane
  6135. * @param zfar defines the far clip plane
  6136. * @returns a new matrix as a left-handed orthographic projection matrix
  6137. */
  6138. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6139. var matrix = Matrix.Zero();
  6140. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6141. return matrix;
  6142. };
  6143. /**
  6144. * Stores a left-handed orthographic projection into a given matrix
  6145. * @param left defines the viewport left coordinate
  6146. * @param right defines the viewport right coordinate
  6147. * @param bottom defines the viewport bottom coordinate
  6148. * @param top defines the viewport top coordinate
  6149. * @param znear defines the near clip plane
  6150. * @param zfar defines the far clip plane
  6151. * @param result defines the target matrix
  6152. */
  6153. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6154. var n = znear;
  6155. var f = zfar;
  6156. var a = 2.0 / (right - left);
  6157. var b = 2.0 / (top - bottom);
  6158. var c = 2.0 / (f - n);
  6159. var d = -(f + n) / (f - n);
  6160. var i0 = (left + right) / (left - right);
  6161. var i1 = (top + bottom) / (bottom - top);
  6162. 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);
  6163. };
  6164. /**
  6165. * Creates a right-handed orthographic projection matrix
  6166. * @param left defines the viewport left coordinate
  6167. * @param right defines the viewport right coordinate
  6168. * @param bottom defines the viewport bottom coordinate
  6169. * @param top defines the viewport top coordinate
  6170. * @param znear defines the near clip plane
  6171. * @param zfar defines the far clip plane
  6172. * @returns a new matrix as a right-handed orthographic projection matrix
  6173. */
  6174. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6175. var matrix = Matrix.Zero();
  6176. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6177. return matrix;
  6178. };
  6179. /**
  6180. * Stores a right-handed orthographic projection into a given matrix
  6181. * @param left defines the viewport left coordinate
  6182. * @param right defines the viewport right coordinate
  6183. * @param bottom defines the viewport bottom coordinate
  6184. * @param top defines the viewport top coordinate
  6185. * @param znear defines the near clip plane
  6186. * @param zfar defines the far clip plane
  6187. * @param result defines the target matrix
  6188. */
  6189. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6190. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6191. result.m[10] *= -1.0;
  6192. };
  6193. /**
  6194. * Creates a left-handed perspective projection matrix
  6195. * @param width defines the viewport width
  6196. * @param height defines the viewport height
  6197. * @param znear defines the near clip plane
  6198. * @param zfar defines the far clip plane
  6199. * @returns a new matrix as a left-handed perspective projection matrix
  6200. */
  6201. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6202. var matrix = Matrix.Zero();
  6203. var n = znear;
  6204. var f = zfar;
  6205. var a = 2.0 * n / width;
  6206. var b = 2.0 * n / height;
  6207. var c = (f + n) / (f - n);
  6208. var d = -2.0 * f * n / (f - n);
  6209. 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);
  6210. return matrix;
  6211. };
  6212. /**
  6213. * Creates a left-handed perspective projection matrix
  6214. * @param fov defines the horizontal field of view
  6215. * @param aspect defines the aspect ratio
  6216. * @param znear defines the near clip plane
  6217. * @param zfar defines the far clip plane
  6218. * @returns a new matrix as a left-handed perspective projection matrix
  6219. */
  6220. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6221. var matrix = Matrix.Zero();
  6222. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6223. return matrix;
  6224. };
  6225. /**
  6226. * Stores a left-handed perspective projection into a given matrix
  6227. * @param fov defines the horizontal field of view
  6228. * @param aspect defines the aspect ratio
  6229. * @param znear defines the near clip plane
  6230. * @param zfar defines the far clip plane
  6231. * @param result defines the target matrix
  6232. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6233. */
  6234. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6235. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6236. var n = znear;
  6237. var f = zfar;
  6238. var t = 1.0 / (Math.tan(fov * 0.5));
  6239. var a = isVerticalFovFixed ? (t / aspect) : t;
  6240. var b = isVerticalFovFixed ? t : (t * aspect);
  6241. var c = (f + n) / (f - n);
  6242. var d = -2.0 * f * n / (f - n);
  6243. 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);
  6244. };
  6245. /**
  6246. * Creates a right-handed perspective projection matrix
  6247. * @param fov defines the horizontal field of view
  6248. * @param aspect defines the aspect ratio
  6249. * @param znear defines the near clip plane
  6250. * @param zfar defines the far clip plane
  6251. * @returns a new matrix as a right-handed perspective projection matrix
  6252. */
  6253. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6254. var matrix = Matrix.Zero();
  6255. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6256. return matrix;
  6257. };
  6258. /**
  6259. * Stores a right-handed perspective projection into a given matrix
  6260. * @param fov defines the horizontal field of view
  6261. * @param aspect defines the aspect ratio
  6262. * @param znear defines the near clip plane
  6263. * @param zfar defines the far clip plane
  6264. * @param result defines the target matrix
  6265. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6266. */
  6267. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6268. //alternatively this could be expressed as:
  6269. // m = PerspectiveFovLHToRef
  6270. // m[10] *= -1.0;
  6271. // m[11] *= -1.0;
  6272. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6273. var n = znear;
  6274. var f = zfar;
  6275. var t = 1.0 / (Math.tan(fov * 0.5));
  6276. var a = isVerticalFovFixed ? (t / aspect) : t;
  6277. var b = isVerticalFovFixed ? t : (t * aspect);
  6278. var c = -(f + n) / (f - n);
  6279. var d = -2 * f * n / (f - n);
  6280. 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);
  6281. };
  6282. /**
  6283. * Stores a perspective projection for WebVR info a given matrix
  6284. * @param fov defines the field of view
  6285. * @param znear defines the near clip plane
  6286. * @param zfar defines the far clip plane
  6287. * @param result defines the target matrix
  6288. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6289. */
  6290. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6291. if (rightHanded === void 0) { rightHanded = false; }
  6292. var rightHandedFactor = rightHanded ? -1 : 1;
  6293. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6294. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6295. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6296. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6297. var xScale = 2.0 / (leftTan + rightTan);
  6298. var yScale = 2.0 / (upTan + downTan);
  6299. result.m[0] = xScale;
  6300. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6301. result.m[5] = yScale;
  6302. result.m[6] = result.m[7] = 0.0;
  6303. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6304. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6305. result.m[10] = -zfar / (znear - zfar);
  6306. result.m[11] = 1.0 * rightHandedFactor;
  6307. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6308. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6309. result._markAsUpdated();
  6310. };
  6311. /**
  6312. * Computes a complete transformation matrix
  6313. * @param viewport defines the viewport to use
  6314. * @param world defines the world matrix
  6315. * @param view defines the view matrix
  6316. * @param projection defines the projection matrix
  6317. * @param zmin defines the near clip plane
  6318. * @param zmax defines the far clip plane
  6319. * @returns the transformation matrix
  6320. */
  6321. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6322. var cw = viewport.width;
  6323. var ch = viewport.height;
  6324. var cx = viewport.x;
  6325. var cy = viewport.y;
  6326. 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);
  6327. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6328. };
  6329. /**
  6330. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6331. * @param matrix defines the matrix to use
  6332. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6333. */
  6334. Matrix.GetAsMatrix2x2 = function (matrix) {
  6335. return new Float32Array([
  6336. matrix.m[0], matrix.m[1],
  6337. matrix.m[4], matrix.m[5]
  6338. ]);
  6339. };
  6340. /**
  6341. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6342. * @param matrix defines the matrix to use
  6343. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6344. */
  6345. Matrix.GetAsMatrix3x3 = function (matrix) {
  6346. return new Float32Array([
  6347. matrix.m[0], matrix.m[1], matrix.m[2],
  6348. matrix.m[4], matrix.m[5], matrix.m[6],
  6349. matrix.m[8], matrix.m[9], matrix.m[10]
  6350. ]);
  6351. };
  6352. /**
  6353. * Compute the transpose of a given matrix
  6354. * @param matrix defines the matrix to transpose
  6355. * @returns the new matrix
  6356. */
  6357. Matrix.Transpose = function (matrix) {
  6358. var result = new Matrix();
  6359. Matrix.TransposeToRef(matrix, result);
  6360. return result;
  6361. };
  6362. /**
  6363. * Compute the transpose of a matrix and store it in a target matrix
  6364. * @param matrix defines the matrix to transpose
  6365. * @param result defines the target matrix
  6366. */
  6367. Matrix.TransposeToRef = function (matrix, result) {
  6368. result.m[0] = matrix.m[0];
  6369. result.m[1] = matrix.m[4];
  6370. result.m[2] = matrix.m[8];
  6371. result.m[3] = matrix.m[12];
  6372. result.m[4] = matrix.m[1];
  6373. result.m[5] = matrix.m[5];
  6374. result.m[6] = matrix.m[9];
  6375. result.m[7] = matrix.m[13];
  6376. result.m[8] = matrix.m[2];
  6377. result.m[9] = matrix.m[6];
  6378. result.m[10] = matrix.m[10];
  6379. result.m[11] = matrix.m[14];
  6380. result.m[12] = matrix.m[3];
  6381. result.m[13] = matrix.m[7];
  6382. result.m[14] = matrix.m[11];
  6383. result.m[15] = matrix.m[15];
  6384. };
  6385. /**
  6386. * Computes a reflection matrix from a plane
  6387. * @param plane defines the reflection plane
  6388. * @returns a new matrix
  6389. */
  6390. Matrix.Reflection = function (plane) {
  6391. var matrix = new Matrix();
  6392. Matrix.ReflectionToRef(plane, matrix);
  6393. return matrix;
  6394. };
  6395. /**
  6396. * Computes a reflection matrix from a plane
  6397. * @param plane defines the reflection plane
  6398. * @param result defines the target matrix
  6399. */
  6400. Matrix.ReflectionToRef = function (plane, result) {
  6401. plane.normalize();
  6402. var x = plane.normal.x;
  6403. var y = plane.normal.y;
  6404. var z = plane.normal.z;
  6405. var temp = -2 * x;
  6406. var temp2 = -2 * y;
  6407. var temp3 = -2 * z;
  6408. result.m[0] = (temp * x) + 1;
  6409. result.m[1] = temp2 * x;
  6410. result.m[2] = temp3 * x;
  6411. result.m[3] = 0.0;
  6412. result.m[4] = temp * y;
  6413. result.m[5] = (temp2 * y) + 1;
  6414. result.m[6] = temp3 * y;
  6415. result.m[7] = 0.0;
  6416. result.m[8] = temp * z;
  6417. result.m[9] = temp2 * z;
  6418. result.m[10] = (temp3 * z) + 1;
  6419. result.m[11] = 0.0;
  6420. result.m[12] = temp * plane.d;
  6421. result.m[13] = temp2 * plane.d;
  6422. result.m[14] = temp3 * plane.d;
  6423. result.m[15] = 1.0;
  6424. result._markAsUpdated();
  6425. };
  6426. /**
  6427. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6428. * @param xaxis defines the value of the 1st axis
  6429. * @param yaxis defines the value of the 2nd axis
  6430. * @param zaxis defines the value of the 3rd axis
  6431. * @param result defines the target matrix
  6432. */
  6433. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6434. result.m[0] = xaxis.x;
  6435. result.m[1] = xaxis.y;
  6436. result.m[2] = xaxis.z;
  6437. result.m[3] = 0.0;
  6438. result.m[4] = yaxis.x;
  6439. result.m[5] = yaxis.y;
  6440. result.m[6] = yaxis.z;
  6441. result.m[7] = 0.0;
  6442. result.m[8] = zaxis.x;
  6443. result.m[9] = zaxis.y;
  6444. result.m[10] = zaxis.z;
  6445. result.m[11] = 0.0;
  6446. result.m[12] = 0.0;
  6447. result.m[13] = 0.0;
  6448. result.m[14] = 0.0;
  6449. result.m[15] = 1.0;
  6450. result._markAsUpdated();
  6451. };
  6452. /**
  6453. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6454. * @param quat defines the quaternion to use
  6455. * @param result defines the target matrix
  6456. */
  6457. Matrix.FromQuaternionToRef = function (quat, result) {
  6458. var xx = quat.x * quat.x;
  6459. var yy = quat.y * quat.y;
  6460. var zz = quat.z * quat.z;
  6461. var xy = quat.x * quat.y;
  6462. var zw = quat.z * quat.w;
  6463. var zx = quat.z * quat.x;
  6464. var yw = quat.y * quat.w;
  6465. var yz = quat.y * quat.z;
  6466. var xw = quat.x * quat.w;
  6467. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6468. result.m[1] = 2.0 * (xy + zw);
  6469. result.m[2] = 2.0 * (zx - yw);
  6470. result.m[3] = 0.0;
  6471. result.m[4] = 2.0 * (xy - zw);
  6472. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6473. result.m[6] = 2.0 * (yz + xw);
  6474. result.m[7] = 0.0;
  6475. result.m[8] = 2.0 * (zx + yw);
  6476. result.m[9] = 2.0 * (yz - xw);
  6477. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6478. result.m[11] = 0.0;
  6479. result.m[12] = 0.0;
  6480. result.m[13] = 0.0;
  6481. result.m[14] = 0.0;
  6482. result.m[15] = 1.0;
  6483. result._markAsUpdated();
  6484. };
  6485. Matrix._tempQuaternion = new Quaternion();
  6486. Matrix._xAxis = Vector3.Zero();
  6487. Matrix._yAxis = Vector3.Zero();
  6488. Matrix._zAxis = Vector3.Zero();
  6489. Matrix._updateFlagSeed = 0;
  6490. Matrix._identityReadOnly = Matrix.Identity();
  6491. return Matrix;
  6492. }());
  6493. BABYLON.Matrix = Matrix;
  6494. var Plane = /** @class */ (function () {
  6495. /**
  6496. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6497. */
  6498. function Plane(a, b, c, d) {
  6499. this.normal = new Vector3(a, b, c);
  6500. this.d = d;
  6501. }
  6502. /**
  6503. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6504. */
  6505. Plane.prototype.asArray = function () {
  6506. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6507. };
  6508. // Methods
  6509. /**
  6510. * Returns a new plane copied from the current Plane.
  6511. */
  6512. Plane.prototype.clone = function () {
  6513. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6514. };
  6515. /**
  6516. * Returns the string "Plane".
  6517. */
  6518. Plane.prototype.getClassName = function () {
  6519. return "Plane";
  6520. };
  6521. /**
  6522. * Returns the Plane hash code.
  6523. */
  6524. Plane.prototype.getHashCode = function () {
  6525. var hash = this.normal.getHashCode();
  6526. hash = (hash * 397) ^ (this.d || 0);
  6527. return hash;
  6528. };
  6529. /**
  6530. * Normalize the current Plane in place.
  6531. * Returns the updated Plane.
  6532. */
  6533. Plane.prototype.normalize = function () {
  6534. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6535. var magnitude = 0.0;
  6536. if (norm !== 0) {
  6537. magnitude = 1.0 / norm;
  6538. }
  6539. this.normal.x *= magnitude;
  6540. this.normal.y *= magnitude;
  6541. this.normal.z *= magnitude;
  6542. this.d *= magnitude;
  6543. return this;
  6544. };
  6545. /**
  6546. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6547. */
  6548. Plane.prototype.transform = function (transformation) {
  6549. var transposedMatrix = Matrix.Transpose(transformation);
  6550. var x = this.normal.x;
  6551. var y = this.normal.y;
  6552. var z = this.normal.z;
  6553. var d = this.d;
  6554. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6555. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6556. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6557. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6558. return new Plane(normalX, normalY, normalZ, finalD);
  6559. };
  6560. /**
  6561. * Returns the dot product (float) of the point coordinates and the plane normal.
  6562. */
  6563. Plane.prototype.dotCoordinate = function (point) {
  6564. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6565. };
  6566. /**
  6567. * Updates the current Plane from the plane defined by the three given points.
  6568. * Returns the updated Plane.
  6569. */
  6570. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6571. var x1 = point2.x - point1.x;
  6572. var y1 = point2.y - point1.y;
  6573. var z1 = point2.z - point1.z;
  6574. var x2 = point3.x - point1.x;
  6575. var y2 = point3.y - point1.y;
  6576. var z2 = point3.z - point1.z;
  6577. var yz = (y1 * z2) - (z1 * y2);
  6578. var xz = (z1 * x2) - (x1 * z2);
  6579. var xy = (x1 * y2) - (y1 * x2);
  6580. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6581. var invPyth;
  6582. if (pyth !== 0) {
  6583. invPyth = 1.0 / pyth;
  6584. }
  6585. else {
  6586. invPyth = 0.0;
  6587. }
  6588. this.normal.x = yz * invPyth;
  6589. this.normal.y = xz * invPyth;
  6590. this.normal.z = xy * invPyth;
  6591. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6592. return this;
  6593. };
  6594. /**
  6595. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6596. */
  6597. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6598. var dot = Vector3.Dot(this.normal, direction);
  6599. return (dot <= epsilon);
  6600. };
  6601. /**
  6602. * Returns the signed distance (float) from the given point to the Plane.
  6603. */
  6604. Plane.prototype.signedDistanceTo = function (point) {
  6605. return Vector3.Dot(point, this.normal) + this.d;
  6606. };
  6607. // Statics
  6608. /**
  6609. * Returns a new Plane from the given array.
  6610. */
  6611. Plane.FromArray = function (array) {
  6612. return new Plane(array[0], array[1], array[2], array[3]);
  6613. };
  6614. /**
  6615. * Returns a new Plane defined by the three given points.
  6616. */
  6617. Plane.FromPoints = function (point1, point2, point3) {
  6618. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6619. result.copyFromPoints(point1, point2, point3);
  6620. return result;
  6621. };
  6622. /**
  6623. * Returns a new Plane the normal vector to this plane at the given origin point.
  6624. * Note : the vector "normal" is updated because normalized.
  6625. */
  6626. Plane.FromPositionAndNormal = function (origin, normal) {
  6627. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6628. normal.normalize();
  6629. result.normal = normal;
  6630. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6631. return result;
  6632. };
  6633. /**
  6634. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6635. */
  6636. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6637. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6638. return Vector3.Dot(point, normal) + d;
  6639. };
  6640. return Plane;
  6641. }());
  6642. BABYLON.Plane = Plane;
  6643. var Viewport = /** @class */ (function () {
  6644. /**
  6645. * Creates a Viewport object located at (x, y) and sized (width, height).
  6646. */
  6647. function Viewport(x, y, width, height) {
  6648. this.x = x;
  6649. this.y = y;
  6650. this.width = width;
  6651. this.height = height;
  6652. }
  6653. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6654. if (renderWidthOrEngine.getRenderWidth) {
  6655. var engine = renderWidthOrEngine;
  6656. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6657. }
  6658. var renderWidth = renderWidthOrEngine;
  6659. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6660. };
  6661. /**
  6662. * Returns a new Viewport copied from the current one.
  6663. */
  6664. Viewport.prototype.clone = function () {
  6665. return new Viewport(this.x, this.y, this.width, this.height);
  6666. };
  6667. return Viewport;
  6668. }());
  6669. BABYLON.Viewport = Viewport;
  6670. var Frustum = /** @class */ (function () {
  6671. function Frustum() {
  6672. }
  6673. /**
  6674. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6675. */
  6676. Frustum.GetPlanes = function (transform) {
  6677. var frustumPlanes = [];
  6678. for (var index = 0; index < 6; index++) {
  6679. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6680. }
  6681. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6682. return frustumPlanes;
  6683. };
  6684. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6685. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6686. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6687. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6688. frustumPlane.d = transform.m[15] + transform.m[14];
  6689. frustumPlane.normalize();
  6690. };
  6691. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6692. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6693. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6694. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6695. frustumPlane.d = transform.m[15] - transform.m[14];
  6696. frustumPlane.normalize();
  6697. };
  6698. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6699. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6700. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6701. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6702. frustumPlane.d = transform.m[15] + transform.m[12];
  6703. frustumPlane.normalize();
  6704. };
  6705. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6706. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6707. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6708. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6709. frustumPlane.d = transform.m[15] - transform.m[12];
  6710. frustumPlane.normalize();
  6711. };
  6712. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6713. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6714. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6715. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6716. frustumPlane.d = transform.m[15] - transform.m[13];
  6717. frustumPlane.normalize();
  6718. };
  6719. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6720. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6721. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6722. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6723. frustumPlane.d = transform.m[15] + transform.m[13];
  6724. frustumPlane.normalize();
  6725. };
  6726. /**
  6727. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6728. */
  6729. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6730. // Near
  6731. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6732. // Far
  6733. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6734. // Left
  6735. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6736. // Right
  6737. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6738. // Top
  6739. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6740. // Bottom
  6741. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6742. };
  6743. return Frustum;
  6744. }());
  6745. BABYLON.Frustum = Frustum;
  6746. /** Defines supported spaces */
  6747. var Space;
  6748. (function (Space) {
  6749. /** Local (object) space */
  6750. Space[Space["LOCAL"] = 0] = "LOCAL";
  6751. /** World space */
  6752. Space[Space["WORLD"] = 1] = "WORLD";
  6753. /** Bone space */
  6754. Space[Space["BONE"] = 2] = "BONE";
  6755. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6756. /** Defines the 3 main axes */
  6757. var Axis = /** @class */ (function () {
  6758. function Axis() {
  6759. }
  6760. /** X axis */
  6761. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6762. /** Y axis */
  6763. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6764. /** Z axis */
  6765. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6766. return Axis;
  6767. }());
  6768. BABYLON.Axis = Axis;
  6769. ;
  6770. var BezierCurve = /** @class */ (function () {
  6771. function BezierCurve() {
  6772. }
  6773. /**
  6774. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6775. */
  6776. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6777. // Extract X (which is equal to time here)
  6778. var f0 = 1 - 3 * x2 + 3 * x1;
  6779. var f1 = 3 * x2 - 6 * x1;
  6780. var f2 = 3 * x1;
  6781. var refinedT = t;
  6782. for (var i = 0; i < 5; i++) {
  6783. var refinedT2 = refinedT * refinedT;
  6784. var refinedT3 = refinedT2 * refinedT;
  6785. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6786. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6787. refinedT -= (x - t) * slope;
  6788. refinedT = Math.min(1, Math.max(0, refinedT));
  6789. }
  6790. // Resolve cubic bezier for the given x
  6791. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6792. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6793. Math.pow(refinedT, 3);
  6794. };
  6795. return BezierCurve;
  6796. }());
  6797. BABYLON.BezierCurve = BezierCurve;
  6798. /**
  6799. * Defines potential orientation for back face culling
  6800. */
  6801. var Orientation;
  6802. (function (Orientation) {
  6803. /**
  6804. * Clockwise
  6805. */
  6806. Orientation[Orientation["CW"] = 0] = "CW";
  6807. /** Counter clockwise */
  6808. Orientation[Orientation["CCW"] = 1] = "CCW";
  6809. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6810. /**
  6811. * Defines angle representation
  6812. */
  6813. var Angle = /** @class */ (function () {
  6814. /**
  6815. * Creates an Angle object of "radians" radians (float).
  6816. */
  6817. function Angle(radians) {
  6818. this._radians = radians;
  6819. if (this._radians < 0.0)
  6820. this._radians += (2.0 * Math.PI);
  6821. }
  6822. /**
  6823. * Get value in degrees
  6824. * @returns the Angle value in degrees (float)
  6825. */
  6826. Angle.prototype.degrees = function () {
  6827. return this._radians * 180.0 / Math.PI;
  6828. };
  6829. /**
  6830. * Get value in radians
  6831. * @returns the Angle value in radians (float)
  6832. */
  6833. Angle.prototype.radians = function () {
  6834. return this._radians;
  6835. };
  6836. /**
  6837. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6838. * @param a defines first vector
  6839. * @param b defines second vector
  6840. * @returns a new Angle
  6841. */
  6842. Angle.BetweenTwoPoints = function (a, b) {
  6843. var delta = b.subtract(a);
  6844. var theta = Math.atan2(delta.y, delta.x);
  6845. return new Angle(theta);
  6846. };
  6847. /**
  6848. * Gets a new Angle object from the given float in radians
  6849. * @param radians defines the angle value in radians
  6850. * @returns a new Angle
  6851. */
  6852. Angle.FromRadians = function (radians) {
  6853. return new Angle(radians);
  6854. };
  6855. /**
  6856. * Gets a new Angle object from the given float in degrees
  6857. * @param degrees defines the angle value in degrees
  6858. * @returns a new Angle
  6859. */
  6860. Angle.FromDegrees = function (degrees) {
  6861. return new Angle(degrees * Math.PI / 180.0);
  6862. };
  6863. return Angle;
  6864. }());
  6865. BABYLON.Angle = Angle;
  6866. var Arc2 = /** @class */ (function () {
  6867. /**
  6868. * Creates an Arc object from the three given points : start, middle and end.
  6869. */
  6870. function Arc2(startPoint, midPoint, endPoint) {
  6871. this.startPoint = startPoint;
  6872. this.midPoint = midPoint;
  6873. this.endPoint = endPoint;
  6874. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6875. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6876. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6877. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6878. 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);
  6879. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6880. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6881. var a1 = this.startAngle.degrees();
  6882. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6883. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6884. // angles correction
  6885. if (a2 - a1 > +180.0)
  6886. a2 -= 360.0;
  6887. if (a2 - a1 < -180.0)
  6888. a2 += 360.0;
  6889. if (a3 - a2 > +180.0)
  6890. a3 -= 360.0;
  6891. if (a3 - a2 < -180.0)
  6892. a3 += 360.0;
  6893. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6894. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6895. }
  6896. return Arc2;
  6897. }());
  6898. BABYLON.Arc2 = Arc2;
  6899. var Path2 = /** @class */ (function () {
  6900. /**
  6901. * Creates a Path2 object from the starting 2D coordinates x and y.
  6902. */
  6903. function Path2(x, y) {
  6904. this._points = new Array();
  6905. this._length = 0.0;
  6906. this.closed = false;
  6907. this._points.push(new Vector2(x, y));
  6908. }
  6909. /**
  6910. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6911. * Returns the updated Path2.
  6912. */
  6913. Path2.prototype.addLineTo = function (x, y) {
  6914. if (this.closed) {
  6915. return this;
  6916. }
  6917. var newPoint = new Vector2(x, y);
  6918. var previousPoint = this._points[this._points.length - 1];
  6919. this._points.push(newPoint);
  6920. this._length += newPoint.subtract(previousPoint).length();
  6921. return this;
  6922. };
  6923. /**
  6924. * 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.
  6925. * Returns the updated Path2.
  6926. */
  6927. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6928. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6929. if (this.closed) {
  6930. return this;
  6931. }
  6932. var startPoint = this._points[this._points.length - 1];
  6933. var midPoint = new Vector2(midX, midY);
  6934. var endPoint = new Vector2(endX, endY);
  6935. var arc = new Arc2(startPoint, midPoint, endPoint);
  6936. var increment = arc.angle.radians() / numberOfSegments;
  6937. if (arc.orientation === Orientation.CW)
  6938. increment *= -1;
  6939. var currentAngle = arc.startAngle.radians() + increment;
  6940. for (var i = 0; i < numberOfSegments; i++) {
  6941. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6942. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6943. this.addLineTo(x, y);
  6944. currentAngle += increment;
  6945. }
  6946. return this;
  6947. };
  6948. /**
  6949. * Closes the Path2.
  6950. * Returns the Path2.
  6951. */
  6952. Path2.prototype.close = function () {
  6953. this.closed = true;
  6954. return this;
  6955. };
  6956. /**
  6957. * Returns the Path2 total length (float).
  6958. */
  6959. Path2.prototype.length = function () {
  6960. var result = this._length;
  6961. if (!this.closed) {
  6962. var lastPoint = this._points[this._points.length - 1];
  6963. var firstPoint = this._points[0];
  6964. result += (firstPoint.subtract(lastPoint).length());
  6965. }
  6966. return result;
  6967. };
  6968. /**
  6969. * Returns the Path2 internal array of points.
  6970. */
  6971. Path2.prototype.getPoints = function () {
  6972. return this._points;
  6973. };
  6974. /**
  6975. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6976. */
  6977. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6978. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6979. return Vector2.Zero();
  6980. }
  6981. var lengthPosition = normalizedLengthPosition * this.length();
  6982. var previousOffset = 0;
  6983. for (var i = 0; i < this._points.length; i++) {
  6984. var j = (i + 1) % this._points.length;
  6985. var a = this._points[i];
  6986. var b = this._points[j];
  6987. var bToA = b.subtract(a);
  6988. var nextOffset = (bToA.length() + previousOffset);
  6989. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6990. var dir = bToA.normalize();
  6991. var localOffset = lengthPosition - previousOffset;
  6992. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6993. }
  6994. previousOffset = nextOffset;
  6995. }
  6996. return Vector2.Zero();
  6997. };
  6998. /**
  6999. * Returns a new Path2 starting at the coordinates (x, y).
  7000. */
  7001. Path2.StartingAt = function (x, y) {
  7002. return new Path2(x, y);
  7003. };
  7004. return Path2;
  7005. }());
  7006. BABYLON.Path2 = Path2;
  7007. var Path3D = /** @class */ (function () {
  7008. /**
  7009. * new Path3D(path, normal, raw)
  7010. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7011. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7012. * path : an array of Vector3, the curve axis of the Path3D
  7013. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7014. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7015. */
  7016. function Path3D(path, firstNormal, raw) {
  7017. if (firstNormal === void 0) { firstNormal = null; }
  7018. this.path = path;
  7019. this._curve = new Array();
  7020. this._distances = new Array();
  7021. this._tangents = new Array();
  7022. this._normals = new Array();
  7023. this._binormals = new Array();
  7024. for (var p = 0; p < path.length; p++) {
  7025. this._curve[p] = path[p].clone(); // hard copy
  7026. }
  7027. this._raw = raw || false;
  7028. this._compute(firstNormal);
  7029. }
  7030. /**
  7031. * Returns the Path3D array of successive Vector3 designing its curve.
  7032. */
  7033. Path3D.prototype.getCurve = function () {
  7034. return this._curve;
  7035. };
  7036. /**
  7037. * Returns an array populated with tangent vectors on each Path3D curve point.
  7038. */
  7039. Path3D.prototype.getTangents = function () {
  7040. return this._tangents;
  7041. };
  7042. /**
  7043. * Returns an array populated with normal vectors on each Path3D curve point.
  7044. */
  7045. Path3D.prototype.getNormals = function () {
  7046. return this._normals;
  7047. };
  7048. /**
  7049. * Returns an array populated with binormal vectors on each Path3D curve point.
  7050. */
  7051. Path3D.prototype.getBinormals = function () {
  7052. return this._binormals;
  7053. };
  7054. /**
  7055. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7056. */
  7057. Path3D.prototype.getDistances = function () {
  7058. return this._distances;
  7059. };
  7060. /**
  7061. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7062. * Returns the same object updated.
  7063. */
  7064. Path3D.prototype.update = function (path, firstNormal) {
  7065. if (firstNormal === void 0) { firstNormal = null; }
  7066. for (var p = 0; p < path.length; p++) {
  7067. this._curve[p].x = path[p].x;
  7068. this._curve[p].y = path[p].y;
  7069. this._curve[p].z = path[p].z;
  7070. }
  7071. this._compute(firstNormal);
  7072. return this;
  7073. };
  7074. // private function compute() : computes tangents, normals and binormals
  7075. Path3D.prototype._compute = function (firstNormal) {
  7076. var l = this._curve.length;
  7077. // first and last tangents
  7078. this._tangents[0] = this._getFirstNonNullVector(0);
  7079. if (!this._raw) {
  7080. this._tangents[0].normalize();
  7081. }
  7082. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7083. if (!this._raw) {
  7084. this._tangents[l - 1].normalize();
  7085. }
  7086. // normals and binormals at first point : arbitrary vector with _normalVector()
  7087. var tg0 = this._tangents[0];
  7088. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7089. this._normals[0] = pp0;
  7090. if (!this._raw) {
  7091. this._normals[0].normalize();
  7092. }
  7093. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7094. if (!this._raw) {
  7095. this._binormals[0].normalize();
  7096. }
  7097. this._distances[0] = 0.0;
  7098. // normals and binormals : next points
  7099. var prev; // previous vector (segment)
  7100. var cur; // current vector (segment)
  7101. var curTang; // current tangent
  7102. // previous normal
  7103. var prevBinor; // previous binormal
  7104. for (var i = 1; i < l; i++) {
  7105. // tangents
  7106. prev = this._getLastNonNullVector(i);
  7107. if (i < l - 1) {
  7108. cur = this._getFirstNonNullVector(i);
  7109. this._tangents[i] = prev.add(cur);
  7110. this._tangents[i].normalize();
  7111. }
  7112. this._distances[i] = this._distances[i - 1] + prev.length();
  7113. // normals and binormals
  7114. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7115. curTang = this._tangents[i];
  7116. prevBinor = this._binormals[i - 1];
  7117. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7118. if (!this._raw) {
  7119. this._normals[i].normalize();
  7120. }
  7121. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7122. if (!this._raw) {
  7123. this._binormals[i].normalize();
  7124. }
  7125. }
  7126. };
  7127. // private function getFirstNonNullVector(index)
  7128. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7129. Path3D.prototype._getFirstNonNullVector = function (index) {
  7130. var i = 1;
  7131. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7132. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7133. i++;
  7134. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7135. }
  7136. return nNVector;
  7137. };
  7138. // private function getLastNonNullVector(index)
  7139. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7140. Path3D.prototype._getLastNonNullVector = function (index) {
  7141. var i = 1;
  7142. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7143. while (nLVector.length() === 0 && index > i + 1) {
  7144. i++;
  7145. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7146. }
  7147. return nLVector;
  7148. };
  7149. // private function normalVector(v0, vt, va) :
  7150. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7151. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7152. Path3D.prototype._normalVector = function (v0, vt, va) {
  7153. var normal0;
  7154. var tgl = vt.length();
  7155. if (tgl === 0.0) {
  7156. tgl = 1.0;
  7157. }
  7158. if (va === undefined || va === null) {
  7159. var point;
  7160. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7161. point = new Vector3(0.0, -1.0, 0.0);
  7162. }
  7163. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7164. point = new Vector3(1.0, 0.0, 0.0);
  7165. }
  7166. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7167. point = new Vector3(0.0, 0.0, 1.0);
  7168. }
  7169. else {
  7170. point = Vector3.Zero();
  7171. }
  7172. normal0 = Vector3.Cross(vt, point);
  7173. }
  7174. else {
  7175. normal0 = Vector3.Cross(vt, va);
  7176. Vector3.CrossToRef(normal0, vt, normal0);
  7177. }
  7178. normal0.normalize();
  7179. return normal0;
  7180. };
  7181. return Path3D;
  7182. }());
  7183. BABYLON.Path3D = Path3D;
  7184. var Curve3 = /** @class */ (function () {
  7185. /**
  7186. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7187. * A Curve3 is designed from a series of successive Vector3.
  7188. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7189. */
  7190. function Curve3(points) {
  7191. this._length = 0.0;
  7192. this._points = points;
  7193. this._length = this._computeLength(points);
  7194. }
  7195. /**
  7196. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7197. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7198. * @param v1 (Vector3) the control point
  7199. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7200. * @param nbPoints (integer) the wanted number of points in the curve
  7201. */
  7202. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7203. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7204. var bez = new Array();
  7205. var equation = function (t, val0, val1, val2) {
  7206. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7207. return res;
  7208. };
  7209. for (var i = 0; i <= nbPoints; i++) {
  7210. 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)));
  7211. }
  7212. return new Curve3(bez);
  7213. };
  7214. /**
  7215. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7216. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7217. * @param v1 (Vector3) the first control point
  7218. * @param v2 (Vector3) the second control point
  7219. * @param v3 (Vector3) the end point of the Cubic Bezier
  7220. * @param nbPoints (integer) the wanted number of points in the curve
  7221. */
  7222. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7223. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7224. var bez = new Array();
  7225. var equation = function (t, val0, val1, val2, val3) {
  7226. 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;
  7227. return res;
  7228. };
  7229. for (var i = 0; i <= nbPoints; i++) {
  7230. 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)));
  7231. }
  7232. return new Curve3(bez);
  7233. };
  7234. /**
  7235. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7236. * @param p1 (Vector3) the origin point of the Hermite Spline
  7237. * @param t1 (Vector3) the tangent vector at the origin point
  7238. * @param p2 (Vector3) the end point of the Hermite Spline
  7239. * @param t2 (Vector3) the tangent vector at the end point
  7240. * @param nbPoints (integer) the wanted number of points in the curve
  7241. */
  7242. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7243. var hermite = new Array();
  7244. var step = 1.0 / nbPoints;
  7245. for (var i = 0; i <= nbPoints; i++) {
  7246. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7247. }
  7248. return new Curve3(hermite);
  7249. };
  7250. /**
  7251. * Returns a Curve3 object along a CatmullRom Spline curve :
  7252. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  7253. * @param nbPoints (integer) the wanted number of points between each curve control points.
  7254. */
  7255. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  7256. var totalPoints = new Array();
  7257. totalPoints.push(points[0].clone());
  7258. Array.prototype.push.apply(totalPoints, points);
  7259. totalPoints.push(points[points.length - 1].clone());
  7260. var catmullRom = new Array();
  7261. var step = 1.0 / nbPoints;
  7262. var amount = 0.0;
  7263. for (var i = 0; i < totalPoints.length - 3; i++) {
  7264. amount = 0;
  7265. for (var c = 0; c < nbPoints; c++) {
  7266. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7267. amount += step;
  7268. }
  7269. }
  7270. i--;
  7271. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7272. return new Curve3(catmullRom);
  7273. };
  7274. /**
  7275. * Returns the Curve3 stored array of successive Vector3
  7276. */
  7277. Curve3.prototype.getPoints = function () {
  7278. return this._points;
  7279. };
  7280. /**
  7281. * Returns the computed length (float) of the curve.
  7282. */
  7283. Curve3.prototype.length = function () {
  7284. return this._length;
  7285. };
  7286. /**
  7287. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7288. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7289. * curveA and curveB keep unchanged.
  7290. */
  7291. Curve3.prototype.continue = function (curve) {
  7292. var lastPoint = this._points[this._points.length - 1];
  7293. var continuedPoints = this._points.slice();
  7294. var curvePoints = curve.getPoints();
  7295. for (var i = 1; i < curvePoints.length; i++) {
  7296. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7297. }
  7298. var continuedCurve = new Curve3(continuedPoints);
  7299. return continuedCurve;
  7300. };
  7301. Curve3.prototype._computeLength = function (path) {
  7302. var l = 0;
  7303. for (var i = 1; i < path.length; i++) {
  7304. l += (path[i].subtract(path[i - 1])).length();
  7305. }
  7306. return l;
  7307. };
  7308. return Curve3;
  7309. }());
  7310. BABYLON.Curve3 = Curve3;
  7311. // Vertex formats
  7312. var PositionNormalVertex = /** @class */ (function () {
  7313. function PositionNormalVertex(position, normal) {
  7314. if (position === void 0) { position = Vector3.Zero(); }
  7315. if (normal === void 0) { normal = Vector3.Up(); }
  7316. this.position = position;
  7317. this.normal = normal;
  7318. }
  7319. PositionNormalVertex.prototype.clone = function () {
  7320. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7321. };
  7322. return PositionNormalVertex;
  7323. }());
  7324. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7325. var PositionNormalTextureVertex = /** @class */ (function () {
  7326. function PositionNormalTextureVertex(position, normal, uv) {
  7327. if (position === void 0) { position = Vector3.Zero(); }
  7328. if (normal === void 0) { normal = Vector3.Up(); }
  7329. if (uv === void 0) { uv = Vector2.Zero(); }
  7330. this.position = position;
  7331. this.normal = normal;
  7332. this.uv = uv;
  7333. }
  7334. PositionNormalTextureVertex.prototype.clone = function () {
  7335. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7336. };
  7337. return PositionNormalTextureVertex;
  7338. }());
  7339. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7340. // Temporary pre-allocated objects for engine internal use
  7341. // usage in any internal function :
  7342. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7343. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7344. var Tmp = /** @class */ (function () {
  7345. function Tmp() {
  7346. }
  7347. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7348. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7349. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7350. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7351. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7352. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7353. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7354. Matrix.Zero(), Matrix.Zero(),
  7355. Matrix.Zero(), Matrix.Zero(),
  7356. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7357. return Tmp;
  7358. }());
  7359. BABYLON.Tmp = Tmp;
  7360. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7361. var MathTmp = /** @class */ (function () {
  7362. function MathTmp() {
  7363. }
  7364. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7365. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7366. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7367. return MathTmp;
  7368. }());
  7369. })(BABYLON || (BABYLON = {}));
  7370. //# sourceMappingURL=babylon.math.js.map
  7371. var BABYLON;
  7372. (function (BABYLON) {
  7373. var Scalar = /** @class */ (function () {
  7374. function Scalar() {
  7375. }
  7376. /**
  7377. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7378. */
  7379. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7380. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7381. var num = a - b;
  7382. return -epsilon <= num && num <= epsilon;
  7383. };
  7384. /**
  7385. * Returns a string : the upper case translation of the number i to hexadecimal.
  7386. */
  7387. Scalar.ToHex = function (i) {
  7388. var str = i.toString(16);
  7389. if (i <= 15) {
  7390. return ("0" + str).toUpperCase();
  7391. }
  7392. return str.toUpperCase();
  7393. };
  7394. /**
  7395. * Returns -1 if value is negative and +1 is value is positive.
  7396. * Returns the value itself if it's equal to zero.
  7397. */
  7398. Scalar.Sign = function (value) {
  7399. value = +value; // convert to a number
  7400. if (value === 0 || isNaN(value))
  7401. return value;
  7402. return value > 0 ? 1 : -1;
  7403. };
  7404. /**
  7405. * Returns the value itself if it's between min and max.
  7406. * Returns min if the value is lower than min.
  7407. * Returns max if the value is greater than max.
  7408. */
  7409. Scalar.Clamp = function (value, min, max) {
  7410. if (min === void 0) { min = 0; }
  7411. if (max === void 0) { max = 1; }
  7412. return Math.min(max, Math.max(min, value));
  7413. };
  7414. /**
  7415. * Returns the log2 of value.
  7416. */
  7417. Scalar.Log2 = function (value) {
  7418. return Math.log(value) * Math.LOG2E;
  7419. };
  7420. /**
  7421. * Loops the value, so that it is never larger than length and never smaller than 0.
  7422. *
  7423. * This is similar to the modulo operator but it works with floating point numbers.
  7424. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7425. * With t = 5 and length = 2.5, the result would be 0.0.
  7426. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7427. */
  7428. Scalar.Repeat = function (value, length) {
  7429. return value - Math.floor(value / length) * length;
  7430. };
  7431. /**
  7432. * Normalize the value between 0.0 and 1.0 using min and max values
  7433. */
  7434. Scalar.Normalize = function (value, min, max) {
  7435. return (value - min) / (max - min);
  7436. };
  7437. /**
  7438. * Denormalize the value from 0.0 and 1.0 using min and max values
  7439. */
  7440. Scalar.Denormalize = function (normalized, min, max) {
  7441. return (normalized * (max - min) + min);
  7442. };
  7443. /**
  7444. * Calculates the shortest difference between two given angles given in degrees.
  7445. */
  7446. Scalar.DeltaAngle = function (current, target) {
  7447. var num = Scalar.Repeat(target - current, 360.0);
  7448. if (num > 180.0) {
  7449. num -= 360.0;
  7450. }
  7451. return num;
  7452. };
  7453. /**
  7454. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7455. *
  7456. * The returned value will move back and forth between 0 and length
  7457. */
  7458. Scalar.PingPong = function (tx, length) {
  7459. var t = Scalar.Repeat(tx, length * 2.0);
  7460. return length - Math.abs(t - length);
  7461. };
  7462. /**
  7463. * Interpolates between min and max with smoothing at the limits.
  7464. *
  7465. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7466. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7467. */
  7468. Scalar.SmoothStep = function (from, to, tx) {
  7469. var t = Scalar.Clamp(tx);
  7470. t = -2.0 * t * t * t + 3.0 * t * t;
  7471. return to * t + from * (1.0 - t);
  7472. };
  7473. /**
  7474. * Moves a value current towards target.
  7475. *
  7476. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7477. * Negative values of maxDelta pushes the value away from target.
  7478. */
  7479. Scalar.MoveTowards = function (current, target, maxDelta) {
  7480. var result = 0;
  7481. if (Math.abs(target - current) <= maxDelta) {
  7482. result = target;
  7483. }
  7484. else {
  7485. result = current + Scalar.Sign(target - current) * maxDelta;
  7486. }
  7487. return result;
  7488. };
  7489. /**
  7490. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7491. *
  7492. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7493. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7494. */
  7495. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7496. var num = Scalar.DeltaAngle(current, target);
  7497. var result = 0;
  7498. if (-maxDelta < num && num < maxDelta) {
  7499. result = target;
  7500. }
  7501. else {
  7502. target = current + num;
  7503. result = Scalar.MoveTowards(current, target, maxDelta);
  7504. }
  7505. return result;
  7506. };
  7507. /**
  7508. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7509. */
  7510. Scalar.Lerp = function (start, end, amount) {
  7511. return start + ((end - start) * amount);
  7512. };
  7513. /**
  7514. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7515. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7516. */
  7517. Scalar.LerpAngle = function (start, end, amount) {
  7518. var num = Scalar.Repeat(end - start, 360.0);
  7519. if (num > 180.0) {
  7520. num -= 360.0;
  7521. }
  7522. return start + num * Scalar.Clamp(amount);
  7523. };
  7524. /**
  7525. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7526. */
  7527. Scalar.InverseLerp = function (a, b, value) {
  7528. var result = 0;
  7529. if (a != b) {
  7530. result = Scalar.Clamp((value - a) / (b - a));
  7531. }
  7532. else {
  7533. result = 0.0;
  7534. }
  7535. return result;
  7536. };
  7537. /**
  7538. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7539. */
  7540. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7541. var squared = amount * amount;
  7542. var cubed = amount * squared;
  7543. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7544. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7545. var part3 = (cubed - (2.0 * squared)) + amount;
  7546. var part4 = cubed - squared;
  7547. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7548. };
  7549. /**
  7550. * Returns a random float number between and min and max values
  7551. */
  7552. Scalar.RandomRange = function (min, max) {
  7553. if (min === max)
  7554. return min;
  7555. return ((Math.random() * (max - min)) + min);
  7556. };
  7557. /**
  7558. * This function returns percentage of a number in a given range.
  7559. *
  7560. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7561. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7562. */
  7563. Scalar.RangeToPercent = function (number, min, max) {
  7564. return ((number - min) / (max - min));
  7565. };
  7566. /**
  7567. * This function returns number that corresponds to the percentage in a given range.
  7568. *
  7569. * PercentToRange(0.34,0,100) will return 34.
  7570. */
  7571. Scalar.PercentToRange = function (percent, min, max) {
  7572. return ((max - min) * percent + min);
  7573. };
  7574. /**
  7575. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7576. * @param angle The angle to normalize in radian.
  7577. * @return The converted angle.
  7578. */
  7579. Scalar.NormalizeRadians = function (angle) {
  7580. // More precise but slower version kept for reference.
  7581. // angle = angle % Tools.TwoPi;
  7582. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7583. //if (angle > Math.PI) {
  7584. // angle -= Tools.TwoPi;
  7585. //}
  7586. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7587. return angle;
  7588. };
  7589. /**
  7590. * Two pi constants convenient for computation.
  7591. */
  7592. Scalar.TwoPi = Math.PI * 2;
  7593. return Scalar;
  7594. }());
  7595. BABYLON.Scalar = Scalar;
  7596. })(BABYLON || (BABYLON = {}));
  7597. //# sourceMappingURL=babylon.math.scalar.js.map
  7598. //# sourceMappingURL=babylon.mixins.js.map
  7599. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7600. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7601. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7602. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7603. //# sourceMappingURL=babylon.webgl2.js.map
  7604. var BABYLON;
  7605. (function (BABYLON) {
  7606. var __decoratorInitialStore = {};
  7607. var __mergedStore = {};
  7608. var _copySource = function (creationFunction, source, instanciate) {
  7609. var destination = creationFunction();
  7610. // Tags
  7611. if (BABYLON.Tags) {
  7612. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7613. }
  7614. var classStore = getMergedStore(destination);
  7615. // Properties
  7616. for (var property in classStore) {
  7617. var propertyDescriptor = classStore[property];
  7618. var sourceProperty = source[property];
  7619. var propertyType = propertyDescriptor.type;
  7620. if (sourceProperty !== undefined && sourceProperty !== null) {
  7621. switch (propertyType) {
  7622. case 0: // Value
  7623. case 6: // Mesh reference
  7624. case 11: // Camera reference
  7625. destination[property] = sourceProperty;
  7626. break;
  7627. case 1: // Texture
  7628. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7629. break;
  7630. case 2: // Color3
  7631. case 3: // FresnelParameters
  7632. case 4: // Vector2
  7633. case 5: // Vector3
  7634. case 7: // Color Curves
  7635. case 10: // Quaternion
  7636. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7637. break;
  7638. }
  7639. }
  7640. }
  7641. return destination;
  7642. };
  7643. function getDirectStore(target) {
  7644. var classKey = target.getClassName();
  7645. if (!__decoratorInitialStore[classKey]) {
  7646. __decoratorInitialStore[classKey] = {};
  7647. }
  7648. return __decoratorInitialStore[classKey];
  7649. }
  7650. /**
  7651. * Return the list of properties flagged as serializable
  7652. * @param target: host object
  7653. */
  7654. function getMergedStore(target) {
  7655. var classKey = target.getClassName();
  7656. if (__mergedStore[classKey]) {
  7657. return __mergedStore[classKey];
  7658. }
  7659. __mergedStore[classKey] = {};
  7660. var store = __mergedStore[classKey];
  7661. var currentTarget = target;
  7662. var currentKey = classKey;
  7663. while (currentKey) {
  7664. var initialStore = __decoratorInitialStore[currentKey];
  7665. for (var property in initialStore) {
  7666. store[property] = initialStore[property];
  7667. }
  7668. var parent_1 = void 0;
  7669. var done = false;
  7670. do {
  7671. parent_1 = Object.getPrototypeOf(currentTarget);
  7672. if (!parent_1.getClassName) {
  7673. done = true;
  7674. break;
  7675. }
  7676. if (parent_1.getClassName() !== currentKey) {
  7677. break;
  7678. }
  7679. currentTarget = parent_1;
  7680. } while (parent_1);
  7681. if (done) {
  7682. break;
  7683. }
  7684. currentKey = parent_1.getClassName();
  7685. currentTarget = parent_1;
  7686. }
  7687. return store;
  7688. }
  7689. function generateSerializableMember(type, sourceName) {
  7690. return function (target, propertyKey) {
  7691. var classStore = getDirectStore(target);
  7692. if (!classStore[propertyKey]) {
  7693. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7694. }
  7695. };
  7696. }
  7697. function generateExpandMember(setCallback, targetKey) {
  7698. if (targetKey === void 0) { targetKey = null; }
  7699. return function (target, propertyKey) {
  7700. var key = targetKey || ("_" + propertyKey);
  7701. Object.defineProperty(target, propertyKey, {
  7702. get: function () {
  7703. return this[key];
  7704. },
  7705. set: function (value) {
  7706. if (this[key] === value) {
  7707. return;
  7708. }
  7709. this[key] = value;
  7710. target[setCallback].apply(this);
  7711. },
  7712. enumerable: true,
  7713. configurable: true
  7714. });
  7715. };
  7716. }
  7717. function expandToProperty(callback, targetKey) {
  7718. if (targetKey === void 0) { targetKey = null; }
  7719. return generateExpandMember(callback, targetKey);
  7720. }
  7721. BABYLON.expandToProperty = expandToProperty;
  7722. function serialize(sourceName) {
  7723. return generateSerializableMember(0, sourceName); // value member
  7724. }
  7725. BABYLON.serialize = serialize;
  7726. function serializeAsTexture(sourceName) {
  7727. return generateSerializableMember(1, sourceName); // texture member
  7728. }
  7729. BABYLON.serializeAsTexture = serializeAsTexture;
  7730. function serializeAsColor3(sourceName) {
  7731. return generateSerializableMember(2, sourceName); // color3 member
  7732. }
  7733. BABYLON.serializeAsColor3 = serializeAsColor3;
  7734. function serializeAsFresnelParameters(sourceName) {
  7735. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7736. }
  7737. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7738. function serializeAsVector2(sourceName) {
  7739. return generateSerializableMember(4, sourceName); // vector2 member
  7740. }
  7741. BABYLON.serializeAsVector2 = serializeAsVector2;
  7742. function serializeAsVector3(sourceName) {
  7743. return generateSerializableMember(5, sourceName); // vector3 member
  7744. }
  7745. BABYLON.serializeAsVector3 = serializeAsVector3;
  7746. function serializeAsMeshReference(sourceName) {
  7747. return generateSerializableMember(6, sourceName); // mesh reference member
  7748. }
  7749. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7750. function serializeAsColorCurves(sourceName) {
  7751. return generateSerializableMember(7, sourceName); // color curves
  7752. }
  7753. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7754. function serializeAsColor4(sourceName) {
  7755. return generateSerializableMember(8, sourceName); // color 4
  7756. }
  7757. BABYLON.serializeAsColor4 = serializeAsColor4;
  7758. function serializeAsImageProcessingConfiguration(sourceName) {
  7759. return generateSerializableMember(9, sourceName); // image processing
  7760. }
  7761. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7762. function serializeAsQuaternion(sourceName) {
  7763. return generateSerializableMember(10, sourceName); // quaternion member
  7764. }
  7765. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7766. /**
  7767. * Decorator used to define property that can be serialized as reference to a camera
  7768. * @param sourceName defines the name of the property to decorate
  7769. */
  7770. function serializeAsCameraReference(sourceName) {
  7771. return generateSerializableMember(11, sourceName); // camera reference member
  7772. }
  7773. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7774. var SerializationHelper = /** @class */ (function () {
  7775. function SerializationHelper() {
  7776. }
  7777. SerializationHelper.Serialize = function (entity, serializationObject) {
  7778. if (!serializationObject) {
  7779. serializationObject = {};
  7780. }
  7781. // Tags
  7782. if (BABYLON.Tags) {
  7783. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7784. }
  7785. var serializedProperties = getMergedStore(entity);
  7786. // Properties
  7787. for (var property in serializedProperties) {
  7788. var propertyDescriptor = serializedProperties[property];
  7789. var targetPropertyName = propertyDescriptor.sourceName || property;
  7790. var propertyType = propertyDescriptor.type;
  7791. var sourceProperty = entity[property];
  7792. if (sourceProperty !== undefined && sourceProperty !== null) {
  7793. switch (propertyType) {
  7794. case 0: // Value
  7795. serializationObject[targetPropertyName] = sourceProperty;
  7796. break;
  7797. case 1: // Texture
  7798. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7799. break;
  7800. case 2: // Color3
  7801. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7802. break;
  7803. case 3: // FresnelParameters
  7804. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7805. break;
  7806. case 4: // Vector2
  7807. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7808. break;
  7809. case 5: // Vector3
  7810. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7811. break;
  7812. case 6: // Mesh reference
  7813. serializationObject[targetPropertyName] = sourceProperty.id;
  7814. break;
  7815. case 7: // Color Curves
  7816. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7817. break;
  7818. case 8: // Color 4
  7819. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7820. break;
  7821. case 9: // Image Processing
  7822. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7823. break;
  7824. case 10: // Quaternion
  7825. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7826. break;
  7827. case 11: // Camera reference
  7828. serializationObject[targetPropertyName] = sourceProperty.id;
  7829. break;
  7830. }
  7831. }
  7832. }
  7833. return serializationObject;
  7834. };
  7835. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7836. if (rootUrl === void 0) { rootUrl = null; }
  7837. var destination = creationFunction();
  7838. if (!rootUrl) {
  7839. rootUrl = "";
  7840. }
  7841. // Tags
  7842. if (BABYLON.Tags) {
  7843. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7844. }
  7845. var classStore = getMergedStore(destination);
  7846. // Properties
  7847. for (var property in classStore) {
  7848. var propertyDescriptor = classStore[property];
  7849. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7850. var propertyType = propertyDescriptor.type;
  7851. if (sourceProperty !== undefined && sourceProperty !== null) {
  7852. var dest = destination;
  7853. switch (propertyType) {
  7854. case 0: // Value
  7855. dest[property] = sourceProperty;
  7856. break;
  7857. case 1: // Texture
  7858. if (scene) {
  7859. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7860. }
  7861. break;
  7862. case 2: // Color3
  7863. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7864. break;
  7865. case 3: // FresnelParameters
  7866. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7867. break;
  7868. case 4: // Vector2
  7869. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7870. break;
  7871. case 5: // Vector3
  7872. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7873. break;
  7874. case 6: // Mesh reference
  7875. if (scene) {
  7876. dest[property] = scene.getLastMeshByID(sourceProperty);
  7877. }
  7878. break;
  7879. case 7: // Color Curves
  7880. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7881. break;
  7882. case 8: // Color 4
  7883. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7884. break;
  7885. case 9: // Image Processing
  7886. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7887. break;
  7888. case 10: // Quaternion
  7889. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7890. break;
  7891. case 11: // Camera reference
  7892. if (scene) {
  7893. dest[property] = scene.getCameraByID(sourceProperty);
  7894. }
  7895. break;
  7896. }
  7897. }
  7898. }
  7899. return destination;
  7900. };
  7901. SerializationHelper.Clone = function (creationFunction, source) {
  7902. return _copySource(creationFunction, source, false);
  7903. };
  7904. SerializationHelper.Instanciate = function (creationFunction, source) {
  7905. return _copySource(creationFunction, source, true);
  7906. };
  7907. return SerializationHelper;
  7908. }());
  7909. BABYLON.SerializationHelper = SerializationHelper;
  7910. })(BABYLON || (BABYLON = {}));
  7911. //# sourceMappingURL=babylon.decorators.js.map
  7912. var BABYLON;
  7913. (function (BABYLON) {
  7914. /**
  7915. * Wrapper class for promise with external resolve and reject.
  7916. */
  7917. var Deferred = /** @class */ (function () {
  7918. /**
  7919. * Constructor for this deferred object.
  7920. */
  7921. function Deferred() {
  7922. var _this = this;
  7923. this.promise = new Promise(function (resolve, reject) {
  7924. _this._resolve = resolve;
  7925. _this._reject = reject;
  7926. });
  7927. }
  7928. Object.defineProperty(Deferred.prototype, "resolve", {
  7929. /**
  7930. * The resolve method of the promise associated with this deferred object.
  7931. */
  7932. get: function () {
  7933. return this._resolve;
  7934. },
  7935. enumerable: true,
  7936. configurable: true
  7937. });
  7938. Object.defineProperty(Deferred.prototype, "reject", {
  7939. /**
  7940. * The reject method of the promise associated with this deferred object.
  7941. */
  7942. get: function () {
  7943. return this._reject;
  7944. },
  7945. enumerable: true,
  7946. configurable: true
  7947. });
  7948. return Deferred;
  7949. }());
  7950. BABYLON.Deferred = Deferred;
  7951. })(BABYLON || (BABYLON = {}));
  7952. //# sourceMappingURL=babylon.deferred.js.map
  7953. var BABYLON;
  7954. (function (BABYLON) {
  7955. /**
  7956. * A class serves as a medium between the observable and its observers
  7957. */
  7958. var EventState = /** @class */ (function () {
  7959. /**
  7960. * Create a new EventState
  7961. * @param mask defines the mask associated with this state
  7962. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7963. * @param target defines the original target of the state
  7964. * @param currentTarget defines the current target of the state
  7965. */
  7966. function EventState(mask, skipNextObservers, target, currentTarget) {
  7967. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7968. this.initalize(mask, skipNextObservers, target, currentTarget);
  7969. }
  7970. /**
  7971. * Initialize the current event state
  7972. * @param mask defines the mask associated with this state
  7973. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7974. * @param target defines the original target of the state
  7975. * @param currentTarget defines the current target of the state
  7976. * @returns the current event state
  7977. */
  7978. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7979. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7980. this.mask = mask;
  7981. this.skipNextObservers = skipNextObservers;
  7982. this.target = target;
  7983. this.currentTarget = currentTarget;
  7984. return this;
  7985. };
  7986. return EventState;
  7987. }());
  7988. BABYLON.EventState = EventState;
  7989. /**
  7990. * Represent an Observer registered to a given Observable object.
  7991. */
  7992. var Observer = /** @class */ (function () {
  7993. /**
  7994. * Creates a new observer
  7995. * @param callback defines the callback to call when the observer is notified
  7996. * @param mask defines the mask of the observer (used to filter notifications)
  7997. * @param scope defines the current scope used to restore the JS context
  7998. */
  7999. function Observer(
  8000. /**
  8001. * Defines the callback to call when the observer is notified
  8002. */
  8003. callback,
  8004. /**
  8005. * Defines the mask of the observer (used to filter notifications)
  8006. */
  8007. mask,
  8008. /**
  8009. * Defines the current scope used to restore the JS context
  8010. */
  8011. scope) {
  8012. if (scope === void 0) { scope = null; }
  8013. this.callback = callback;
  8014. this.mask = mask;
  8015. this.scope = scope;
  8016. /** @hidden */
  8017. this._willBeUnregistered = false;
  8018. /**
  8019. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8020. */
  8021. this.unregisterOnNextCall = false;
  8022. }
  8023. return Observer;
  8024. }());
  8025. BABYLON.Observer = Observer;
  8026. /**
  8027. * Represent a list of observers registered to multiple Observables object.
  8028. */
  8029. var MultiObserver = /** @class */ (function () {
  8030. function MultiObserver() {
  8031. }
  8032. /**
  8033. * Release associated resources
  8034. */
  8035. MultiObserver.prototype.dispose = function () {
  8036. if (this._observers && this._observables) {
  8037. for (var index = 0; index < this._observers.length; index++) {
  8038. this._observables[index].remove(this._observers[index]);
  8039. }
  8040. }
  8041. this._observers = null;
  8042. this._observables = null;
  8043. };
  8044. /**
  8045. * Raise a callback when one of the observable will notify
  8046. * @param observables defines a list of observables to watch
  8047. * @param callback defines the callback to call on notification
  8048. * @param mask defines the mask used to filter notifications
  8049. * @param scope defines the current scope used to restore the JS context
  8050. * @returns the new MultiObserver
  8051. */
  8052. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8053. if (mask === void 0) { mask = -1; }
  8054. if (scope === void 0) { scope = null; }
  8055. var result = new MultiObserver();
  8056. result._observers = new Array();
  8057. result._observables = observables;
  8058. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8059. var observable = observables_1[_i];
  8060. var observer = observable.add(callback, mask, false, scope);
  8061. if (observer) {
  8062. result._observers.push(observer);
  8063. }
  8064. }
  8065. return result;
  8066. };
  8067. return MultiObserver;
  8068. }());
  8069. BABYLON.MultiObserver = MultiObserver;
  8070. /**
  8071. * The Observable class is a simple implementation of the Observable pattern.
  8072. *
  8073. * 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.
  8074. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8075. * 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).
  8076. * 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.
  8077. */
  8078. var Observable = /** @class */ (function () {
  8079. /**
  8080. * Creates a new observable
  8081. * @param onObserverAdded defines a callback to call when a new observer is added
  8082. */
  8083. function Observable(onObserverAdded) {
  8084. this._observers = new Array();
  8085. this._eventState = new EventState(0);
  8086. if (onObserverAdded) {
  8087. this._onObserverAdded = onObserverAdded;
  8088. }
  8089. }
  8090. /**
  8091. * Create a new Observer with the specified callback
  8092. * @param callback the callback that will be executed for that Observer
  8093. * @param mask the mask used to filter observers
  8094. * @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.
  8095. * @param scope optional scope for the callback to be called from
  8096. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8097. * @returns the new observer created for the callback
  8098. */
  8099. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8100. if (mask === void 0) { mask = -1; }
  8101. if (insertFirst === void 0) { insertFirst = false; }
  8102. if (scope === void 0) { scope = null; }
  8103. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8104. if (!callback) {
  8105. return null;
  8106. }
  8107. var observer = new Observer(callback, mask, scope);
  8108. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8109. if (insertFirst) {
  8110. this._observers.unshift(observer);
  8111. }
  8112. else {
  8113. this._observers.push(observer);
  8114. }
  8115. if (this._onObserverAdded) {
  8116. this._onObserverAdded(observer);
  8117. }
  8118. return observer;
  8119. };
  8120. /**
  8121. * Remove an Observer from the Observable object
  8122. * @param observer the instance of the Observer to remove
  8123. * @returns false if it doesn't belong to this Observable
  8124. */
  8125. Observable.prototype.remove = function (observer) {
  8126. if (!observer) {
  8127. return false;
  8128. }
  8129. var index = this._observers.indexOf(observer);
  8130. if (index !== -1) {
  8131. this._observers.splice(index, 1);
  8132. return true;
  8133. }
  8134. return false;
  8135. };
  8136. /**
  8137. * Remove a callback from the Observable object
  8138. * @param callback the callback to remove
  8139. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8140. * @returns false if it doesn't belong to this Observable
  8141. */
  8142. Observable.prototype.removeCallback = function (callback, scope) {
  8143. for (var index = 0; index < this._observers.length; index++) {
  8144. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8145. this._observers.splice(index, 1);
  8146. return true;
  8147. }
  8148. }
  8149. return false;
  8150. };
  8151. Observable.prototype._deferUnregister = function (observer) {
  8152. var _this = this;
  8153. observer.unregisterOnNextCall = false;
  8154. observer._willBeUnregistered = true;
  8155. BABYLON.Tools.SetImmediate(function () {
  8156. _this.remove(observer);
  8157. });
  8158. };
  8159. /**
  8160. * Notify all Observers by calling their respective callback with the given data
  8161. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8162. * @param eventData defines the data to send to all observers
  8163. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8164. * @param target defines the original target of the state
  8165. * @param currentTarget defines the current target of the state
  8166. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8167. */
  8168. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8169. if (mask === void 0) { mask = -1; }
  8170. if (!this._observers.length) {
  8171. return true;
  8172. }
  8173. var state = this._eventState;
  8174. state.mask = mask;
  8175. state.target = target;
  8176. state.currentTarget = currentTarget;
  8177. state.skipNextObservers = false;
  8178. state.lastReturnValue = eventData;
  8179. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8180. var obs = _a[_i];
  8181. if (obs._willBeUnregistered) {
  8182. continue;
  8183. }
  8184. if (obs.mask & mask) {
  8185. if (obs.scope) {
  8186. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8187. }
  8188. else {
  8189. state.lastReturnValue = obs.callback(eventData, state);
  8190. }
  8191. if (obs.unregisterOnNextCall) {
  8192. this._deferUnregister(obs);
  8193. }
  8194. }
  8195. if (state.skipNextObservers) {
  8196. return false;
  8197. }
  8198. }
  8199. return true;
  8200. };
  8201. /**
  8202. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8203. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8204. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8205. * and it is crucial that all callbacks will be executed.
  8206. * The order of the callbacks is kept, callbacks are not executed parallel.
  8207. *
  8208. * @param eventData The data to be sent to each callback
  8209. * @param mask is used to filter observers defaults to -1
  8210. * @param target defines the callback target (see EventState)
  8211. * @param currentTarget defines he current object in the bubbling phase
  8212. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8213. */
  8214. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8215. var _this = this;
  8216. if (mask === void 0) { mask = -1; }
  8217. // create an empty promise
  8218. var p = Promise.resolve(eventData);
  8219. // no observers? return this promise.
  8220. if (!this._observers.length) {
  8221. return p;
  8222. }
  8223. var state = this._eventState;
  8224. state.mask = mask;
  8225. state.target = target;
  8226. state.currentTarget = currentTarget;
  8227. state.skipNextObservers = false;
  8228. // execute one callback after another (not using Promise.all, the order is important)
  8229. this._observers.forEach(function (obs) {
  8230. if (state.skipNextObservers) {
  8231. return;
  8232. }
  8233. if (obs._willBeUnregistered) {
  8234. return;
  8235. }
  8236. if (obs.mask & mask) {
  8237. if (obs.scope) {
  8238. p = p.then(function (lastReturnedValue) {
  8239. state.lastReturnValue = lastReturnedValue;
  8240. return obs.callback.apply(obs.scope, [eventData, state]);
  8241. });
  8242. }
  8243. else {
  8244. p = p.then(function (lastReturnedValue) {
  8245. state.lastReturnValue = lastReturnedValue;
  8246. return obs.callback(eventData, state);
  8247. });
  8248. }
  8249. if (obs.unregisterOnNextCall) {
  8250. _this._deferUnregister(obs);
  8251. }
  8252. }
  8253. });
  8254. // return the eventData
  8255. return p.then(function () { return eventData; });
  8256. };
  8257. /**
  8258. * Notify a specific observer
  8259. * @param observer defines the observer to notify
  8260. * @param eventData defines the data to be sent to each callback
  8261. * @param mask is used to filter observers defaults to -1
  8262. */
  8263. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8264. if (mask === void 0) { mask = -1; }
  8265. var state = this._eventState;
  8266. state.mask = mask;
  8267. state.skipNextObservers = false;
  8268. observer.callback(eventData, state);
  8269. };
  8270. /**
  8271. * Gets a boolean indicating if the observable has at least one observer
  8272. * @returns true is the Observable has at least one Observer registered
  8273. */
  8274. Observable.prototype.hasObservers = function () {
  8275. return this._observers.length > 0;
  8276. };
  8277. /**
  8278. * Clear the list of observers
  8279. */
  8280. Observable.prototype.clear = function () {
  8281. this._observers = new Array();
  8282. this._onObserverAdded = null;
  8283. };
  8284. /**
  8285. * Clone the current observable
  8286. * @returns a new observable
  8287. */
  8288. Observable.prototype.clone = function () {
  8289. var result = new Observable();
  8290. result._observers = this._observers.slice(0);
  8291. return result;
  8292. };
  8293. /**
  8294. * Does this observable handles observer registered with a given mask
  8295. * @param mask defines the mask to be tested
  8296. * @return whether or not one observer registered with the given mask is handeled
  8297. **/
  8298. Observable.prototype.hasSpecificMask = function (mask) {
  8299. if (mask === void 0) { mask = -1; }
  8300. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8301. var obs = _a[_i];
  8302. if (obs.mask & mask || obs.mask === mask) {
  8303. return true;
  8304. }
  8305. }
  8306. return false;
  8307. };
  8308. return Observable;
  8309. }());
  8310. BABYLON.Observable = Observable;
  8311. })(BABYLON || (BABYLON = {}));
  8312. //# sourceMappingURL=babylon.observable.js.map
  8313. var BABYLON;
  8314. (function (BABYLON) {
  8315. var SmartArray = /** @class */ (function () {
  8316. function SmartArray(capacity) {
  8317. this.length = 0;
  8318. this.data = new Array(capacity);
  8319. this._id = SmartArray._GlobalId++;
  8320. }
  8321. SmartArray.prototype.push = function (value) {
  8322. this.data[this.length++] = value;
  8323. if (this.length > this.data.length) {
  8324. this.data.length *= 2;
  8325. }
  8326. };
  8327. SmartArray.prototype.forEach = function (func) {
  8328. for (var index = 0; index < this.length; index++) {
  8329. func(this.data[index]);
  8330. }
  8331. };
  8332. SmartArray.prototype.sort = function (compareFn) {
  8333. this.data.sort(compareFn);
  8334. };
  8335. SmartArray.prototype.reset = function () {
  8336. this.length = 0;
  8337. };
  8338. SmartArray.prototype.dispose = function () {
  8339. this.reset();
  8340. if (this.data) {
  8341. this.data.length = 0;
  8342. this.data = [];
  8343. }
  8344. };
  8345. SmartArray.prototype.concat = function (array) {
  8346. if (array.length === 0) {
  8347. return;
  8348. }
  8349. if (this.length + array.length > this.data.length) {
  8350. this.data.length = (this.length + array.length) * 2;
  8351. }
  8352. for (var index = 0; index < array.length; index++) {
  8353. this.data[this.length++] = (array.data || array)[index];
  8354. }
  8355. };
  8356. SmartArray.prototype.indexOf = function (value) {
  8357. var position = this.data.indexOf(value);
  8358. if (position >= this.length) {
  8359. return -1;
  8360. }
  8361. return position;
  8362. };
  8363. SmartArray.prototype.contains = function (value) {
  8364. return this.data.indexOf(value) !== -1;
  8365. };
  8366. // Statics
  8367. SmartArray._GlobalId = 0;
  8368. return SmartArray;
  8369. }());
  8370. BABYLON.SmartArray = SmartArray;
  8371. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8372. __extends(SmartArrayNoDuplicate, _super);
  8373. function SmartArrayNoDuplicate() {
  8374. var _this = _super !== null && _super.apply(this, arguments) || this;
  8375. _this._duplicateId = 0;
  8376. return _this;
  8377. }
  8378. SmartArrayNoDuplicate.prototype.push = function (value) {
  8379. _super.prototype.push.call(this, value);
  8380. if (!value.__smartArrayFlags) {
  8381. value.__smartArrayFlags = {};
  8382. }
  8383. value.__smartArrayFlags[this._id] = this._duplicateId;
  8384. };
  8385. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8386. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8387. return false;
  8388. }
  8389. this.push(value);
  8390. return true;
  8391. };
  8392. SmartArrayNoDuplicate.prototype.reset = function () {
  8393. _super.prototype.reset.call(this);
  8394. this._duplicateId++;
  8395. };
  8396. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8397. if (array.length === 0) {
  8398. return;
  8399. }
  8400. if (this.length + array.length > this.data.length) {
  8401. this.data.length = (this.length + array.length) * 2;
  8402. }
  8403. for (var index = 0; index < array.length; index++) {
  8404. var item = (array.data || array)[index];
  8405. this.pushNoDuplicate(item);
  8406. }
  8407. };
  8408. return SmartArrayNoDuplicate;
  8409. }(SmartArray));
  8410. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8411. })(BABYLON || (BABYLON = {}));
  8412. //# sourceMappingURL=babylon.smartArray.js.map
  8413. var BABYLON;
  8414. (function (BABYLON) {
  8415. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8416. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8417. var LoadFileError = /** @class */ (function (_super) {
  8418. __extends(LoadFileError, _super);
  8419. function LoadFileError(message, request) {
  8420. var _this = _super.call(this, message) || this;
  8421. _this.request = request;
  8422. _this.name = "LoadFileError";
  8423. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8424. return _this;
  8425. }
  8426. // Polyfill for Object.setPrototypeOf if necessary.
  8427. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8428. return LoadFileError;
  8429. }(Error));
  8430. BABYLON.LoadFileError = LoadFileError;
  8431. var RetryStrategy = /** @class */ (function () {
  8432. function RetryStrategy() {
  8433. }
  8434. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8435. if (maxRetries === void 0) { maxRetries = 3; }
  8436. if (baseInterval === void 0) { baseInterval = 500; }
  8437. return function (url, request, retryIndex) {
  8438. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8439. return -1;
  8440. }
  8441. return Math.pow(2, retryIndex) * baseInterval;
  8442. };
  8443. };
  8444. return RetryStrategy;
  8445. }());
  8446. BABYLON.RetryStrategy = RetryStrategy;
  8447. // Screenshots
  8448. var screenshotCanvas;
  8449. var cloneValue = function (source, destinationObject) {
  8450. if (!source)
  8451. return null;
  8452. if (source instanceof BABYLON.Mesh) {
  8453. return null;
  8454. }
  8455. if (source instanceof BABYLON.SubMesh) {
  8456. return source.clone(destinationObject);
  8457. }
  8458. else if (source.clone) {
  8459. return source.clone();
  8460. }
  8461. return null;
  8462. };
  8463. var Tools = /** @class */ (function () {
  8464. function Tools() {
  8465. }
  8466. /**
  8467. * Interpolates between a and b via alpha
  8468. * @param a The lower value (returned when alpha = 0)
  8469. * @param b The upper value (returned when alpha = 1)
  8470. * @param alpha The interpolation-factor
  8471. * @return The mixed value
  8472. */
  8473. Tools.Mix = function (a, b, alpha) {
  8474. return a * (1 - alpha) + b * alpha;
  8475. };
  8476. Tools.Instantiate = function (className) {
  8477. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8478. return Tools.RegisteredExternalClasses[className];
  8479. }
  8480. var arr = className.split(".");
  8481. var fn = (window || this);
  8482. for (var i = 0, len = arr.length; i < len; i++) {
  8483. fn = fn[arr[i]];
  8484. }
  8485. if (typeof fn !== "function") {
  8486. return null;
  8487. }
  8488. return fn;
  8489. };
  8490. /**
  8491. * Provides a slice function that will work even on IE
  8492. * @param data defines the array to slice
  8493. * @param start defines the start of the data (optional)
  8494. * @param end defines the end of the data (optional)
  8495. * @returns the new sliced array
  8496. */
  8497. Tools.Slice = function (data, start, end) {
  8498. if (data.slice) {
  8499. return data.slice(start, end);
  8500. }
  8501. return Array.prototype.slice.call(data, start, end);
  8502. };
  8503. Tools.SetImmediate = function (action) {
  8504. if (window.setImmediate) {
  8505. window.setImmediate(action);
  8506. }
  8507. else {
  8508. setTimeout(action, 1);
  8509. }
  8510. };
  8511. Tools.IsExponentOfTwo = function (value) {
  8512. var count = 1;
  8513. do {
  8514. count *= 2;
  8515. } while (count < value);
  8516. return count === value;
  8517. };
  8518. /**
  8519. * Returns the nearest 32-bit single precision float representation of a Number
  8520. * @param value A Number. If the parameter is of a different type, it will get converted
  8521. * to a number or to NaN if it cannot be converted
  8522. * @returns number
  8523. */
  8524. Tools.FloatRound = function (value) {
  8525. if (Math.fround) {
  8526. return Math.fround(value);
  8527. }
  8528. return (Tools._tmpFloatArray[0] = value);
  8529. };
  8530. /**
  8531. * Find the next highest power of two.
  8532. * @param x Number to start search from.
  8533. * @return Next highest power of two.
  8534. */
  8535. Tools.CeilingPOT = function (x) {
  8536. x--;
  8537. x |= x >> 1;
  8538. x |= x >> 2;
  8539. x |= x >> 4;
  8540. x |= x >> 8;
  8541. x |= x >> 16;
  8542. x++;
  8543. return x;
  8544. };
  8545. /**
  8546. * Find the next lowest power of two.
  8547. * @param x Number to start search from.
  8548. * @return Next lowest power of two.
  8549. */
  8550. Tools.FloorPOT = function (x) {
  8551. x = x | (x >> 1);
  8552. x = x | (x >> 2);
  8553. x = x | (x >> 4);
  8554. x = x | (x >> 8);
  8555. x = x | (x >> 16);
  8556. return x - (x >> 1);
  8557. };
  8558. /**
  8559. * Find the nearest power of two.
  8560. * @param x Number to start search from.
  8561. * @return Next nearest power of two.
  8562. */
  8563. Tools.NearestPOT = function (x) {
  8564. var c = Tools.CeilingPOT(x);
  8565. var f = Tools.FloorPOT(x);
  8566. return (c - x) > (x - f) ? f : c;
  8567. };
  8568. Tools.GetExponentOfTwo = function (value, max, mode) {
  8569. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8570. var pot;
  8571. switch (mode) {
  8572. case BABYLON.Engine.SCALEMODE_FLOOR:
  8573. pot = Tools.FloorPOT(value);
  8574. break;
  8575. case BABYLON.Engine.SCALEMODE_NEAREST:
  8576. pot = Tools.NearestPOT(value);
  8577. break;
  8578. case BABYLON.Engine.SCALEMODE_CEILING:
  8579. default:
  8580. pot = Tools.CeilingPOT(value);
  8581. break;
  8582. }
  8583. return Math.min(pot, max);
  8584. };
  8585. Tools.GetFilename = function (path) {
  8586. var index = path.lastIndexOf("/");
  8587. if (index < 0)
  8588. return path;
  8589. return path.substring(index + 1);
  8590. };
  8591. /**
  8592. * Extracts the "folder" part of a path (everything before the filename).
  8593. * @param uri The URI to extract the info from
  8594. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8595. * @returns The "folder" part of the path
  8596. */
  8597. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8598. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8599. var index = uri.lastIndexOf("/");
  8600. if (index < 0) {
  8601. if (returnUnchangedIfNoSlash) {
  8602. return uri;
  8603. }
  8604. return "";
  8605. }
  8606. return uri.substring(0, index + 1);
  8607. };
  8608. Tools.GetDOMTextContent = function (element) {
  8609. var result = "";
  8610. var child = element.firstChild;
  8611. while (child) {
  8612. if (child.nodeType === 3) {
  8613. result += child.textContent;
  8614. }
  8615. child = child.nextSibling;
  8616. }
  8617. return result;
  8618. };
  8619. Tools.ToDegrees = function (angle) {
  8620. return angle * 180 / Math.PI;
  8621. };
  8622. Tools.ToRadians = function (angle) {
  8623. return angle * Math.PI / 180;
  8624. };
  8625. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8626. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8627. var output = "";
  8628. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8629. var i = 0;
  8630. var bytes = new Uint8Array(buffer);
  8631. while (i < bytes.length) {
  8632. chr1 = bytes[i++];
  8633. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8634. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8635. enc1 = chr1 >> 2;
  8636. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8637. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8638. enc4 = chr3 & 63;
  8639. if (isNaN(chr2)) {
  8640. enc3 = enc4 = 64;
  8641. }
  8642. else if (isNaN(chr3)) {
  8643. enc4 = 64;
  8644. }
  8645. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8646. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8647. }
  8648. return "data:image/png;base64," + output;
  8649. };
  8650. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8651. if (bias === void 0) { bias = null; }
  8652. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8653. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8654. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8655. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8656. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8657. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8658. }
  8659. if (bias) {
  8660. minimum.x -= minimum.x * bias.x + bias.y;
  8661. minimum.y -= minimum.y * bias.x + bias.y;
  8662. minimum.z -= minimum.z * bias.x + bias.y;
  8663. maximum.x += maximum.x * bias.x + bias.y;
  8664. maximum.y += maximum.y * bias.x + bias.y;
  8665. maximum.z += maximum.z * bias.x + bias.y;
  8666. }
  8667. return {
  8668. minimum: minimum,
  8669. maximum: maximum
  8670. };
  8671. };
  8672. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8673. if (bias === void 0) { bias = null; }
  8674. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8675. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8676. if (!stride) {
  8677. stride = 3;
  8678. }
  8679. for (var index = start; index < start + count; index++) {
  8680. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8681. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8682. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8683. }
  8684. if (bias) {
  8685. minimum.x -= minimum.x * bias.x + bias.y;
  8686. minimum.y -= minimum.y * bias.x + bias.y;
  8687. minimum.z -= minimum.z * bias.x + bias.y;
  8688. maximum.x += maximum.x * bias.x + bias.y;
  8689. maximum.y += maximum.y * bias.x + bias.y;
  8690. maximum.z += maximum.z * bias.x + bias.y;
  8691. }
  8692. return {
  8693. minimum: minimum,
  8694. maximum: maximum
  8695. };
  8696. };
  8697. Tools.Vector2ArrayFeeder = function (array) {
  8698. return function (index) {
  8699. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8700. var length = isFloatArray ? array.length / 2 : array.length;
  8701. if (index >= length) {
  8702. return null;
  8703. }
  8704. if (isFloatArray) {
  8705. var fa = array;
  8706. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8707. }
  8708. var a = array;
  8709. return a[index];
  8710. };
  8711. };
  8712. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8713. if (bias === void 0) { bias = null; }
  8714. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8715. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8716. var i = 0;
  8717. var cur = feeder(i++);
  8718. while (cur) {
  8719. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8720. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8721. cur = feeder(i++);
  8722. }
  8723. if (bias) {
  8724. minimum.x -= minimum.x * bias.x + bias.y;
  8725. minimum.y -= minimum.y * bias.x + bias.y;
  8726. maximum.x += maximum.x * bias.x + bias.y;
  8727. maximum.y += maximum.y * bias.x + bias.y;
  8728. }
  8729. return {
  8730. minimum: minimum,
  8731. maximum: maximum
  8732. };
  8733. };
  8734. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8735. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8736. return null;
  8737. return Array.isArray(obj) ? obj : [obj];
  8738. };
  8739. // Misc.
  8740. Tools.GetPointerPrefix = function () {
  8741. var eventPrefix = "pointer";
  8742. // Check if pointer events are supported
  8743. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8744. eventPrefix = "mouse";
  8745. }
  8746. return eventPrefix;
  8747. };
  8748. /**
  8749. * @param func - the function to be called
  8750. * @param requester - the object that will request the next frame. Falls back to window.
  8751. */
  8752. Tools.QueueNewFrame = function (func, requester) {
  8753. if (!Tools.IsWindowObjectExist()) {
  8754. return setTimeout(func, 16);
  8755. }
  8756. if (!requester) {
  8757. requester = window;
  8758. }
  8759. if (requester.requestAnimationFrame) {
  8760. return requester.requestAnimationFrame(func);
  8761. }
  8762. else if (requester.msRequestAnimationFrame) {
  8763. return requester.msRequestAnimationFrame(func);
  8764. }
  8765. else if (requester.webkitRequestAnimationFrame) {
  8766. return requester.webkitRequestAnimationFrame(func);
  8767. }
  8768. else if (requester.mozRequestAnimationFrame) {
  8769. return requester.mozRequestAnimationFrame(func);
  8770. }
  8771. else if (requester.oRequestAnimationFrame) {
  8772. return requester.oRequestAnimationFrame(func);
  8773. }
  8774. else {
  8775. return window.setTimeout(func, 16);
  8776. }
  8777. };
  8778. Tools.RequestFullscreen = function (element) {
  8779. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8780. if (!requestFunction)
  8781. return;
  8782. requestFunction.call(element);
  8783. };
  8784. Tools.ExitFullscreen = function () {
  8785. if (document.exitFullscreen) {
  8786. document.exitFullscreen();
  8787. }
  8788. else if (document.mozCancelFullScreen) {
  8789. document.mozCancelFullScreen();
  8790. }
  8791. else if (document.webkitCancelFullScreen) {
  8792. document.webkitCancelFullScreen();
  8793. }
  8794. else if (document.msCancelFullScreen) {
  8795. document.msCancelFullScreen();
  8796. }
  8797. };
  8798. Tools.SetCorsBehavior = function (url, element) {
  8799. if (url && url.indexOf("data:") === 0) {
  8800. return;
  8801. }
  8802. if (Tools.CorsBehavior) {
  8803. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8804. element.crossOrigin = Tools.CorsBehavior;
  8805. }
  8806. else {
  8807. var result = Tools.CorsBehavior(url);
  8808. if (result) {
  8809. element.crossOrigin = result;
  8810. }
  8811. }
  8812. }
  8813. };
  8814. // External files
  8815. Tools.CleanUrl = function (url) {
  8816. url = url.replace(/#/mg, "%23");
  8817. return url;
  8818. };
  8819. Tools.LoadImage = function (url, onLoad, onError, database) {
  8820. if (url instanceof ArrayBuffer) {
  8821. url = Tools.EncodeArrayBufferTobase64(url);
  8822. }
  8823. url = Tools.CleanUrl(url);
  8824. url = Tools.PreprocessUrl(url);
  8825. var img = new Image();
  8826. Tools.SetCorsBehavior(url, img);
  8827. var loadHandler = function () {
  8828. img.removeEventListener("load", loadHandler);
  8829. img.removeEventListener("error", errorHandler);
  8830. onLoad(img);
  8831. };
  8832. var errorHandler = function (err) {
  8833. img.removeEventListener("load", loadHandler);
  8834. img.removeEventListener("error", errorHandler);
  8835. Tools.Error("Error while trying to load image: " + url);
  8836. if (onError) {
  8837. onError("Error while trying to load image: " + url, err);
  8838. }
  8839. };
  8840. img.addEventListener("load", loadHandler);
  8841. img.addEventListener("error", errorHandler);
  8842. var noIndexedDB = function () {
  8843. img.src = url;
  8844. };
  8845. var loadFromIndexedDB = function () {
  8846. if (database) {
  8847. database.loadImageFromDB(url, img);
  8848. }
  8849. };
  8850. //ANY database to do!
  8851. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8852. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8853. }
  8854. else {
  8855. if (url.indexOf("file:") !== -1) {
  8856. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8857. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8858. try {
  8859. var blobURL;
  8860. try {
  8861. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8862. }
  8863. catch (ex) {
  8864. // Chrome doesn't support oneTimeOnly parameter
  8865. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8866. }
  8867. img.src = blobURL;
  8868. }
  8869. catch (e) {
  8870. img.src = "";
  8871. }
  8872. return img;
  8873. }
  8874. }
  8875. noIndexedDB();
  8876. }
  8877. return img;
  8878. };
  8879. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8880. url = Tools.CleanUrl(url);
  8881. url = Tools.PreprocessUrl(url);
  8882. // If file and file input are set
  8883. if (url.indexOf("file:") !== -1) {
  8884. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8885. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8886. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8887. }
  8888. }
  8889. var loadUrl = Tools.BaseUrl + url;
  8890. var aborted = false;
  8891. var fileRequest = {
  8892. onCompleteObservable: new BABYLON.Observable(),
  8893. abort: function () { return aborted = true; },
  8894. };
  8895. var requestFile = function () {
  8896. var request = new XMLHttpRequest();
  8897. var retryHandle = null;
  8898. fileRequest.abort = function () {
  8899. aborted = true;
  8900. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8901. request.abort();
  8902. }
  8903. if (retryHandle !== null) {
  8904. clearTimeout(retryHandle);
  8905. retryHandle = null;
  8906. }
  8907. };
  8908. var retryLoop = function (retryIndex) {
  8909. request.open('GET', loadUrl, true);
  8910. if (useArrayBuffer) {
  8911. request.responseType = "arraybuffer";
  8912. }
  8913. if (onProgress) {
  8914. request.addEventListener("progress", onProgress);
  8915. }
  8916. var onLoadEnd = function () {
  8917. request.removeEventListener("loadend", onLoadEnd);
  8918. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8919. fileRequest.onCompleteObservable.clear();
  8920. };
  8921. request.addEventListener("loadend", onLoadEnd);
  8922. var onReadyStateChange = function () {
  8923. if (aborted) {
  8924. return;
  8925. }
  8926. // In case of undefined state in some browsers.
  8927. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8928. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8929. request.removeEventListener("readystatechange", onReadyStateChange);
  8930. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8931. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8932. return;
  8933. }
  8934. var retryStrategy = Tools.DefaultRetryStrategy;
  8935. if (retryStrategy) {
  8936. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8937. if (waitTime !== -1) {
  8938. // Prevent the request from completing for retry.
  8939. request.removeEventListener("loadend", onLoadEnd);
  8940. request = new XMLHttpRequest();
  8941. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8942. return;
  8943. }
  8944. }
  8945. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8946. if (onError) {
  8947. onError(request, e);
  8948. }
  8949. else {
  8950. throw e;
  8951. }
  8952. }
  8953. };
  8954. request.addEventListener("readystatechange", onReadyStateChange);
  8955. request.send();
  8956. };
  8957. retryLoop(0);
  8958. };
  8959. // Caching all files
  8960. if (database && database.enableSceneOffline) {
  8961. var noIndexedDB_1 = function () {
  8962. if (!aborted) {
  8963. requestFile();
  8964. }
  8965. };
  8966. var loadFromIndexedDB = function () {
  8967. // TODO: database needs to support aborting and should return a IFileRequest
  8968. if (aborted) {
  8969. return;
  8970. }
  8971. if (database) {
  8972. database.loadFileFromDB(url, function (data) {
  8973. if (!aborted) {
  8974. onSuccess(data);
  8975. }
  8976. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8977. }, onProgress ? function (event) {
  8978. if (!aborted) {
  8979. onProgress(event);
  8980. }
  8981. } : undefined, noIndexedDB_1, useArrayBuffer);
  8982. }
  8983. };
  8984. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8985. }
  8986. else {
  8987. requestFile();
  8988. }
  8989. return fileRequest;
  8990. };
  8991. /**
  8992. * Load a script (identified by an url). When the url returns, the
  8993. * content of this file is added into a new script element, attached to the DOM (body element)
  8994. */
  8995. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8996. var head = document.getElementsByTagName('head')[0];
  8997. var script = document.createElement('script');
  8998. script.type = 'text/javascript';
  8999. script.src = scriptUrl;
  9000. script.onload = function () {
  9001. if (onSuccess) {
  9002. onSuccess();
  9003. }
  9004. };
  9005. script.onerror = function (e) {
  9006. if (onError) {
  9007. onError("Unable to load script '" + scriptUrl + "'", e);
  9008. }
  9009. };
  9010. head.appendChild(script);
  9011. };
  9012. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9013. var reader = new FileReader();
  9014. var request = {
  9015. onCompleteObservable: new BABYLON.Observable(),
  9016. abort: function () { return reader.abort(); },
  9017. };
  9018. reader.onloadend = function (e) {
  9019. request.onCompleteObservable.notifyObservers(request);
  9020. };
  9021. reader.onload = function (e) {
  9022. //target doesn't have result from ts 1.3
  9023. callback(e.target['result']);
  9024. };
  9025. reader.onprogress = progressCallback;
  9026. reader.readAsDataURL(fileToLoad);
  9027. return request;
  9028. };
  9029. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9030. var reader = new FileReader();
  9031. var request = {
  9032. onCompleteObservable: new BABYLON.Observable(),
  9033. abort: function () { return reader.abort(); },
  9034. };
  9035. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9036. reader.onerror = function (e) {
  9037. Tools.Log("Error while reading file: " + fileToLoad.name);
  9038. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9039. };
  9040. reader.onload = function (e) {
  9041. //target doesn't have result from ts 1.3
  9042. callback(e.target['result']);
  9043. };
  9044. if (progressCallBack) {
  9045. reader.onprogress = progressCallBack;
  9046. }
  9047. if (!useArrayBuffer) {
  9048. // Asynchronous read
  9049. reader.readAsText(fileToLoad);
  9050. }
  9051. else {
  9052. reader.readAsArrayBuffer(fileToLoad);
  9053. }
  9054. return request;
  9055. };
  9056. //returns a downloadable url to a file content.
  9057. Tools.FileAsURL = function (content) {
  9058. var fileBlob = new Blob([content]);
  9059. var url = window.URL || window.webkitURL;
  9060. var link = url.createObjectURL(fileBlob);
  9061. return link;
  9062. };
  9063. // Misc.
  9064. Tools.Format = function (value, decimals) {
  9065. if (decimals === void 0) { decimals = 2; }
  9066. return value.toFixed(decimals);
  9067. };
  9068. Tools.CheckExtends = function (v, min, max) {
  9069. if (v.x < min.x)
  9070. min.x = v.x;
  9071. if (v.y < min.y)
  9072. min.y = v.y;
  9073. if (v.z < min.z)
  9074. min.z = v.z;
  9075. if (v.x > max.x)
  9076. max.x = v.x;
  9077. if (v.y > max.y)
  9078. max.y = v.y;
  9079. if (v.z > max.z)
  9080. max.z = v.z;
  9081. };
  9082. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9083. for (var prop in source) {
  9084. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9085. continue;
  9086. }
  9087. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9088. continue;
  9089. }
  9090. var sourceValue = source[prop];
  9091. var typeOfSourceValue = typeof sourceValue;
  9092. if (typeOfSourceValue === "function") {
  9093. continue;
  9094. }
  9095. try {
  9096. if (typeOfSourceValue === "object") {
  9097. if (sourceValue instanceof Array) {
  9098. destination[prop] = [];
  9099. if (sourceValue.length > 0) {
  9100. if (typeof sourceValue[0] == "object") {
  9101. for (var index = 0; index < sourceValue.length; index++) {
  9102. var clonedValue = cloneValue(sourceValue[index], destination);
  9103. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9104. destination[prop].push(clonedValue);
  9105. }
  9106. }
  9107. }
  9108. else {
  9109. destination[prop] = sourceValue.slice(0);
  9110. }
  9111. }
  9112. }
  9113. else {
  9114. destination[prop] = cloneValue(sourceValue, destination);
  9115. }
  9116. }
  9117. else {
  9118. destination[prop] = sourceValue;
  9119. }
  9120. }
  9121. catch (e) {
  9122. // Just ignore error (it could be because of a read-only property)
  9123. }
  9124. }
  9125. };
  9126. Tools.IsEmpty = function (obj) {
  9127. for (var i in obj) {
  9128. if (obj.hasOwnProperty(i)) {
  9129. return false;
  9130. }
  9131. }
  9132. return true;
  9133. };
  9134. Tools.RegisterTopRootEvents = function (events) {
  9135. for (var index = 0; index < events.length; index++) {
  9136. var event = events[index];
  9137. window.addEventListener(event.name, event.handler, false);
  9138. try {
  9139. if (window.parent) {
  9140. window.parent.addEventListener(event.name, event.handler, false);
  9141. }
  9142. }
  9143. catch (e) {
  9144. // Silently fails...
  9145. }
  9146. }
  9147. };
  9148. Tools.UnregisterTopRootEvents = function (events) {
  9149. for (var index = 0; index < events.length; index++) {
  9150. var event = events[index];
  9151. window.removeEventListener(event.name, event.handler);
  9152. try {
  9153. if (window.parent) {
  9154. window.parent.removeEventListener(event.name, event.handler);
  9155. }
  9156. }
  9157. catch (e) {
  9158. // Silently fails...
  9159. }
  9160. }
  9161. };
  9162. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9163. if (mimeType === void 0) { mimeType = "image/png"; }
  9164. // Read the contents of the framebuffer
  9165. var numberOfChannelsByLine = width * 4;
  9166. var halfHeight = height / 2;
  9167. //Reading datas from WebGL
  9168. var data = engine.readPixels(0, 0, width, height);
  9169. //To flip image on Y axis.
  9170. for (var i = 0; i < halfHeight; i++) {
  9171. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9172. var currentCell = j + i * numberOfChannelsByLine;
  9173. var targetLine = height - i - 1;
  9174. var targetCell = j + targetLine * numberOfChannelsByLine;
  9175. var temp = data[currentCell];
  9176. data[currentCell] = data[targetCell];
  9177. data[targetCell] = temp;
  9178. }
  9179. }
  9180. // Create a 2D canvas to store the result
  9181. if (!screenshotCanvas) {
  9182. screenshotCanvas = document.createElement('canvas');
  9183. }
  9184. screenshotCanvas.width = width;
  9185. screenshotCanvas.height = height;
  9186. var context = screenshotCanvas.getContext('2d');
  9187. if (context) {
  9188. // Copy the pixels to a 2D canvas
  9189. var imageData = context.createImageData(width, height);
  9190. var castData = (imageData.data);
  9191. castData.set(data);
  9192. context.putImageData(imageData, 0, 0);
  9193. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9194. }
  9195. };
  9196. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9197. if (mimeType === void 0) { mimeType = "image/png"; }
  9198. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9199. if (successCallback) {
  9200. successCallback(base64Image);
  9201. }
  9202. else {
  9203. // We need HTMLCanvasElement.toBlob for HD screenshots
  9204. if (!screenshotCanvas.toBlob) {
  9205. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9206. screenshotCanvas.toBlob = function (callback, type, quality) {
  9207. var _this = this;
  9208. setTimeout(function () {
  9209. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9210. for (var i = 0; i < len; i++) {
  9211. arr[i] = binStr.charCodeAt(i);
  9212. }
  9213. callback(new Blob([arr], { type: type || 'image/png' }));
  9214. });
  9215. };
  9216. }
  9217. screenshotCanvas.toBlob(function (blob) {
  9218. var url = URL.createObjectURL(blob);
  9219. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9220. if (("download" in document.createElement("a"))) {
  9221. var a = window.document.createElement("a");
  9222. a.href = url;
  9223. if (fileName) {
  9224. a.setAttribute("download", fileName);
  9225. }
  9226. else {
  9227. var date = new Date();
  9228. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9229. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9230. }
  9231. window.document.body.appendChild(a);
  9232. a.addEventListener("click", function () {
  9233. if (a.parentElement) {
  9234. a.parentElement.removeChild(a);
  9235. }
  9236. });
  9237. a.click();
  9238. }
  9239. else {
  9240. var newWindow = window.open("");
  9241. if (!newWindow)
  9242. return;
  9243. var img = newWindow.document.createElement("img");
  9244. img.onload = function () {
  9245. // no longer need to read the blob so it's revoked
  9246. URL.revokeObjectURL(url);
  9247. };
  9248. img.src = url;
  9249. newWindow.document.body.appendChild(img);
  9250. }
  9251. });
  9252. }
  9253. };
  9254. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9255. if (mimeType === void 0) { mimeType = "image/png"; }
  9256. var width;
  9257. var height;
  9258. // If a precision value is specified
  9259. if (size.precision) {
  9260. width = Math.round(engine.getRenderWidth() * size.precision);
  9261. height = Math.round(width / engine.getAspectRatio(camera));
  9262. }
  9263. else if (size.width && size.height) {
  9264. width = size.width;
  9265. height = size.height;
  9266. }
  9267. //If passing only width, computing height to keep display canvas ratio.
  9268. else if (size.width && !size.height) {
  9269. width = size.width;
  9270. height = Math.round(width / engine.getAspectRatio(camera));
  9271. }
  9272. //If passing only height, computing width to keep display canvas ratio.
  9273. else if (size.height && !size.width) {
  9274. height = size.height;
  9275. width = Math.round(height * engine.getAspectRatio(camera));
  9276. }
  9277. //Assuming here that "size" parameter is a number
  9278. else if (!isNaN(size)) {
  9279. height = size;
  9280. width = size;
  9281. }
  9282. else {
  9283. Tools.Error("Invalid 'size' parameter !");
  9284. return;
  9285. }
  9286. if (!screenshotCanvas) {
  9287. screenshotCanvas = document.createElement('canvas');
  9288. }
  9289. screenshotCanvas.width = width;
  9290. screenshotCanvas.height = height;
  9291. var renderContext = screenshotCanvas.getContext("2d");
  9292. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9293. var newWidth = width;
  9294. var newHeight = newWidth / ratio;
  9295. if (newHeight > height) {
  9296. newHeight = height;
  9297. newWidth = newHeight * ratio;
  9298. }
  9299. var offsetX = Math.max(0, width - newWidth) / 2;
  9300. var offsetY = Math.max(0, height - newHeight) / 2;
  9301. var renderingCanvas = engine.getRenderingCanvas();
  9302. if (renderContext && renderingCanvas) {
  9303. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9304. }
  9305. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9306. };
  9307. /**
  9308. * Generates an image screenshot from the specified camera.
  9309. *
  9310. * @param engine The engine to use for rendering
  9311. * @param camera The camera to use for rendering
  9312. * @param size This parameter can be set to a single number or to an object with the
  9313. * following (optional) properties: precision, width, height. If a single number is passed,
  9314. * it will be used for both width and height. If an object is passed, the screenshot size
  9315. * will be derived from the parameters. The precision property is a multiplier allowing
  9316. * rendering at a higher or lower resolution.
  9317. * @param successCallback The callback receives a single parameter which contains the
  9318. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9319. * src parameter of an <img> to display it.
  9320. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9321. * Check your browser for supported MIME types.
  9322. * @param samples Texture samples (default: 1)
  9323. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9324. * @param fileName A name for for the downloaded file.
  9325. * @constructor
  9326. */
  9327. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9328. if (mimeType === void 0) { mimeType = "image/png"; }
  9329. if (samples === void 0) { samples = 1; }
  9330. if (antialiasing === void 0) { antialiasing = false; }
  9331. var width;
  9332. var height;
  9333. //If a precision value is specified
  9334. if (size.precision) {
  9335. width = Math.round(engine.getRenderWidth() * size.precision);
  9336. height = Math.round(width / engine.getAspectRatio(camera));
  9337. size = { width: width, height: height };
  9338. }
  9339. else if (size.width && size.height) {
  9340. width = size.width;
  9341. height = size.height;
  9342. }
  9343. //If passing only width, computing height to keep display canvas ratio.
  9344. else if (size.width && !size.height) {
  9345. width = size.width;
  9346. height = Math.round(width / engine.getAspectRatio(camera));
  9347. size = { width: width, height: height };
  9348. }
  9349. //If passing only height, computing width to keep display canvas ratio.
  9350. else if (size.height && !size.width) {
  9351. height = size.height;
  9352. width = Math.round(height * engine.getAspectRatio(camera));
  9353. size = { width: width, height: height };
  9354. }
  9355. //Assuming here that "size" parameter is a number
  9356. else if (!isNaN(size)) {
  9357. height = size;
  9358. width = size;
  9359. }
  9360. else {
  9361. Tools.Error("Invalid 'size' parameter !");
  9362. return;
  9363. }
  9364. var scene = camera.getScene();
  9365. var previousCamera = null;
  9366. if (scene.activeCamera !== camera) {
  9367. previousCamera = scene.activeCamera;
  9368. scene.activeCamera = camera;
  9369. }
  9370. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9371. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9372. texture.renderList = null;
  9373. texture.samples = samples;
  9374. if (antialiasing) {
  9375. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9376. }
  9377. texture.onAfterRenderObservable.add(function () {
  9378. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9379. });
  9380. scene.incrementRenderId();
  9381. scene.resetCachedMaterial();
  9382. texture.render(true);
  9383. texture.dispose();
  9384. if (previousCamera) {
  9385. scene.activeCamera = previousCamera;
  9386. }
  9387. camera.getProjectionMatrix(true); // Force cache refresh;
  9388. };
  9389. // XHR response validator for local file scenario
  9390. Tools.ValidateXHRData = function (xhr, dataType) {
  9391. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9392. if (dataType === void 0) { dataType = 7; }
  9393. try {
  9394. if (dataType & 1) {
  9395. if (xhr.responseText && xhr.responseText.length > 0) {
  9396. return true;
  9397. }
  9398. else if (dataType === 1) {
  9399. return false;
  9400. }
  9401. }
  9402. if (dataType & 2) {
  9403. // Check header width and height since there is no "TGA" magic number
  9404. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9405. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9406. return true;
  9407. }
  9408. else if (dataType === 2) {
  9409. return false;
  9410. }
  9411. }
  9412. if (dataType & 4) {
  9413. // Check for the "DDS" magic number
  9414. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9415. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9416. return true;
  9417. }
  9418. else {
  9419. return false;
  9420. }
  9421. }
  9422. }
  9423. catch (e) {
  9424. // Global protection
  9425. }
  9426. return false;
  9427. };
  9428. /**
  9429. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9430. * Be aware Math.random() could cause collisions, but:
  9431. * "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"
  9432. */
  9433. Tools.RandomId = function () {
  9434. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9435. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9436. return v.toString(16);
  9437. });
  9438. };
  9439. /**
  9440. * Test if the given uri is a base64 string.
  9441. * @param uri The uri to test
  9442. * @return True if the uri is a base64 string or false otherwise.
  9443. */
  9444. Tools.IsBase64 = function (uri) {
  9445. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9446. };
  9447. /**
  9448. * Decode the given base64 uri.
  9449. * @param uri The uri to decode
  9450. * @return The decoded base64 data.
  9451. */
  9452. Tools.DecodeBase64 = function (uri) {
  9453. var decodedString = atob(uri.split(",")[1]);
  9454. var bufferLength = decodedString.length;
  9455. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9456. for (var i = 0; i < bufferLength; i++) {
  9457. bufferView[i] = decodedString.charCodeAt(i);
  9458. }
  9459. return bufferView.buffer;
  9460. };
  9461. Object.defineProperty(Tools, "NoneLogLevel", {
  9462. get: function () {
  9463. return Tools._NoneLogLevel;
  9464. },
  9465. enumerable: true,
  9466. configurable: true
  9467. });
  9468. Object.defineProperty(Tools, "MessageLogLevel", {
  9469. get: function () {
  9470. return Tools._MessageLogLevel;
  9471. },
  9472. enumerable: true,
  9473. configurable: true
  9474. });
  9475. Object.defineProperty(Tools, "WarningLogLevel", {
  9476. get: function () {
  9477. return Tools._WarningLogLevel;
  9478. },
  9479. enumerable: true,
  9480. configurable: true
  9481. });
  9482. Object.defineProperty(Tools, "ErrorLogLevel", {
  9483. get: function () {
  9484. return Tools._ErrorLogLevel;
  9485. },
  9486. enumerable: true,
  9487. configurable: true
  9488. });
  9489. Object.defineProperty(Tools, "AllLogLevel", {
  9490. get: function () {
  9491. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9492. },
  9493. enumerable: true,
  9494. configurable: true
  9495. });
  9496. Tools._AddLogEntry = function (entry) {
  9497. Tools._LogCache = entry + Tools._LogCache;
  9498. if (Tools.OnNewCacheEntry) {
  9499. Tools.OnNewCacheEntry(entry);
  9500. }
  9501. };
  9502. Tools._FormatMessage = function (message) {
  9503. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9504. var date = new Date();
  9505. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9506. };
  9507. Tools._LogDisabled = function (message) {
  9508. // nothing to do
  9509. };
  9510. Tools._LogEnabled = function (message) {
  9511. var formattedMessage = Tools._FormatMessage(message);
  9512. console.log("BJS - " + formattedMessage);
  9513. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9514. Tools._AddLogEntry(entry);
  9515. };
  9516. Tools._WarnDisabled = function (message) {
  9517. // nothing to do
  9518. };
  9519. Tools._WarnEnabled = function (message) {
  9520. var formattedMessage = Tools._FormatMessage(message);
  9521. console.warn("BJS - " + formattedMessage);
  9522. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9523. Tools._AddLogEntry(entry);
  9524. };
  9525. Tools._ErrorDisabled = function (message) {
  9526. // nothing to do
  9527. };
  9528. Tools._ErrorEnabled = function (message) {
  9529. Tools.errorsCount++;
  9530. var formattedMessage = Tools._FormatMessage(message);
  9531. console.error("BJS - " + formattedMessage);
  9532. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9533. Tools._AddLogEntry(entry);
  9534. };
  9535. Object.defineProperty(Tools, "LogCache", {
  9536. get: function () {
  9537. return Tools._LogCache;
  9538. },
  9539. enumerable: true,
  9540. configurable: true
  9541. });
  9542. Tools.ClearLogCache = function () {
  9543. Tools._LogCache = "";
  9544. Tools.errorsCount = 0;
  9545. };
  9546. Object.defineProperty(Tools, "LogLevels", {
  9547. set: function (level) {
  9548. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9549. Tools.Log = Tools._LogEnabled;
  9550. }
  9551. else {
  9552. Tools.Log = Tools._LogDisabled;
  9553. }
  9554. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9555. Tools.Warn = Tools._WarnEnabled;
  9556. }
  9557. else {
  9558. Tools.Warn = Tools._WarnDisabled;
  9559. }
  9560. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9561. Tools.Error = Tools._ErrorEnabled;
  9562. }
  9563. else {
  9564. Tools.Error = Tools._ErrorDisabled;
  9565. }
  9566. },
  9567. enumerable: true,
  9568. configurable: true
  9569. });
  9570. Tools.IsWindowObjectExist = function () {
  9571. return (typeof window) !== "undefined";
  9572. };
  9573. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9574. get: function () {
  9575. return Tools._PerformanceNoneLogLevel;
  9576. },
  9577. enumerable: true,
  9578. configurable: true
  9579. });
  9580. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9581. get: function () {
  9582. return Tools._PerformanceUserMarkLogLevel;
  9583. },
  9584. enumerable: true,
  9585. configurable: true
  9586. });
  9587. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9588. get: function () {
  9589. return Tools._PerformanceConsoleLogLevel;
  9590. },
  9591. enumerable: true,
  9592. configurable: true
  9593. });
  9594. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9595. set: function (level) {
  9596. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9597. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9598. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9599. return;
  9600. }
  9601. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9602. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9603. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9604. return;
  9605. }
  9606. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9607. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9608. },
  9609. enumerable: true,
  9610. configurable: true
  9611. });
  9612. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9613. };
  9614. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9615. };
  9616. Tools._StartUserMark = function (counterName, condition) {
  9617. if (condition === void 0) { condition = true; }
  9618. if (!Tools._performance) {
  9619. if (!Tools.IsWindowObjectExist()) {
  9620. return;
  9621. }
  9622. Tools._performance = window.performance;
  9623. }
  9624. if (!condition || !Tools._performance.mark) {
  9625. return;
  9626. }
  9627. Tools._performance.mark(counterName + "-Begin");
  9628. };
  9629. Tools._EndUserMark = function (counterName, condition) {
  9630. if (condition === void 0) { condition = true; }
  9631. if (!condition || !Tools._performance.mark) {
  9632. return;
  9633. }
  9634. Tools._performance.mark(counterName + "-End");
  9635. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9636. };
  9637. Tools._StartPerformanceConsole = function (counterName, condition) {
  9638. if (condition === void 0) { condition = true; }
  9639. if (!condition) {
  9640. return;
  9641. }
  9642. Tools._StartUserMark(counterName, condition);
  9643. if (console.time) {
  9644. console.time(counterName);
  9645. }
  9646. };
  9647. Tools._EndPerformanceConsole = function (counterName, condition) {
  9648. if (condition === void 0) { condition = true; }
  9649. if (!condition) {
  9650. return;
  9651. }
  9652. Tools._EndUserMark(counterName, condition);
  9653. if (console.time) {
  9654. console.timeEnd(counterName);
  9655. }
  9656. };
  9657. Object.defineProperty(Tools, "Now", {
  9658. get: function () {
  9659. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9660. return window.performance.now();
  9661. }
  9662. return Date.now();
  9663. },
  9664. enumerable: true,
  9665. configurable: true
  9666. });
  9667. /**
  9668. * This method will return the name of the class used to create the instance of the given object.
  9669. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9670. * @param object the object to get the class name from
  9671. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9672. */
  9673. Tools.GetClassName = function (object, isType) {
  9674. if (isType === void 0) { isType = false; }
  9675. var name = null;
  9676. if (!isType && object.getClassName) {
  9677. name = object.getClassName();
  9678. }
  9679. else {
  9680. if (object instanceof Object) {
  9681. var classObj = isType ? object : Object.getPrototypeOf(object);
  9682. name = classObj.constructor["__bjsclassName__"];
  9683. }
  9684. if (!name) {
  9685. name = typeof object;
  9686. }
  9687. }
  9688. return name;
  9689. };
  9690. Tools.First = function (array, predicate) {
  9691. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9692. var el = array_1[_i];
  9693. if (predicate(el)) {
  9694. return el;
  9695. }
  9696. }
  9697. return null;
  9698. };
  9699. /**
  9700. * This method will return the name of the full name of the class, including its owning module (if any).
  9701. * 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).
  9702. * @param object the object to get the class name from
  9703. * @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.
  9704. */
  9705. Tools.getFullClassName = function (object, isType) {
  9706. if (isType === void 0) { isType = false; }
  9707. var className = null;
  9708. var moduleName = null;
  9709. if (!isType && object.getClassName) {
  9710. className = object.getClassName();
  9711. }
  9712. else {
  9713. if (object instanceof Object) {
  9714. var classObj = isType ? object : Object.getPrototypeOf(object);
  9715. className = classObj.constructor["__bjsclassName__"];
  9716. moduleName = classObj.constructor["__bjsmoduleName__"];
  9717. }
  9718. if (!className) {
  9719. className = typeof object;
  9720. }
  9721. }
  9722. if (!className) {
  9723. return null;
  9724. }
  9725. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9726. };
  9727. /**
  9728. * 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.
  9729. * @param array
  9730. */
  9731. Tools.arrayOrStringFeeder = function (array) {
  9732. return function (index) {
  9733. if (index >= array.length) {
  9734. return null;
  9735. }
  9736. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9737. if (val && val.getHashCode) {
  9738. val = val.getHashCode();
  9739. }
  9740. if (typeof val === "string") {
  9741. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9742. }
  9743. return val;
  9744. };
  9745. };
  9746. /**
  9747. * Compute the hashCode of a stream of number
  9748. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9749. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9750. * @return the hash code computed
  9751. */
  9752. Tools.hashCodeFromStream = function (feeder) {
  9753. // Based from here: http://stackoverflow.com/a/7616484/802124
  9754. var hash = 0;
  9755. var index = 0;
  9756. var chr = feeder(index++);
  9757. while (chr != null) {
  9758. hash = ((hash << 5) - hash) + chr;
  9759. hash |= 0; // Convert to 32bit integer
  9760. chr = feeder(index++);
  9761. }
  9762. return hash;
  9763. };
  9764. /**
  9765. * Returns a promise that resolves after the given amount of time.
  9766. * @param delay Number of milliseconds to delay
  9767. * @returns Promise that resolves after the given amount of time
  9768. */
  9769. Tools.DelayAsync = function (delay) {
  9770. return new Promise(function (resolve) {
  9771. setTimeout(function () {
  9772. resolve();
  9773. }, delay);
  9774. });
  9775. };
  9776. Tools.BaseUrl = "";
  9777. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9778. /**
  9779. * Default behaviour for cors in the application.
  9780. * It can be a string if the expected behavior is identical in the entire app.
  9781. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9782. */
  9783. Tools.CorsBehavior = "anonymous";
  9784. Tools.UseFallbackTexture = true;
  9785. /**
  9786. * Use this object to register external classes like custom textures or material
  9787. * to allow the laoders to instantiate them
  9788. */
  9789. Tools.RegisteredExternalClasses = {};
  9790. // Used in case of a texture loading problem
  9791. 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";
  9792. Tools._tmpFloatArray = new Float32Array(1);
  9793. Tools.PreprocessUrl = function (url) {
  9794. return url;
  9795. };
  9796. // Logs
  9797. Tools._NoneLogLevel = 0;
  9798. Tools._MessageLogLevel = 1;
  9799. Tools._WarningLogLevel = 2;
  9800. Tools._ErrorLogLevel = 4;
  9801. Tools._LogCache = "";
  9802. Tools.errorsCount = 0;
  9803. Tools.Log = Tools._LogEnabled;
  9804. Tools.Warn = Tools._WarnEnabled;
  9805. Tools.Error = Tools._ErrorEnabled;
  9806. // Performances
  9807. Tools._PerformanceNoneLogLevel = 0;
  9808. Tools._PerformanceUserMarkLogLevel = 1;
  9809. Tools._PerformanceConsoleLogLevel = 2;
  9810. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9811. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9812. return Tools;
  9813. }());
  9814. BABYLON.Tools = Tools;
  9815. /**
  9816. * This class is used to track a performance counter which is number based.
  9817. * The user has access to many properties which give statistics of different nature
  9818. *
  9819. * The implementer can track two kinds of Performance Counter: time and count
  9820. * 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.
  9821. * 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.
  9822. */
  9823. var PerfCounter = /** @class */ (function () {
  9824. function PerfCounter() {
  9825. this._startMonitoringTime = 0;
  9826. this._min = 0;
  9827. this._max = 0;
  9828. this._average = 0;
  9829. this._lastSecAverage = 0;
  9830. this._current = 0;
  9831. this._totalValueCount = 0;
  9832. this._totalAccumulated = 0;
  9833. this._lastSecAccumulated = 0;
  9834. this._lastSecTime = 0;
  9835. this._lastSecValueCount = 0;
  9836. }
  9837. Object.defineProperty(PerfCounter.prototype, "min", {
  9838. /**
  9839. * Returns the smallest value ever
  9840. */
  9841. get: function () {
  9842. return this._min;
  9843. },
  9844. enumerable: true,
  9845. configurable: true
  9846. });
  9847. Object.defineProperty(PerfCounter.prototype, "max", {
  9848. /**
  9849. * Returns the biggest value ever
  9850. */
  9851. get: function () {
  9852. return this._max;
  9853. },
  9854. enumerable: true,
  9855. configurable: true
  9856. });
  9857. Object.defineProperty(PerfCounter.prototype, "average", {
  9858. /**
  9859. * Returns the average value since the performance counter is running
  9860. */
  9861. get: function () {
  9862. return this._average;
  9863. },
  9864. enumerable: true,
  9865. configurable: true
  9866. });
  9867. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9868. /**
  9869. * Returns the average value of the last second the counter was monitored
  9870. */
  9871. get: function () {
  9872. return this._lastSecAverage;
  9873. },
  9874. enumerable: true,
  9875. configurable: true
  9876. });
  9877. Object.defineProperty(PerfCounter.prototype, "current", {
  9878. /**
  9879. * Returns the current value
  9880. */
  9881. get: function () {
  9882. return this._current;
  9883. },
  9884. enumerable: true,
  9885. configurable: true
  9886. });
  9887. Object.defineProperty(PerfCounter.prototype, "total", {
  9888. get: function () {
  9889. return this._totalAccumulated;
  9890. },
  9891. enumerable: true,
  9892. configurable: true
  9893. });
  9894. Object.defineProperty(PerfCounter.prototype, "count", {
  9895. get: function () {
  9896. return this._totalValueCount;
  9897. },
  9898. enumerable: true,
  9899. configurable: true
  9900. });
  9901. /**
  9902. * Call this method to start monitoring a new frame.
  9903. * 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.
  9904. */
  9905. PerfCounter.prototype.fetchNewFrame = function () {
  9906. this._totalValueCount++;
  9907. this._current = 0;
  9908. this._lastSecValueCount++;
  9909. };
  9910. /**
  9911. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9912. * @param newCount the count value to add to the monitored count
  9913. * @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.
  9914. */
  9915. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9916. if (!PerfCounter.Enabled) {
  9917. return;
  9918. }
  9919. this._current += newCount;
  9920. if (fetchResult) {
  9921. this._fetchResult();
  9922. }
  9923. };
  9924. /**
  9925. * Start monitoring this performance counter
  9926. */
  9927. PerfCounter.prototype.beginMonitoring = function () {
  9928. if (!PerfCounter.Enabled) {
  9929. return;
  9930. }
  9931. this._startMonitoringTime = Tools.Now;
  9932. };
  9933. /**
  9934. * Compute the time lapsed since the previous beginMonitoring() call.
  9935. * @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
  9936. */
  9937. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9938. if (newFrame === void 0) { newFrame = true; }
  9939. if (!PerfCounter.Enabled) {
  9940. return;
  9941. }
  9942. if (newFrame) {
  9943. this.fetchNewFrame();
  9944. }
  9945. var currentTime = Tools.Now;
  9946. this._current = currentTime - this._startMonitoringTime;
  9947. if (newFrame) {
  9948. this._fetchResult();
  9949. }
  9950. };
  9951. PerfCounter.prototype._fetchResult = function () {
  9952. this._totalAccumulated += this._current;
  9953. this._lastSecAccumulated += this._current;
  9954. // Min/Max update
  9955. this._min = Math.min(this._min, this._current);
  9956. this._max = Math.max(this._max, this._current);
  9957. this._average = this._totalAccumulated / this._totalValueCount;
  9958. // Reset last sec?
  9959. var now = Tools.Now;
  9960. if ((now - this._lastSecTime) > 1000) {
  9961. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9962. this._lastSecTime = now;
  9963. this._lastSecAccumulated = 0;
  9964. this._lastSecValueCount = 0;
  9965. }
  9966. };
  9967. PerfCounter.Enabled = true;
  9968. return PerfCounter;
  9969. }());
  9970. BABYLON.PerfCounter = PerfCounter;
  9971. /**
  9972. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9973. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9974. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9975. * @param name The name of the class, case should be preserved
  9976. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9977. */
  9978. function className(name, module) {
  9979. return function (target) {
  9980. target["__bjsclassName__"] = name;
  9981. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9982. };
  9983. }
  9984. BABYLON.className = className;
  9985. /**
  9986. * An implementation of a loop for asynchronous functions.
  9987. */
  9988. var AsyncLoop = /** @class */ (function () {
  9989. /**
  9990. * Constroctor.
  9991. * @param iterations the number of iterations.
  9992. * @param _fn the function to run each iteration
  9993. * @param _successCallback the callback that will be called upon succesful execution
  9994. * @param offset starting offset.
  9995. */
  9996. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9997. if (offset === void 0) { offset = 0; }
  9998. this.iterations = iterations;
  9999. this._fn = _fn;
  10000. this._successCallback = _successCallback;
  10001. this.index = offset - 1;
  10002. this._done = false;
  10003. }
  10004. /**
  10005. * Execute the next iteration. Must be called after the last iteration was finished.
  10006. */
  10007. AsyncLoop.prototype.executeNext = function () {
  10008. if (!this._done) {
  10009. if (this.index + 1 < this.iterations) {
  10010. ++this.index;
  10011. this._fn(this);
  10012. }
  10013. else {
  10014. this.breakLoop();
  10015. }
  10016. }
  10017. };
  10018. /**
  10019. * Break the loop and run the success callback.
  10020. */
  10021. AsyncLoop.prototype.breakLoop = function () {
  10022. this._done = true;
  10023. this._successCallback();
  10024. };
  10025. /**
  10026. * Helper function
  10027. */
  10028. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10029. if (offset === void 0) { offset = 0; }
  10030. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10031. loop.executeNext();
  10032. return loop;
  10033. };
  10034. /**
  10035. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10036. * @param iterations total number of iterations
  10037. * @param syncedIterations number of synchronous iterations in each async iteration.
  10038. * @param fn the function to call each iteration.
  10039. * @param callback a success call back that will be called when iterating stops.
  10040. * @param breakFunction a break condition (optional)
  10041. * @param timeout timeout settings for the setTimeout function. default - 0.
  10042. * @constructor
  10043. */
  10044. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10045. if (timeout === void 0) { timeout = 0; }
  10046. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10047. if (breakFunction && breakFunction())
  10048. loop.breakLoop();
  10049. else {
  10050. setTimeout(function () {
  10051. for (var i = 0; i < syncedIterations; ++i) {
  10052. var iteration = (loop.index * syncedIterations) + i;
  10053. if (iteration >= iterations)
  10054. break;
  10055. fn(iteration);
  10056. if (breakFunction && breakFunction()) {
  10057. loop.breakLoop();
  10058. break;
  10059. }
  10060. }
  10061. loop.executeNext();
  10062. }, timeout);
  10063. }
  10064. }, callback);
  10065. };
  10066. return AsyncLoop;
  10067. }());
  10068. BABYLON.AsyncLoop = AsyncLoop;
  10069. })(BABYLON || (BABYLON = {}));
  10070. //# sourceMappingURL=babylon.tools.js.map
  10071. var BABYLON;
  10072. (function (BABYLON) {
  10073. var PromiseStates;
  10074. (function (PromiseStates) {
  10075. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10076. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10077. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10078. })(PromiseStates || (PromiseStates = {}));
  10079. var FulFillmentAgregator = /** @class */ (function () {
  10080. function FulFillmentAgregator() {
  10081. this.count = 0;
  10082. this.target = 0;
  10083. this.results = [];
  10084. }
  10085. return FulFillmentAgregator;
  10086. }());
  10087. var InternalPromise = /** @class */ (function () {
  10088. function InternalPromise(resolver) {
  10089. var _this = this;
  10090. this._state = PromiseStates.Pending;
  10091. this._children = new Array();
  10092. this._rejectWasConsumed = false;
  10093. if (!resolver) {
  10094. return;
  10095. }
  10096. try {
  10097. resolver(function (value) {
  10098. _this._resolve(value);
  10099. }, function (reason) {
  10100. _this._reject(reason);
  10101. });
  10102. }
  10103. catch (e) {
  10104. this._reject(e);
  10105. }
  10106. }
  10107. Object.defineProperty(InternalPromise.prototype, "_result", {
  10108. get: function () {
  10109. return this._resultValue;
  10110. },
  10111. set: function (value) {
  10112. this._resultValue = value;
  10113. if (this._parent && this._parent._result === undefined) {
  10114. this._parent._result = value;
  10115. }
  10116. },
  10117. enumerable: true,
  10118. configurable: true
  10119. });
  10120. InternalPromise.prototype.catch = function (onRejected) {
  10121. return this.then(undefined, onRejected);
  10122. };
  10123. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10124. var _this = this;
  10125. var newPromise = new InternalPromise();
  10126. newPromise._onFulfilled = onFulfilled;
  10127. newPromise._onRejected = onRejected;
  10128. // Composition
  10129. this._children.push(newPromise);
  10130. newPromise._parent = this;
  10131. if (this._state !== PromiseStates.Pending) {
  10132. BABYLON.Tools.SetImmediate(function () {
  10133. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10134. var returnedValue = newPromise._resolve(_this._result);
  10135. if (returnedValue !== undefined && returnedValue !== null) {
  10136. if (returnedValue._state !== undefined) {
  10137. var returnedPromise = returnedValue;
  10138. newPromise._children.push(returnedPromise);
  10139. returnedPromise._parent = newPromise;
  10140. newPromise = returnedPromise;
  10141. }
  10142. else {
  10143. newPromise._result = returnedValue;
  10144. }
  10145. }
  10146. }
  10147. else {
  10148. newPromise._reject(_this._reason);
  10149. }
  10150. });
  10151. }
  10152. return newPromise;
  10153. };
  10154. InternalPromise.prototype._moveChildren = function (children) {
  10155. var _this = this;
  10156. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10157. this._children.forEach(function (child) {
  10158. child._parent = _this;
  10159. });
  10160. if (this._state === PromiseStates.Fulfilled) {
  10161. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10162. var child = _b[_i];
  10163. child._resolve(this._result);
  10164. }
  10165. }
  10166. else if (this._state === PromiseStates.Rejected) {
  10167. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10168. var child = _d[_c];
  10169. child._reject(this._reason);
  10170. }
  10171. }
  10172. var _a;
  10173. };
  10174. InternalPromise.prototype._resolve = function (value) {
  10175. try {
  10176. this._state = PromiseStates.Fulfilled;
  10177. var returnedValue = null;
  10178. if (this._onFulfilled) {
  10179. returnedValue = this._onFulfilled(value);
  10180. }
  10181. if (returnedValue !== undefined && returnedValue !== null) {
  10182. if (returnedValue._state !== undefined) {
  10183. // Transmit children
  10184. var returnedPromise = returnedValue;
  10185. returnedPromise._parent = this;
  10186. returnedPromise._moveChildren(this._children);
  10187. value = returnedPromise._result;
  10188. }
  10189. else {
  10190. value = returnedValue;
  10191. }
  10192. }
  10193. this._result = value;
  10194. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10195. var child = _a[_i];
  10196. child._resolve(value);
  10197. }
  10198. this._children.length = 0;
  10199. delete this._onFulfilled;
  10200. delete this._onRejected;
  10201. }
  10202. catch (e) {
  10203. this._reject(e, true);
  10204. }
  10205. };
  10206. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10207. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10208. this._state = PromiseStates.Rejected;
  10209. this._reason = reason;
  10210. if (this._onRejected && !onLocalThrow) {
  10211. try {
  10212. this._onRejected(reason);
  10213. this._rejectWasConsumed = true;
  10214. }
  10215. catch (e) {
  10216. reason = e;
  10217. }
  10218. }
  10219. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10220. var child = _a[_i];
  10221. if (this._rejectWasConsumed) {
  10222. child._resolve(null);
  10223. }
  10224. else {
  10225. child._reject(reason);
  10226. }
  10227. }
  10228. this._children.length = 0;
  10229. delete this._onFulfilled;
  10230. delete this._onRejected;
  10231. };
  10232. InternalPromise.resolve = function (value) {
  10233. var newPromise = new InternalPromise();
  10234. newPromise._resolve(value);
  10235. return newPromise;
  10236. };
  10237. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10238. promise.then(function (value) {
  10239. agregator.results[index] = value;
  10240. agregator.count++;
  10241. if (agregator.count === agregator.target) {
  10242. agregator.rootPromise._resolve(agregator.results);
  10243. }
  10244. return null;
  10245. }, function (reason) {
  10246. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10247. agregator.rootPromise._reject(reason);
  10248. }
  10249. });
  10250. };
  10251. InternalPromise.all = function (promises) {
  10252. var newPromise = new InternalPromise();
  10253. var agregator = new FulFillmentAgregator();
  10254. agregator.target = promises.length;
  10255. agregator.rootPromise = newPromise;
  10256. if (promises.length) {
  10257. for (var index = 0; index < promises.length; index++) {
  10258. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10259. }
  10260. }
  10261. else {
  10262. newPromise._resolve([]);
  10263. }
  10264. return newPromise;
  10265. };
  10266. InternalPromise.race = function (promises) {
  10267. var newPromise = new InternalPromise();
  10268. if (promises.length) {
  10269. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10270. var promise = promises_1[_i];
  10271. promise.then(function (value) {
  10272. if (newPromise) {
  10273. newPromise._resolve(value);
  10274. newPromise = null;
  10275. }
  10276. return null;
  10277. }, function (reason) {
  10278. if (newPromise) {
  10279. newPromise._reject(reason);
  10280. newPromise = null;
  10281. }
  10282. });
  10283. }
  10284. }
  10285. return newPromise;
  10286. };
  10287. return InternalPromise;
  10288. }());
  10289. /**
  10290. * Helper class that provides a small promise polyfill
  10291. */
  10292. var PromisePolyfill = /** @class */ (function () {
  10293. function PromisePolyfill() {
  10294. }
  10295. /**
  10296. * Static function used to check if the polyfill is required
  10297. * If this is the case then the function will inject the polyfill to window.Promise
  10298. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10299. */
  10300. PromisePolyfill.Apply = function (force) {
  10301. if (force === void 0) { force = false; }
  10302. if (force || typeof Promise === 'undefined') {
  10303. var root = window;
  10304. root.Promise = InternalPromise;
  10305. }
  10306. };
  10307. return PromisePolyfill;
  10308. }());
  10309. BABYLON.PromisePolyfill = PromisePolyfill;
  10310. })(BABYLON || (BABYLON = {}));
  10311. //# sourceMappingURL=babylon.promise.js.map
  10312. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10313. var BABYLON;
  10314. (function (BABYLON) {
  10315. /**
  10316. * Helper class to push actions to a pool of workers.
  10317. */
  10318. var WorkerPool = /** @class */ (function () {
  10319. /**
  10320. * Constructor
  10321. * @param workers Array of workers to use for actions
  10322. */
  10323. function WorkerPool(workers) {
  10324. this._pendingActions = new Array();
  10325. this._workerInfos = workers.map(function (worker) { return ({
  10326. worker: worker,
  10327. active: false
  10328. }); });
  10329. }
  10330. /**
  10331. * Terminates all workers and clears any pending actions.
  10332. */
  10333. WorkerPool.prototype.dispose = function () {
  10334. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10335. var workerInfo = _a[_i];
  10336. workerInfo.worker.terminate();
  10337. }
  10338. delete this._workerInfos;
  10339. delete this._pendingActions;
  10340. };
  10341. /**
  10342. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10343. * pended until a worker has completed its action.
  10344. * @param action The action to perform. Call onComplete when the action is complete.
  10345. */
  10346. WorkerPool.prototype.push = function (action) {
  10347. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10348. var workerInfo = _a[_i];
  10349. if (!workerInfo.active) {
  10350. this._execute(workerInfo, action);
  10351. return;
  10352. }
  10353. }
  10354. this._pendingActions.push(action);
  10355. };
  10356. WorkerPool.prototype._execute = function (workerInfo, action) {
  10357. var _this = this;
  10358. workerInfo.active = true;
  10359. action(workerInfo.worker, function () {
  10360. workerInfo.active = false;
  10361. var nextAction = _this._pendingActions.shift();
  10362. if (nextAction) {
  10363. _this._execute(workerInfo, nextAction);
  10364. }
  10365. });
  10366. };
  10367. return WorkerPool;
  10368. }());
  10369. BABYLON.WorkerPool = WorkerPool;
  10370. })(BABYLON || (BABYLON = {}));
  10371. //# sourceMappingURL=babylon.workerPool.js.map
  10372. var BABYLON;
  10373. (function (BABYLON) {
  10374. /**
  10375. * @hidden
  10376. **/
  10377. var _AlphaState = /** @class */ (function () {
  10378. /**
  10379. * Initializes the state.
  10380. */
  10381. function _AlphaState() {
  10382. this._isAlphaBlendDirty = false;
  10383. this._isBlendFunctionParametersDirty = false;
  10384. this._isBlendEquationParametersDirty = false;
  10385. this._isBlendConstantsDirty = false;
  10386. this._alphaBlend = false;
  10387. this._blendFunctionParameters = new Array(4);
  10388. this._blendEquationParameters = new Array(2);
  10389. this._blendConstants = new Array(4);
  10390. this.reset();
  10391. }
  10392. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10393. get: function () {
  10394. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10395. },
  10396. enumerable: true,
  10397. configurable: true
  10398. });
  10399. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10400. get: function () {
  10401. return this._alphaBlend;
  10402. },
  10403. set: function (value) {
  10404. if (this._alphaBlend === value) {
  10405. return;
  10406. }
  10407. this._alphaBlend = value;
  10408. this._isAlphaBlendDirty = true;
  10409. },
  10410. enumerable: true,
  10411. configurable: true
  10412. });
  10413. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10414. if (this._blendConstants[0] === r &&
  10415. this._blendConstants[1] === g &&
  10416. this._blendConstants[2] === b &&
  10417. this._blendConstants[3] === a) {
  10418. return;
  10419. }
  10420. this._blendConstants[0] = r;
  10421. this._blendConstants[1] = g;
  10422. this._blendConstants[2] = b;
  10423. this._blendConstants[3] = a;
  10424. this._isBlendConstantsDirty = true;
  10425. };
  10426. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10427. if (this._blendFunctionParameters[0] === value0 &&
  10428. this._blendFunctionParameters[1] === value1 &&
  10429. this._blendFunctionParameters[2] === value2 &&
  10430. this._blendFunctionParameters[3] === value3) {
  10431. return;
  10432. }
  10433. this._blendFunctionParameters[0] = value0;
  10434. this._blendFunctionParameters[1] = value1;
  10435. this._blendFunctionParameters[2] = value2;
  10436. this._blendFunctionParameters[3] = value3;
  10437. this._isBlendFunctionParametersDirty = true;
  10438. };
  10439. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10440. if (this._blendEquationParameters[0] === rgb &&
  10441. this._blendEquationParameters[1] === alpha) {
  10442. return;
  10443. }
  10444. this._blendEquationParameters[0] = rgb;
  10445. this._blendEquationParameters[1] = alpha;
  10446. this._isBlendEquationParametersDirty = true;
  10447. };
  10448. _AlphaState.prototype.reset = function () {
  10449. this._alphaBlend = false;
  10450. this._blendFunctionParameters[0] = null;
  10451. this._blendFunctionParameters[1] = null;
  10452. this._blendFunctionParameters[2] = null;
  10453. this._blendFunctionParameters[3] = null;
  10454. this._blendEquationParameters[0] = null;
  10455. this._blendEquationParameters[1] = null;
  10456. this._blendConstants[0] = null;
  10457. this._blendConstants[1] = null;
  10458. this._blendConstants[2] = null;
  10459. this._blendConstants[3] = null;
  10460. this._isAlphaBlendDirty = true;
  10461. this._isBlendFunctionParametersDirty = false;
  10462. this._isBlendEquationParametersDirty = false;
  10463. this._isBlendConstantsDirty = false;
  10464. };
  10465. _AlphaState.prototype.apply = function (gl) {
  10466. if (!this.isDirty) {
  10467. return;
  10468. }
  10469. // Alpha blend
  10470. if (this._isAlphaBlendDirty) {
  10471. if (this._alphaBlend) {
  10472. gl.enable(gl.BLEND);
  10473. }
  10474. else {
  10475. gl.disable(gl.BLEND);
  10476. }
  10477. this._isAlphaBlendDirty = false;
  10478. }
  10479. // Alpha function
  10480. if (this._isBlendFunctionParametersDirty) {
  10481. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10482. this._isBlendFunctionParametersDirty = false;
  10483. }
  10484. // Alpha equation
  10485. if (this._isBlendEquationParametersDirty) {
  10486. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10487. this._isBlendEquationParametersDirty = false;
  10488. }
  10489. // Constants
  10490. if (this._isBlendConstantsDirty) {
  10491. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10492. this._isBlendConstantsDirty = false;
  10493. }
  10494. };
  10495. return _AlphaState;
  10496. }());
  10497. BABYLON._AlphaState = _AlphaState;
  10498. })(BABYLON || (BABYLON = {}));
  10499. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10500. var BABYLON;
  10501. (function (BABYLON) {
  10502. /**
  10503. * @hidden
  10504. **/
  10505. var _DepthCullingState = /** @class */ (function () {
  10506. /**
  10507. * Initializes the state.
  10508. */
  10509. function _DepthCullingState() {
  10510. this._isDepthTestDirty = false;
  10511. this._isDepthMaskDirty = false;
  10512. this._isDepthFuncDirty = false;
  10513. this._isCullFaceDirty = false;
  10514. this._isCullDirty = false;
  10515. this._isZOffsetDirty = false;
  10516. this._isFrontFaceDirty = false;
  10517. this.reset();
  10518. }
  10519. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10520. get: function () {
  10521. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10522. },
  10523. enumerable: true,
  10524. configurable: true
  10525. });
  10526. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10527. get: function () {
  10528. return this._zOffset;
  10529. },
  10530. set: function (value) {
  10531. if (this._zOffset === value) {
  10532. return;
  10533. }
  10534. this._zOffset = value;
  10535. this._isZOffsetDirty = true;
  10536. },
  10537. enumerable: true,
  10538. configurable: true
  10539. });
  10540. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10541. get: function () {
  10542. return this._cullFace;
  10543. },
  10544. set: function (value) {
  10545. if (this._cullFace === value) {
  10546. return;
  10547. }
  10548. this._cullFace = value;
  10549. this._isCullFaceDirty = true;
  10550. },
  10551. enumerable: true,
  10552. configurable: true
  10553. });
  10554. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10555. get: function () {
  10556. return this._cull;
  10557. },
  10558. set: function (value) {
  10559. if (this._cull === value) {
  10560. return;
  10561. }
  10562. this._cull = value;
  10563. this._isCullDirty = true;
  10564. },
  10565. enumerable: true,
  10566. configurable: true
  10567. });
  10568. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10569. get: function () {
  10570. return this._depthFunc;
  10571. },
  10572. set: function (value) {
  10573. if (this._depthFunc === value) {
  10574. return;
  10575. }
  10576. this._depthFunc = value;
  10577. this._isDepthFuncDirty = true;
  10578. },
  10579. enumerable: true,
  10580. configurable: true
  10581. });
  10582. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10583. get: function () {
  10584. return this._depthMask;
  10585. },
  10586. set: function (value) {
  10587. if (this._depthMask === value) {
  10588. return;
  10589. }
  10590. this._depthMask = value;
  10591. this._isDepthMaskDirty = true;
  10592. },
  10593. enumerable: true,
  10594. configurable: true
  10595. });
  10596. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10597. get: function () {
  10598. return this._depthTest;
  10599. },
  10600. set: function (value) {
  10601. if (this._depthTest === value) {
  10602. return;
  10603. }
  10604. this._depthTest = value;
  10605. this._isDepthTestDirty = true;
  10606. },
  10607. enumerable: true,
  10608. configurable: true
  10609. });
  10610. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10611. get: function () {
  10612. return this._frontFace;
  10613. },
  10614. set: function (value) {
  10615. if (this._frontFace === value) {
  10616. return;
  10617. }
  10618. this._frontFace = value;
  10619. this._isFrontFaceDirty = true;
  10620. },
  10621. enumerable: true,
  10622. configurable: true
  10623. });
  10624. _DepthCullingState.prototype.reset = function () {
  10625. this._depthMask = true;
  10626. this._depthTest = true;
  10627. this._depthFunc = null;
  10628. this._cullFace = null;
  10629. this._cull = null;
  10630. this._zOffset = 0;
  10631. this._frontFace = null;
  10632. this._isDepthTestDirty = true;
  10633. this._isDepthMaskDirty = true;
  10634. this._isDepthFuncDirty = false;
  10635. this._isCullFaceDirty = false;
  10636. this._isCullDirty = false;
  10637. this._isZOffsetDirty = false;
  10638. this._isFrontFaceDirty = false;
  10639. };
  10640. _DepthCullingState.prototype.apply = function (gl) {
  10641. if (!this.isDirty) {
  10642. return;
  10643. }
  10644. // Cull
  10645. if (this._isCullDirty) {
  10646. if (this.cull) {
  10647. gl.enable(gl.CULL_FACE);
  10648. }
  10649. else {
  10650. gl.disable(gl.CULL_FACE);
  10651. }
  10652. this._isCullDirty = false;
  10653. }
  10654. // Cull face
  10655. if (this._isCullFaceDirty) {
  10656. gl.cullFace(this.cullFace);
  10657. this._isCullFaceDirty = false;
  10658. }
  10659. // Depth mask
  10660. if (this._isDepthMaskDirty) {
  10661. gl.depthMask(this.depthMask);
  10662. this._isDepthMaskDirty = false;
  10663. }
  10664. // Depth test
  10665. if (this._isDepthTestDirty) {
  10666. if (this.depthTest) {
  10667. gl.enable(gl.DEPTH_TEST);
  10668. }
  10669. else {
  10670. gl.disable(gl.DEPTH_TEST);
  10671. }
  10672. this._isDepthTestDirty = false;
  10673. }
  10674. // Depth func
  10675. if (this._isDepthFuncDirty) {
  10676. gl.depthFunc(this.depthFunc);
  10677. this._isDepthFuncDirty = false;
  10678. }
  10679. // zOffset
  10680. if (this._isZOffsetDirty) {
  10681. if (this.zOffset) {
  10682. gl.enable(gl.POLYGON_OFFSET_FILL);
  10683. gl.polygonOffset(this.zOffset, 0);
  10684. }
  10685. else {
  10686. gl.disable(gl.POLYGON_OFFSET_FILL);
  10687. }
  10688. this._isZOffsetDirty = false;
  10689. }
  10690. // Front face
  10691. if (this._isFrontFaceDirty) {
  10692. gl.frontFace(this.frontFace);
  10693. this._isFrontFaceDirty = false;
  10694. }
  10695. };
  10696. return _DepthCullingState;
  10697. }());
  10698. BABYLON._DepthCullingState = _DepthCullingState;
  10699. })(BABYLON || (BABYLON = {}));
  10700. //# sourceMappingURL=babylon.depthCullingState.js.map
  10701. var BABYLON;
  10702. (function (BABYLON) {
  10703. /**
  10704. * @hidden
  10705. **/
  10706. var _StencilState = /** @class */ (function () {
  10707. function _StencilState() {
  10708. this._isStencilTestDirty = false;
  10709. this._isStencilMaskDirty = false;
  10710. this._isStencilFuncDirty = false;
  10711. this._isStencilOpDirty = false;
  10712. this.reset();
  10713. }
  10714. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10715. get: function () {
  10716. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10717. },
  10718. enumerable: true,
  10719. configurable: true
  10720. });
  10721. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10722. get: function () {
  10723. return this._stencilFunc;
  10724. },
  10725. set: function (value) {
  10726. if (this._stencilFunc === value) {
  10727. return;
  10728. }
  10729. this._stencilFunc = value;
  10730. this._isStencilFuncDirty = true;
  10731. },
  10732. enumerable: true,
  10733. configurable: true
  10734. });
  10735. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10736. get: function () {
  10737. return this._stencilFuncRef;
  10738. },
  10739. set: function (value) {
  10740. if (this._stencilFuncRef === value) {
  10741. return;
  10742. }
  10743. this._stencilFuncRef = value;
  10744. this._isStencilFuncDirty = true;
  10745. },
  10746. enumerable: true,
  10747. configurable: true
  10748. });
  10749. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10750. get: function () {
  10751. return this._stencilFuncMask;
  10752. },
  10753. set: function (value) {
  10754. if (this._stencilFuncMask === value) {
  10755. return;
  10756. }
  10757. this._stencilFuncMask = value;
  10758. this._isStencilFuncDirty = true;
  10759. },
  10760. enumerable: true,
  10761. configurable: true
  10762. });
  10763. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10764. get: function () {
  10765. return this._stencilOpStencilFail;
  10766. },
  10767. set: function (value) {
  10768. if (this._stencilOpStencilFail === value) {
  10769. return;
  10770. }
  10771. this._stencilOpStencilFail = value;
  10772. this._isStencilOpDirty = true;
  10773. },
  10774. enumerable: true,
  10775. configurable: true
  10776. });
  10777. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10778. get: function () {
  10779. return this._stencilOpDepthFail;
  10780. },
  10781. set: function (value) {
  10782. if (this._stencilOpDepthFail === value) {
  10783. return;
  10784. }
  10785. this._stencilOpDepthFail = value;
  10786. this._isStencilOpDirty = true;
  10787. },
  10788. enumerable: true,
  10789. configurable: true
  10790. });
  10791. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10792. get: function () {
  10793. return this._stencilOpStencilDepthPass;
  10794. },
  10795. set: function (value) {
  10796. if (this._stencilOpStencilDepthPass === value) {
  10797. return;
  10798. }
  10799. this._stencilOpStencilDepthPass = value;
  10800. this._isStencilOpDirty = true;
  10801. },
  10802. enumerable: true,
  10803. configurable: true
  10804. });
  10805. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10806. get: function () {
  10807. return this._stencilMask;
  10808. },
  10809. set: function (value) {
  10810. if (this._stencilMask === value) {
  10811. return;
  10812. }
  10813. this._stencilMask = value;
  10814. this._isStencilMaskDirty = true;
  10815. },
  10816. enumerable: true,
  10817. configurable: true
  10818. });
  10819. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10820. get: function () {
  10821. return this._stencilTest;
  10822. },
  10823. set: function (value) {
  10824. if (this._stencilTest === value) {
  10825. return;
  10826. }
  10827. this._stencilTest = value;
  10828. this._isStencilTestDirty = true;
  10829. },
  10830. enumerable: true,
  10831. configurable: true
  10832. });
  10833. _StencilState.prototype.reset = function () {
  10834. this._stencilTest = false;
  10835. this._stencilMask = 0xFF;
  10836. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10837. this._stencilFuncRef = 1;
  10838. this._stencilFuncMask = 0xFF;
  10839. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10840. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10841. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10842. this._isStencilTestDirty = true;
  10843. this._isStencilMaskDirty = true;
  10844. this._isStencilFuncDirty = true;
  10845. this._isStencilOpDirty = true;
  10846. };
  10847. _StencilState.prototype.apply = function (gl) {
  10848. if (!this.isDirty) {
  10849. return;
  10850. }
  10851. // Stencil test
  10852. if (this._isStencilTestDirty) {
  10853. if (this.stencilTest) {
  10854. gl.enable(gl.STENCIL_TEST);
  10855. }
  10856. else {
  10857. gl.disable(gl.STENCIL_TEST);
  10858. }
  10859. this._isStencilTestDirty = false;
  10860. }
  10861. // Stencil mask
  10862. if (this._isStencilMaskDirty) {
  10863. gl.stencilMask(this.stencilMask);
  10864. this._isStencilMaskDirty = false;
  10865. }
  10866. // Stencil func
  10867. if (this._isStencilFuncDirty) {
  10868. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10869. this._isStencilFuncDirty = false;
  10870. }
  10871. // Stencil op
  10872. if (this._isStencilOpDirty) {
  10873. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10874. this._isStencilOpDirty = false;
  10875. }
  10876. };
  10877. return _StencilState;
  10878. }());
  10879. BABYLON._StencilState = _StencilState;
  10880. })(BABYLON || (BABYLON = {}));
  10881. //# sourceMappingURL=babylon.stencilState.js.map
  10882. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10883. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10884. s = arguments[i];
  10885. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10886. t[p] = s[p];
  10887. }
  10888. return t;
  10889. };
  10890. var BABYLON;
  10891. (function (BABYLON) {
  10892. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10893. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10894. };
  10895. var compileRawShader = function (gl, source, type) {
  10896. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10897. gl.shaderSource(shader, source);
  10898. gl.compileShader(shader);
  10899. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10900. var log = gl.getShaderInfoLog(shader);
  10901. if (log) {
  10902. throw new Error(log);
  10903. }
  10904. }
  10905. if (!shader) {
  10906. throw new Error("Something went wrong while compile the shader.");
  10907. }
  10908. return shader;
  10909. };
  10910. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10911. var magFilter = gl.NEAREST;
  10912. var minFilter = gl.NEAREST;
  10913. switch (samplingMode) {
  10914. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10915. magFilter = gl.LINEAR;
  10916. if (generateMipMaps) {
  10917. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10918. }
  10919. else {
  10920. minFilter = gl.LINEAR;
  10921. }
  10922. break;
  10923. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10924. magFilter = gl.LINEAR;
  10925. if (generateMipMaps) {
  10926. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10927. }
  10928. else {
  10929. minFilter = gl.LINEAR;
  10930. }
  10931. break;
  10932. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10933. magFilter = gl.NEAREST;
  10934. if (generateMipMaps) {
  10935. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10936. }
  10937. else {
  10938. minFilter = gl.NEAREST;
  10939. }
  10940. break;
  10941. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10942. magFilter = gl.NEAREST;
  10943. if (generateMipMaps) {
  10944. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10945. }
  10946. else {
  10947. minFilter = gl.NEAREST;
  10948. }
  10949. break;
  10950. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10951. magFilter = gl.NEAREST;
  10952. if (generateMipMaps) {
  10953. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10954. }
  10955. else {
  10956. minFilter = gl.LINEAR;
  10957. }
  10958. break;
  10959. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10960. magFilter = gl.NEAREST;
  10961. if (generateMipMaps) {
  10962. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10963. }
  10964. else {
  10965. minFilter = gl.LINEAR;
  10966. }
  10967. break;
  10968. case BABYLON.Texture.NEAREST_LINEAR:
  10969. magFilter = gl.NEAREST;
  10970. minFilter = gl.LINEAR;
  10971. break;
  10972. case BABYLON.Texture.NEAREST_NEAREST:
  10973. magFilter = gl.NEAREST;
  10974. minFilter = gl.NEAREST;
  10975. break;
  10976. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10977. magFilter = gl.LINEAR;
  10978. if (generateMipMaps) {
  10979. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10980. }
  10981. else {
  10982. minFilter = gl.NEAREST;
  10983. }
  10984. break;
  10985. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10986. magFilter = gl.LINEAR;
  10987. if (generateMipMaps) {
  10988. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10989. }
  10990. else {
  10991. minFilter = gl.NEAREST;
  10992. }
  10993. break;
  10994. case BABYLON.Texture.LINEAR_LINEAR:
  10995. magFilter = gl.LINEAR;
  10996. minFilter = gl.LINEAR;
  10997. break;
  10998. case BABYLON.Texture.LINEAR_NEAREST:
  10999. magFilter = gl.LINEAR;
  11000. minFilter = gl.NEAREST;
  11001. break;
  11002. }
  11003. return {
  11004. min: minFilter,
  11005. mag: magFilter
  11006. };
  11007. };
  11008. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11009. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11010. var img;
  11011. var onload = function () {
  11012. loadedImages[index] = img;
  11013. loadedImages._internalCount++;
  11014. if (scene) {
  11015. scene._removePendingData(img);
  11016. }
  11017. if (loadedImages._internalCount === 6) {
  11018. onfinish(loadedImages);
  11019. }
  11020. };
  11021. var onerror = function (message, exception) {
  11022. if (scene) {
  11023. scene._removePendingData(img);
  11024. }
  11025. if (onErrorCallBack) {
  11026. onErrorCallBack(message, exception);
  11027. }
  11028. };
  11029. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11030. if (scene) {
  11031. scene._addPendingData(img);
  11032. }
  11033. };
  11034. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11035. if (onError === void 0) { onError = null; }
  11036. var loadedImages = [];
  11037. loadedImages._internalCount = 0;
  11038. for (var index = 0; index < 6; index++) {
  11039. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11040. }
  11041. };
  11042. var BufferPointer = /** @class */ (function () {
  11043. function BufferPointer() {
  11044. }
  11045. return BufferPointer;
  11046. }());
  11047. /**
  11048. * Interface for attribute information associated with buffer instanciation
  11049. */
  11050. var InstancingAttributeInfo = /** @class */ (function () {
  11051. function InstancingAttributeInfo() {
  11052. }
  11053. return InstancingAttributeInfo;
  11054. }());
  11055. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11056. /**
  11057. * Define options used to create a render target texture
  11058. */
  11059. var RenderTargetCreationOptions = /** @class */ (function () {
  11060. function RenderTargetCreationOptions() {
  11061. }
  11062. return RenderTargetCreationOptions;
  11063. }());
  11064. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11065. /**
  11066. * Define options used to create a depth texture
  11067. */
  11068. var DepthTextureCreationOptions = /** @class */ (function () {
  11069. function DepthTextureCreationOptions() {
  11070. }
  11071. return DepthTextureCreationOptions;
  11072. }());
  11073. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11074. /**
  11075. * Class used to describe the capabilities of the engine relatively to the current browser
  11076. */
  11077. var EngineCapabilities = /** @class */ (function () {
  11078. function EngineCapabilities() {
  11079. }
  11080. return EngineCapabilities;
  11081. }());
  11082. BABYLON.EngineCapabilities = EngineCapabilities;
  11083. /**
  11084. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11085. */
  11086. var Engine = /** @class */ (function () {
  11087. /**
  11088. * Creates a new engine
  11089. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11090. * @param antialias defines enable antialiasing (default: false)
  11091. * @param options defines further options to be sent to the getContext() function
  11092. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11093. */
  11094. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11095. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11096. var _this = this;
  11097. // Public members
  11098. /**
  11099. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11100. */
  11101. this.forcePOTTextures = false;
  11102. /**
  11103. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11104. */
  11105. this.isFullscreen = false;
  11106. /**
  11107. * Gets a boolean indicating if the pointer is currently locked
  11108. */
  11109. this.isPointerLock = false;
  11110. /**
  11111. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11112. */
  11113. this.cullBackFaces = true;
  11114. /**
  11115. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11116. */
  11117. this.renderEvenInBackground = true;
  11118. /**
  11119. * Gets or sets a boolean indicating that cache can be kept between frames
  11120. */
  11121. this.preventCacheWipeBetweenFrames = false;
  11122. /**
  11123. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11124. **/
  11125. this.enableOfflineSupport = false;
  11126. /**
  11127. * 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)
  11128. **/
  11129. this.disableManifestCheck = false;
  11130. /**
  11131. * Gets the list of created scenes
  11132. */
  11133. this.scenes = new Array();
  11134. /**
  11135. * Gets the list of created postprocesses
  11136. */
  11137. this.postProcesses = new Array();
  11138. // Observables
  11139. /**
  11140. * Observable event triggered each time the rendering canvas is resized
  11141. */
  11142. this.onResizeObservable = new BABYLON.Observable();
  11143. /**
  11144. * Observable event triggered each time the canvas loses focus
  11145. */
  11146. this.onCanvasBlurObservable = new BABYLON.Observable();
  11147. /**
  11148. * Observable event triggered each time the canvas gains focus
  11149. */
  11150. this.onCanvasFocusObservable = new BABYLON.Observable();
  11151. /**
  11152. * Observable event triggered each time the canvas receives pointerout event
  11153. */
  11154. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11155. /**
  11156. * Observable event triggered before each texture is initialized
  11157. */
  11158. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11159. //WebVR
  11160. this._vrDisplay = undefined;
  11161. this._vrSupported = false;
  11162. this._vrExclusivePointerMode = false;
  11163. // Uniform buffers list
  11164. /**
  11165. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11166. */
  11167. this.disableUniformBuffers = false;
  11168. /** @hidden */
  11169. this._uniformBuffers = new Array();
  11170. // Observables
  11171. /**
  11172. * Observable raised when the engine begins a new frame
  11173. */
  11174. this.onBeginFrameObservable = new BABYLON.Observable();
  11175. /**
  11176. * Observable raised when the engine ends the current frame
  11177. */
  11178. this.onEndFrameObservable = new BABYLON.Observable();
  11179. /**
  11180. * Observable raised when the engine is about to compile a shader
  11181. */
  11182. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11183. /**
  11184. * Observable raised when the engine has jsut compiled a shader
  11185. */
  11186. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11187. this._windowIsBackground = false;
  11188. this._webGLVersion = 1.0;
  11189. /** @hidden */
  11190. this._badOS = false;
  11191. /** @hidden */
  11192. this._badDesktopOS = false;
  11193. /**
  11194. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11195. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11196. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11197. */
  11198. this.disableTextureBindingOptimization = false;
  11199. /**
  11200. * Observable signaled when VR display mode changes
  11201. */
  11202. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11203. /**
  11204. * Observable signaled when VR request present is complete
  11205. */
  11206. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11207. /**
  11208. * Observable signaled when VR request present starts
  11209. */
  11210. this.onVRRequestPresentStart = new BABYLON.Observable();
  11211. this._colorWrite = true;
  11212. /** @hidden */
  11213. this._drawCalls = new BABYLON.PerfCounter();
  11214. /** @hidden */
  11215. this._textureCollisions = new BABYLON.PerfCounter();
  11216. this._renderingQueueLaunched = false;
  11217. this._activeRenderLoops = new Array();
  11218. // Deterministic lockstepMaxSteps
  11219. this._deterministicLockstep = false;
  11220. this._lockstepMaxSteps = 4;
  11221. // Lost context
  11222. /**
  11223. * Observable signaled when a context lost event is raised
  11224. */
  11225. this.onContextLostObservable = new BABYLON.Observable();
  11226. /**
  11227. * Observable signaled when a context restored event is raised
  11228. */
  11229. this.onContextRestoredObservable = new BABYLON.Observable();
  11230. this._contextWasLost = false;
  11231. this._doNotHandleContextLost = false;
  11232. // FPS
  11233. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11234. this._fps = 60;
  11235. this._deltaTime = 0;
  11236. /**
  11237. * Turn this value on if you want to pause FPS computation when in background
  11238. */
  11239. this.disablePerformanceMonitorInBackground = false;
  11240. // States
  11241. /** @hidden */
  11242. this._depthCullingState = new BABYLON._DepthCullingState();
  11243. /** @hidden */
  11244. this._stencilState = new BABYLON._StencilState();
  11245. /** @hidden */
  11246. this._alphaState = new BABYLON._AlphaState();
  11247. /** @hidden */
  11248. this._alphaMode = Engine.ALPHA_DISABLE;
  11249. // Cache
  11250. this._internalTexturesCache = new Array();
  11251. /** @hidden */
  11252. this._activeChannel = 0;
  11253. this._currentTextureChannel = -1;
  11254. /** @hidden */
  11255. this._boundTexturesCache = {};
  11256. this._compiledEffects = {};
  11257. this._vertexAttribArraysEnabled = [];
  11258. this._uintIndicesCurrentlySet = false;
  11259. this._currentBoundBuffer = new Array();
  11260. this._currentBufferPointers = new Array();
  11261. this._currentInstanceLocations = new Array();
  11262. this._currentInstanceBuffers = new Array();
  11263. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11264. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11265. this._vaoRecordInProgress = false;
  11266. this._mustWipeVertexAttributes = false;
  11267. this._nextFreeTextureSlots = new Array();
  11268. this._maxSimultaneousTextures = 0;
  11269. this._activeRequests = new Array();
  11270. // Hardware supported Compressed Textures
  11271. this._texturesSupported = new Array();
  11272. this._onVRFullScreenTriggered = function () {
  11273. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11274. //get the old size before we change
  11275. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11276. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11277. //get the width and height, change the render size
  11278. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11279. _this.setHardwareScalingLevel(1);
  11280. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11281. }
  11282. else {
  11283. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11284. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11285. }
  11286. };
  11287. this._boundUniforms = {};
  11288. // Register promises
  11289. BABYLON.PromisePolyfill.Apply();
  11290. var canvas = null;
  11291. Engine.Instances.push(this);
  11292. if (!canvasOrContext) {
  11293. return;
  11294. }
  11295. options = options || {};
  11296. if (canvasOrContext.getContext) {
  11297. canvas = canvasOrContext;
  11298. this._renderingCanvas = canvas;
  11299. if (antialias != null) {
  11300. options.antialias = antialias;
  11301. }
  11302. if (options.deterministicLockstep === undefined) {
  11303. options.deterministicLockstep = false;
  11304. }
  11305. if (options.lockstepMaxSteps === undefined) {
  11306. options.lockstepMaxSteps = 4;
  11307. }
  11308. if (options.preserveDrawingBuffer === undefined) {
  11309. options.preserveDrawingBuffer = false;
  11310. }
  11311. if (options.audioEngine === undefined) {
  11312. options.audioEngine = true;
  11313. }
  11314. if (options.stencil === undefined) {
  11315. options.stencil = true;
  11316. }
  11317. this._deterministicLockstep = options.deterministicLockstep;
  11318. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11319. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11320. // Exceptions
  11321. if (navigator && navigator.userAgent) {
  11322. var ua = navigator.userAgent;
  11323. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11324. var exception = _a[_i];
  11325. var key = exception.key;
  11326. var targets = exception.targets;
  11327. if (ua.indexOf(key) > -1) {
  11328. if (exception.capture && exception.captureConstraint) {
  11329. var capture = exception.capture;
  11330. var constraint = exception.captureConstraint;
  11331. var regex = new RegExp(capture);
  11332. var matches = regex.exec(ua);
  11333. if (matches && matches.length > 0) {
  11334. var capturedValue = parseInt(matches[matches.length - 1]);
  11335. if (capturedValue >= constraint) {
  11336. continue;
  11337. }
  11338. }
  11339. }
  11340. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11341. var target = targets_1[_b];
  11342. switch (target) {
  11343. case "uniformBuffer":
  11344. this.disableUniformBuffers = true;
  11345. break;
  11346. case "textureBindingOptimization":
  11347. this.disableTextureBindingOptimization = true;
  11348. break;
  11349. }
  11350. }
  11351. }
  11352. }
  11353. }
  11354. // GL
  11355. if (!options.disableWebGL2Support) {
  11356. try {
  11357. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11358. if (this._gl) {
  11359. this._webGLVersion = 2.0;
  11360. }
  11361. }
  11362. catch (e) {
  11363. // Do nothing
  11364. }
  11365. }
  11366. if (!this._gl) {
  11367. if (!canvas) {
  11368. throw new Error("The provided canvas is null or undefined.");
  11369. }
  11370. try {
  11371. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11372. }
  11373. catch (e) {
  11374. throw new Error("WebGL not supported");
  11375. }
  11376. }
  11377. if (!this._gl) {
  11378. throw new Error("WebGL not supported");
  11379. }
  11380. this._onCanvasFocus = function () {
  11381. _this.onCanvasFocusObservable.notifyObservers(_this);
  11382. };
  11383. this._onCanvasBlur = function () {
  11384. _this.onCanvasBlurObservable.notifyObservers(_this);
  11385. };
  11386. canvas.addEventListener("focus", this._onCanvasFocus);
  11387. canvas.addEventListener("blur", this._onCanvasBlur);
  11388. this._onBlur = function () {
  11389. if (_this.disablePerformanceMonitorInBackground) {
  11390. _this._performanceMonitor.disable();
  11391. }
  11392. _this._windowIsBackground = true;
  11393. };
  11394. this._onFocus = function () {
  11395. if (_this.disablePerformanceMonitorInBackground) {
  11396. _this._performanceMonitor.enable();
  11397. }
  11398. _this._windowIsBackground = false;
  11399. };
  11400. this._onCanvasPointerOut = function (ev) {
  11401. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11402. };
  11403. window.addEventListener("blur", this._onBlur);
  11404. window.addEventListener("focus", this._onFocus);
  11405. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11406. // Context lost
  11407. if (!this._doNotHandleContextLost) {
  11408. this._onContextLost = function (evt) {
  11409. evt.preventDefault();
  11410. _this._contextWasLost = true;
  11411. BABYLON.Tools.Warn("WebGL context lost.");
  11412. _this.onContextLostObservable.notifyObservers(_this);
  11413. };
  11414. this._onContextRestored = function (evt) {
  11415. // Adding a timeout to avoid race condition at browser level
  11416. setTimeout(function () {
  11417. // Rebuild gl context
  11418. _this._initGLContext();
  11419. // Rebuild effects
  11420. _this._rebuildEffects();
  11421. // Rebuild textures
  11422. _this._rebuildInternalTextures();
  11423. // Rebuild buffers
  11424. _this._rebuildBuffers();
  11425. // Cache
  11426. _this.wipeCaches(true);
  11427. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11428. _this.onContextRestoredObservable.notifyObservers(_this);
  11429. _this._contextWasLost = false;
  11430. }, 0);
  11431. };
  11432. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11433. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11434. }
  11435. }
  11436. else {
  11437. this._gl = canvasOrContext;
  11438. this._renderingCanvas = this._gl.canvas;
  11439. if (this._gl.renderbufferStorageMultisample) {
  11440. this._webGLVersion = 2.0;
  11441. }
  11442. options.stencil = this._gl.getContextAttributes().stencil;
  11443. }
  11444. // Viewport
  11445. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11446. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11447. this.resize();
  11448. this._isStencilEnable = options.stencil ? true : false;
  11449. this._initGLContext();
  11450. if (canvas) {
  11451. // Fullscreen
  11452. this._onFullscreenChange = function () {
  11453. if (document.fullscreen !== undefined) {
  11454. _this.isFullscreen = document.fullscreen;
  11455. }
  11456. else if (document.mozFullScreen !== undefined) {
  11457. _this.isFullscreen = document.mozFullScreen;
  11458. }
  11459. else if (document.webkitIsFullScreen !== undefined) {
  11460. _this.isFullscreen = document.webkitIsFullScreen;
  11461. }
  11462. else if (document.msIsFullScreen !== undefined) {
  11463. _this.isFullscreen = document.msIsFullScreen;
  11464. }
  11465. // Pointer lock
  11466. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11467. canvas.requestPointerLock = canvas.requestPointerLock ||
  11468. canvas.msRequestPointerLock ||
  11469. canvas.mozRequestPointerLock ||
  11470. canvas.webkitRequestPointerLock;
  11471. if (canvas.requestPointerLock) {
  11472. canvas.requestPointerLock();
  11473. }
  11474. }
  11475. };
  11476. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11477. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11478. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11479. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11480. // Pointer lock
  11481. this._onPointerLockChange = function () {
  11482. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11483. document.webkitPointerLockElement === canvas ||
  11484. document.msPointerLockElement === canvas ||
  11485. document.pointerLockElement === canvas);
  11486. };
  11487. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11488. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11489. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11490. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11491. this._onVRDisplayPointerRestricted = function () {
  11492. if (canvas) {
  11493. canvas.requestPointerLock();
  11494. }
  11495. };
  11496. this._onVRDisplayPointerUnrestricted = function () {
  11497. document.exitPointerLock();
  11498. };
  11499. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11500. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11501. }
  11502. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11503. Engine.audioEngine = new BABYLON.AudioEngine();
  11504. }
  11505. // Prepare buffer pointers
  11506. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11507. this._currentBufferPointers[i] = new BufferPointer();
  11508. }
  11509. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11510. // Load WebVR Devices
  11511. if (options.autoEnableWebVR) {
  11512. this.initWebVR();
  11513. }
  11514. // Detect if we are running on a faulty buggy OS.
  11515. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11516. // Detect if we are running on a faulty buggy desktop OS.
  11517. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11518. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11519. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11520. }
  11521. Object.defineProperty(Engine, "LastCreatedEngine", {
  11522. /**
  11523. * Gets the latest created engine
  11524. */
  11525. get: function () {
  11526. if (Engine.Instances.length === 0) {
  11527. return null;
  11528. }
  11529. return Engine.Instances[Engine.Instances.length - 1];
  11530. },
  11531. enumerable: true,
  11532. configurable: true
  11533. });
  11534. Object.defineProperty(Engine, "LastCreatedScene", {
  11535. /**
  11536. * Gets the latest created scene
  11537. */
  11538. get: function () {
  11539. var lastCreatedEngine = Engine.LastCreatedEngine;
  11540. if (!lastCreatedEngine) {
  11541. return null;
  11542. }
  11543. if (lastCreatedEngine.scenes.length === 0) {
  11544. return null;
  11545. }
  11546. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11547. },
  11548. enumerable: true,
  11549. configurable: true
  11550. });
  11551. /**
  11552. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11553. * @param flag defines which part of the materials must be marked as dirty
  11554. * @param predicate defines a predicate used to filter which materials should be affected
  11555. */
  11556. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11557. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11558. var engine = Engine.Instances[engineIndex];
  11559. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11560. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11561. }
  11562. }
  11563. };
  11564. Object.defineProperty(Engine, "NEVER", {
  11565. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11566. get: function () {
  11567. return Engine._NEVER;
  11568. },
  11569. enumerable: true,
  11570. configurable: true
  11571. });
  11572. Object.defineProperty(Engine, "ALWAYS", {
  11573. /** 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 */
  11574. get: function () {
  11575. return Engine._ALWAYS;
  11576. },
  11577. enumerable: true,
  11578. configurable: true
  11579. });
  11580. Object.defineProperty(Engine, "LESS", {
  11581. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11582. get: function () {
  11583. return Engine._LESS;
  11584. },
  11585. enumerable: true,
  11586. configurable: true
  11587. });
  11588. Object.defineProperty(Engine, "EQUAL", {
  11589. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11590. get: function () {
  11591. return Engine._EQUAL;
  11592. },
  11593. enumerable: true,
  11594. configurable: true
  11595. });
  11596. Object.defineProperty(Engine, "LEQUAL", {
  11597. /** 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 */
  11598. get: function () {
  11599. return Engine._LEQUAL;
  11600. },
  11601. enumerable: true,
  11602. configurable: true
  11603. });
  11604. Object.defineProperty(Engine, "GREATER", {
  11605. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11606. get: function () {
  11607. return Engine._GREATER;
  11608. },
  11609. enumerable: true,
  11610. configurable: true
  11611. });
  11612. Object.defineProperty(Engine, "GEQUAL", {
  11613. /** 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 */
  11614. get: function () {
  11615. return Engine._GEQUAL;
  11616. },
  11617. enumerable: true,
  11618. configurable: true
  11619. });
  11620. Object.defineProperty(Engine, "NOTEQUAL", {
  11621. /** 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 */
  11622. get: function () {
  11623. return Engine._NOTEQUAL;
  11624. },
  11625. enumerable: true,
  11626. configurable: true
  11627. });
  11628. Object.defineProperty(Engine, "KEEP", {
  11629. /** Passed to stencilOperation to specify that stencil value must be kept */
  11630. get: function () {
  11631. return Engine._KEEP;
  11632. },
  11633. enumerable: true,
  11634. configurable: true
  11635. });
  11636. Object.defineProperty(Engine, "REPLACE", {
  11637. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11638. get: function () {
  11639. return Engine._REPLACE;
  11640. },
  11641. enumerable: true,
  11642. configurable: true
  11643. });
  11644. Object.defineProperty(Engine, "INCR", {
  11645. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11646. get: function () {
  11647. return Engine._INCR;
  11648. },
  11649. enumerable: true,
  11650. configurable: true
  11651. });
  11652. Object.defineProperty(Engine, "DECR", {
  11653. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11654. get: function () {
  11655. return Engine._DECR;
  11656. },
  11657. enumerable: true,
  11658. configurable: true
  11659. });
  11660. Object.defineProperty(Engine, "INVERT", {
  11661. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11662. get: function () {
  11663. return Engine._INVERT;
  11664. },
  11665. enumerable: true,
  11666. configurable: true
  11667. });
  11668. Object.defineProperty(Engine, "INCR_WRAP", {
  11669. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11670. get: function () {
  11671. return Engine._INCR_WRAP;
  11672. },
  11673. enumerable: true,
  11674. configurable: true
  11675. });
  11676. Object.defineProperty(Engine, "DECR_WRAP", {
  11677. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11678. get: function () {
  11679. return Engine._DECR_WRAP;
  11680. },
  11681. enumerable: true,
  11682. configurable: true
  11683. });
  11684. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11685. // Alpha
  11686. /** Defines that alpha blending is disabled */
  11687. get: function () {
  11688. return Engine._ALPHA_DISABLE;
  11689. },
  11690. enumerable: true,
  11691. configurable: true
  11692. });
  11693. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11694. /** Defines that alpha blending to SRC + DEST */
  11695. get: function () {
  11696. return Engine._ALPHA_ONEONE;
  11697. },
  11698. enumerable: true,
  11699. configurable: true
  11700. });
  11701. Object.defineProperty(Engine, "ALPHA_ADD", {
  11702. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11703. get: function () {
  11704. return Engine._ALPHA_ADD;
  11705. },
  11706. enumerable: true,
  11707. configurable: true
  11708. });
  11709. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11710. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11711. get: function () {
  11712. return Engine._ALPHA_COMBINE;
  11713. },
  11714. enumerable: true,
  11715. configurable: true
  11716. });
  11717. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11718. /** Defines that alpha blending to DEST - SRC * DEST */
  11719. get: function () {
  11720. return Engine._ALPHA_SUBTRACT;
  11721. },
  11722. enumerable: true,
  11723. configurable: true
  11724. });
  11725. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11726. /** Defines that alpha blending to SRC * DEST */
  11727. get: function () {
  11728. return Engine._ALPHA_MULTIPLY;
  11729. },
  11730. enumerable: true,
  11731. configurable: true
  11732. });
  11733. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11734. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11735. get: function () {
  11736. return Engine._ALPHA_MAXIMIZED;
  11737. },
  11738. enumerable: true,
  11739. configurable: true
  11740. });
  11741. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11742. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11743. get: function () {
  11744. return Engine._ALPHA_PREMULTIPLIED;
  11745. },
  11746. enumerable: true,
  11747. configurable: true
  11748. });
  11749. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11750. /**
  11751. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11752. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11753. */
  11754. get: function () {
  11755. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11756. },
  11757. enumerable: true,
  11758. configurable: true
  11759. });
  11760. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11761. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11762. get: function () {
  11763. return Engine._ALPHA_INTERPOLATE;
  11764. },
  11765. enumerable: true,
  11766. configurable: true
  11767. });
  11768. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11769. /**
  11770. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11771. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11772. */
  11773. get: function () {
  11774. return Engine._ALPHA_SCREENMODE;
  11775. },
  11776. enumerable: true,
  11777. configurable: true
  11778. });
  11779. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11780. // Delays
  11781. /** Defines that the ressource is not delayed*/
  11782. get: function () {
  11783. return Engine._DELAYLOADSTATE_NONE;
  11784. },
  11785. enumerable: true,
  11786. configurable: true
  11787. });
  11788. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11789. /** Defines that the ressource was successfully delay loaded */
  11790. get: function () {
  11791. return Engine._DELAYLOADSTATE_LOADED;
  11792. },
  11793. enumerable: true,
  11794. configurable: true
  11795. });
  11796. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11797. /** Defines that the ressource is currently delay loading */
  11798. get: function () {
  11799. return Engine._DELAYLOADSTATE_LOADING;
  11800. },
  11801. enumerable: true,
  11802. configurable: true
  11803. });
  11804. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11805. /** Defines that the ressource is delayed and has not started loading */
  11806. get: function () {
  11807. return Engine._DELAYLOADSTATE_NOTLOADED;
  11808. },
  11809. enumerable: true,
  11810. configurable: true
  11811. });
  11812. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11813. /** ALPHA */
  11814. get: function () {
  11815. return Engine._TEXTUREFORMAT_ALPHA;
  11816. },
  11817. enumerable: true,
  11818. configurable: true
  11819. });
  11820. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11821. /** LUMINANCE */
  11822. get: function () {
  11823. return Engine._TEXTUREFORMAT_LUMINANCE;
  11824. },
  11825. enumerable: true,
  11826. configurable: true
  11827. });
  11828. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11829. /**
  11830. * R32F
  11831. */
  11832. get: function () {
  11833. return Engine._TEXTUREFORMAT_R32F;
  11834. },
  11835. enumerable: true,
  11836. configurable: true
  11837. });
  11838. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11839. /**
  11840. * RG32F
  11841. */
  11842. get: function () {
  11843. return Engine._TEXTUREFORMAT_RG32F;
  11844. },
  11845. enumerable: true,
  11846. configurable: true
  11847. });
  11848. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11849. /**
  11850. * RGB32F
  11851. */
  11852. get: function () {
  11853. return Engine._TEXTUREFORMAT_RGB32F;
  11854. },
  11855. enumerable: true,
  11856. configurable: true
  11857. });
  11858. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11859. /**
  11860. * RGBA32F
  11861. */
  11862. get: function () {
  11863. return Engine._TEXTUREFORMAT_RGBA32F;
  11864. },
  11865. enumerable: true,
  11866. configurable: true
  11867. });
  11868. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11869. /** LUMINANCE_ALPHA */
  11870. get: function () {
  11871. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11872. },
  11873. enumerable: true,
  11874. configurable: true
  11875. });
  11876. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11877. /** RGB */
  11878. get: function () {
  11879. return Engine._TEXTUREFORMAT_RGB;
  11880. },
  11881. enumerable: true,
  11882. configurable: true
  11883. });
  11884. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11885. /** RGBA */
  11886. get: function () {
  11887. return Engine._TEXTUREFORMAT_RGBA;
  11888. },
  11889. enumerable: true,
  11890. configurable: true
  11891. });
  11892. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11893. /** UNSIGNED_INT */
  11894. get: function () {
  11895. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11896. },
  11897. enumerable: true,
  11898. configurable: true
  11899. });
  11900. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11901. /** FLOAT */
  11902. get: function () {
  11903. return Engine._TEXTURETYPE_FLOAT;
  11904. },
  11905. enumerable: true,
  11906. configurable: true
  11907. });
  11908. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11909. /** HALF_FLOAT */
  11910. get: function () {
  11911. return Engine._TEXTURETYPE_HALF_FLOAT;
  11912. },
  11913. enumerable: true,
  11914. configurable: true
  11915. });
  11916. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11917. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11918. get: function () {
  11919. return Engine._SCALEMODE_FLOOR;
  11920. },
  11921. enumerable: true,
  11922. configurable: true
  11923. });
  11924. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11925. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11926. get: function () {
  11927. return Engine._SCALEMODE_NEAREST;
  11928. },
  11929. enumerable: true,
  11930. configurable: true
  11931. });
  11932. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11933. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11934. get: function () {
  11935. return Engine._SCALEMODE_CEILING;
  11936. },
  11937. enumerable: true,
  11938. configurable: true
  11939. });
  11940. Object.defineProperty(Engine, "Version", {
  11941. /**
  11942. * Returns the current version of the framework
  11943. */
  11944. get: function () {
  11945. return "3.2.0-rc.2";
  11946. },
  11947. enumerable: true,
  11948. configurable: true
  11949. });
  11950. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11951. /**
  11952. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11953. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11954. */
  11955. get: function () {
  11956. return this._vrExclusivePointerMode;
  11957. },
  11958. enumerable: true,
  11959. configurable: true
  11960. });
  11961. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11962. /**
  11963. * Gets a boolean indicating that the engine supports uniform buffers
  11964. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11965. */
  11966. get: function () {
  11967. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11968. },
  11969. enumerable: true,
  11970. configurable: true
  11971. });
  11972. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11973. /**
  11974. * Gets a boolean indicating that only power of 2 textures are supported
  11975. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11976. */
  11977. get: function () {
  11978. return this._webGLVersion < 2 || this.forcePOTTextures;
  11979. },
  11980. enumerable: true,
  11981. configurable: true
  11982. });
  11983. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11984. /**
  11985. * Gets the performance monitor attached to this engine
  11986. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  11987. */
  11988. get: function () {
  11989. return this._performanceMonitor;
  11990. },
  11991. enumerable: true,
  11992. configurable: true
  11993. });
  11994. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11995. /**
  11996. * Gets the list of texture formats supported
  11997. */
  11998. get: function () {
  11999. return this._texturesSupported;
  12000. },
  12001. enumerable: true,
  12002. configurable: true
  12003. });
  12004. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12005. /**
  12006. * Gets the list of texture formats in use
  12007. */
  12008. get: function () {
  12009. return this._textureFormatInUse;
  12010. },
  12011. enumerable: true,
  12012. configurable: true
  12013. });
  12014. Object.defineProperty(Engine.prototype, "currentViewport", {
  12015. /**
  12016. * Gets the current viewport
  12017. */
  12018. get: function () {
  12019. return this._cachedViewport;
  12020. },
  12021. enumerable: true,
  12022. configurable: true
  12023. });
  12024. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12025. /**
  12026. * Gets the default empty texture
  12027. */
  12028. get: function () {
  12029. if (!this._emptyTexture) {
  12030. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12031. }
  12032. return this._emptyTexture;
  12033. },
  12034. enumerable: true,
  12035. configurable: true
  12036. });
  12037. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12038. /**
  12039. * Gets the default empty 3D texture
  12040. */
  12041. get: function () {
  12042. if (!this._emptyTexture3D) {
  12043. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12044. }
  12045. return this._emptyTexture3D;
  12046. },
  12047. enumerable: true,
  12048. configurable: true
  12049. });
  12050. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12051. /**
  12052. * Gets the default empty cube texture
  12053. */
  12054. get: function () {
  12055. if (!this._emptyCubeTexture) {
  12056. var faceData = new Uint8Array(4);
  12057. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12058. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12059. }
  12060. return this._emptyCubeTexture;
  12061. },
  12062. enumerable: true,
  12063. configurable: true
  12064. });
  12065. Engine.prototype._rebuildInternalTextures = function () {
  12066. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12067. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12068. var internalTexture = currentState_1[_i];
  12069. internalTexture._rebuild();
  12070. }
  12071. };
  12072. Engine.prototype._rebuildEffects = function () {
  12073. for (var key in this._compiledEffects) {
  12074. var effect = this._compiledEffects[key];
  12075. effect._prepareEffect();
  12076. }
  12077. BABYLON.Effect.ResetCache();
  12078. };
  12079. Engine.prototype._rebuildBuffers = function () {
  12080. // Index / Vertex
  12081. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12082. var scene = _a[_i];
  12083. scene.resetCachedMaterial();
  12084. scene._rebuildGeometries();
  12085. scene._rebuildTextures();
  12086. }
  12087. // Uniforms
  12088. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12089. var uniformBuffer = _c[_b];
  12090. uniformBuffer._rebuild();
  12091. }
  12092. };
  12093. Engine.prototype._initGLContext = function () {
  12094. // Caps
  12095. this._caps = new EngineCapabilities();
  12096. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12097. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12098. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12099. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12100. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12101. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12102. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12103. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12104. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12105. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12106. // Infos
  12107. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12108. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12109. if (rendererInfo != null) {
  12110. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12111. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12112. }
  12113. if (!this._glVendor) {
  12114. this._glVendor = "Unknown vendor";
  12115. }
  12116. if (!this._glRenderer) {
  12117. this._glRenderer = "Unknown renderer";
  12118. }
  12119. // Constants
  12120. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12121. if (this._gl.RGBA16F !== 0x881A) {
  12122. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12123. }
  12124. if (this._gl.RGBA32F !== 0x8814) {
  12125. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12126. }
  12127. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12128. this._gl.DEPTH24_STENCIL8 = 35056;
  12129. }
  12130. // Extensions
  12131. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12132. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12133. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12134. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12135. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12136. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12137. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12138. 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');
  12139. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12140. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12141. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12142. this._caps.highPrecisionShaderSupported = true;
  12143. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12144. if (this._caps.timerQuery) {
  12145. if (this._webGLVersion === 1) {
  12146. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12147. }
  12148. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12149. }
  12150. // Checks if some of the format renders first to allow the use of webgl inspector.
  12151. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12152. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12153. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12154. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12155. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12156. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12157. if (this._webGLVersion > 1) {
  12158. this._gl.HALF_FLOAT_OES = 0x140B;
  12159. }
  12160. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12161. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12162. // Draw buffers
  12163. if (this._webGLVersion > 1) {
  12164. this._caps.drawBuffersExtension = true;
  12165. }
  12166. else {
  12167. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12168. if (drawBuffersExtension !== null) {
  12169. this._caps.drawBuffersExtension = true;
  12170. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12171. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12172. for (var i = 0; i < 16; i++) {
  12173. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12174. }
  12175. }
  12176. else {
  12177. this._caps.drawBuffersExtension = false;
  12178. }
  12179. }
  12180. // Depth Texture
  12181. if (this._webGLVersion > 1) {
  12182. this._caps.depthTextureExtension = true;
  12183. }
  12184. else {
  12185. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12186. if (depthTextureExtension != null) {
  12187. this._caps.depthTextureExtension = true;
  12188. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12189. }
  12190. }
  12191. // Vertex array object
  12192. if (this._webGLVersion > 1) {
  12193. this._caps.vertexArrayObject = true;
  12194. }
  12195. else {
  12196. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12197. if (vertexArrayObjectExtension != null) {
  12198. this._caps.vertexArrayObject = true;
  12199. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12200. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12201. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12202. }
  12203. else {
  12204. this._caps.vertexArrayObject = false;
  12205. }
  12206. }
  12207. // Instances count
  12208. if (this._webGLVersion > 1) {
  12209. this._caps.instancedArrays = true;
  12210. }
  12211. else {
  12212. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12213. if (instanceExtension != null) {
  12214. this._caps.instancedArrays = true;
  12215. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12216. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12217. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12218. }
  12219. else {
  12220. this._caps.instancedArrays = false;
  12221. }
  12222. }
  12223. // Intelligently add supported compressed formats in order to check for.
  12224. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12225. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12226. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12227. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12228. if (this._caps.astc)
  12229. this.texturesSupported.push('-astc.ktx');
  12230. if (this._caps.s3tc)
  12231. this.texturesSupported.push('-dxt.ktx');
  12232. if (this._caps.pvrtc)
  12233. this.texturesSupported.push('-pvrtc.ktx');
  12234. if (this._caps.etc2)
  12235. this.texturesSupported.push('-etc2.ktx');
  12236. if (this._caps.etc1)
  12237. this.texturesSupported.push('-etc1.ktx');
  12238. if (this._gl.getShaderPrecisionFormat) {
  12239. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12240. if (highp) {
  12241. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12242. }
  12243. }
  12244. // Depth buffer
  12245. this.setDepthBuffer(true);
  12246. this.setDepthFunctionToLessOrEqual();
  12247. this.setDepthWrite(true);
  12248. // Texture maps
  12249. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12250. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12251. this._nextFreeTextureSlots.push(slot);
  12252. }
  12253. };
  12254. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12255. /**
  12256. * Gets version of the current webGL context
  12257. */
  12258. get: function () {
  12259. return this._webGLVersion;
  12260. },
  12261. enumerable: true,
  12262. configurable: true
  12263. });
  12264. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12265. /**
  12266. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12267. */
  12268. get: function () {
  12269. return this._isStencilEnable;
  12270. },
  12271. enumerable: true,
  12272. configurable: true
  12273. });
  12274. Engine.prototype._prepareWorkingCanvas = function () {
  12275. if (this._workingCanvas) {
  12276. return;
  12277. }
  12278. this._workingCanvas = document.createElement("canvas");
  12279. var context = this._workingCanvas.getContext("2d");
  12280. if (context) {
  12281. this._workingContext = context;
  12282. }
  12283. };
  12284. /**
  12285. * Reset the texture cache to empty state
  12286. */
  12287. Engine.prototype.resetTextureCache = function () {
  12288. for (var key in this._boundTexturesCache) {
  12289. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12290. continue;
  12291. }
  12292. var boundTexture = this._boundTexturesCache[key];
  12293. if (boundTexture) {
  12294. this._removeDesignatedSlot(boundTexture);
  12295. }
  12296. this._boundTexturesCache[key] = null;
  12297. }
  12298. if (!this.disableTextureBindingOptimization) {
  12299. this._nextFreeTextureSlots = [];
  12300. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12301. this._nextFreeTextureSlots.push(slot);
  12302. }
  12303. }
  12304. this._currentTextureChannel = -1;
  12305. };
  12306. /**
  12307. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12308. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12309. * @returns true if engine is in deterministic lock step mode
  12310. */
  12311. Engine.prototype.isDeterministicLockStep = function () {
  12312. return this._deterministicLockstep;
  12313. };
  12314. /**
  12315. * Gets the max steps when engine is running in deterministic lock step
  12316. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12317. * @returns the max steps
  12318. */
  12319. Engine.prototype.getLockstepMaxSteps = function () {
  12320. return this._lockstepMaxSteps;
  12321. };
  12322. /**
  12323. * Gets an object containing information about the current webGL context
  12324. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12325. */
  12326. Engine.prototype.getGlInfo = function () {
  12327. return {
  12328. vendor: this._glVendor,
  12329. renderer: this._glRenderer,
  12330. version: this._glVersion
  12331. };
  12332. };
  12333. /**
  12334. * Gets current aspect ratio
  12335. * @param camera defines the camera to use to get the aspect ratio
  12336. * @param useScreen defines if screen size must be used (or the current render target if any)
  12337. * @returns a number defining the aspect ratio
  12338. */
  12339. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12340. if (useScreen === void 0) { useScreen = false; }
  12341. var viewport = camera.viewport;
  12342. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12343. };
  12344. /**
  12345. * Gets the current render width
  12346. * @param useScreen defines if screen size must be used (or the current render target if any)
  12347. * @returns a number defining the current render width
  12348. */
  12349. Engine.prototype.getRenderWidth = function (useScreen) {
  12350. if (useScreen === void 0) { useScreen = false; }
  12351. if (!useScreen && this._currentRenderTarget) {
  12352. return this._currentRenderTarget.width;
  12353. }
  12354. return this._gl.drawingBufferWidth;
  12355. };
  12356. /**
  12357. * Gets the current render height
  12358. * @param useScreen defines if screen size must be used (or the current render target if any)
  12359. * @returns a number defining the current render height
  12360. */
  12361. Engine.prototype.getRenderHeight = function (useScreen) {
  12362. if (useScreen === void 0) { useScreen = false; }
  12363. if (!useScreen && this._currentRenderTarget) {
  12364. return this._currentRenderTarget.height;
  12365. }
  12366. return this._gl.drawingBufferHeight;
  12367. };
  12368. /**
  12369. * Gets the HTML canvas attached with the current webGL context
  12370. * @returns a HTML canvas
  12371. */
  12372. Engine.prototype.getRenderingCanvas = function () {
  12373. return this._renderingCanvas;
  12374. };
  12375. /**
  12376. * Gets the client rect of the HTML canvas attached with the current webGL context
  12377. * @returns a client rectanglee
  12378. */
  12379. Engine.prototype.getRenderingCanvasClientRect = function () {
  12380. if (!this._renderingCanvas) {
  12381. return null;
  12382. }
  12383. return this._renderingCanvas.getBoundingClientRect();
  12384. };
  12385. /**
  12386. * Defines the hardware scaling level.
  12387. * By default the hardware scaling level is computed from the window device ratio.
  12388. * 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.
  12389. * @param level defines the level to use
  12390. */
  12391. Engine.prototype.setHardwareScalingLevel = function (level) {
  12392. this._hardwareScalingLevel = level;
  12393. this.resize();
  12394. };
  12395. /**
  12396. * Gets the current hardware scaling level.
  12397. * By default the hardware scaling level is computed from the window device ratio.
  12398. * 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.
  12399. * @returns a number indicating the current hardware scaling level
  12400. */
  12401. Engine.prototype.getHardwareScalingLevel = function () {
  12402. return this._hardwareScalingLevel;
  12403. };
  12404. /**
  12405. * Gets the list of loaded textures
  12406. * @returns an array containing all loaded textures
  12407. */
  12408. Engine.prototype.getLoadedTexturesCache = function () {
  12409. return this._internalTexturesCache;
  12410. };
  12411. /**
  12412. * Gets the object containing all engine capabilities
  12413. * @returns the EngineCapabilities object
  12414. */
  12415. Engine.prototype.getCaps = function () {
  12416. return this._caps;
  12417. };
  12418. Object.defineProperty(Engine.prototype, "drawCalls", {
  12419. /** @hidden */
  12420. get: function () {
  12421. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12422. return 0;
  12423. },
  12424. enumerable: true,
  12425. configurable: true
  12426. });
  12427. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12428. /** @hidden */
  12429. get: function () {
  12430. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12431. return null;
  12432. },
  12433. enumerable: true,
  12434. configurable: true
  12435. });
  12436. /**
  12437. * Gets the current depth function
  12438. * @returns a number defining the depth function
  12439. */
  12440. Engine.prototype.getDepthFunction = function () {
  12441. return this._depthCullingState.depthFunc;
  12442. };
  12443. /**
  12444. * Sets the current depth function
  12445. * @param depthFunc defines the function to use
  12446. */
  12447. Engine.prototype.setDepthFunction = function (depthFunc) {
  12448. this._depthCullingState.depthFunc = depthFunc;
  12449. };
  12450. /**
  12451. * Sets the current depth function to GREATER
  12452. */
  12453. Engine.prototype.setDepthFunctionToGreater = function () {
  12454. this._depthCullingState.depthFunc = this._gl.GREATER;
  12455. };
  12456. /**
  12457. * Sets the current depth function to GEQUAL
  12458. */
  12459. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12460. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12461. };
  12462. /**
  12463. * Sets the current depth function to LESS
  12464. */
  12465. Engine.prototype.setDepthFunctionToLess = function () {
  12466. this._depthCullingState.depthFunc = this._gl.LESS;
  12467. };
  12468. /**
  12469. * Sets the current depth function to LEQUAL
  12470. */
  12471. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12472. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12473. };
  12474. /**
  12475. * Gets a boolean indicating if stencil buffer is enabled
  12476. * @returns the current stencil buffer state
  12477. */
  12478. Engine.prototype.getStencilBuffer = function () {
  12479. return this._stencilState.stencilTest;
  12480. };
  12481. /**
  12482. * Enable or disable the stencil buffer
  12483. * @param enable defines if the stencil buffer must be enabled or disabled
  12484. */
  12485. Engine.prototype.setStencilBuffer = function (enable) {
  12486. this._stencilState.stencilTest = enable;
  12487. };
  12488. /**
  12489. * Gets the current stencil mask
  12490. * @returns a number defining the new stencil mask to use
  12491. */
  12492. Engine.prototype.getStencilMask = function () {
  12493. return this._stencilState.stencilMask;
  12494. };
  12495. /**
  12496. * Sets the current stencil mask
  12497. * @param mask defines the new stencil mask to use
  12498. */
  12499. Engine.prototype.setStencilMask = function (mask) {
  12500. this._stencilState.stencilMask = mask;
  12501. };
  12502. /**
  12503. * Gets the current stencil function
  12504. * @returns a number defining the stencil function to use
  12505. */
  12506. Engine.prototype.getStencilFunction = function () {
  12507. return this._stencilState.stencilFunc;
  12508. };
  12509. /**
  12510. * Gets the current stencil reference value
  12511. * @returns a number defining the stencil reference value to use
  12512. */
  12513. Engine.prototype.getStencilFunctionReference = function () {
  12514. return this._stencilState.stencilFuncRef;
  12515. };
  12516. /**
  12517. * Gets the current stencil mask
  12518. * @returns a number defining the stencil mask to use
  12519. */
  12520. Engine.prototype.getStencilFunctionMask = function () {
  12521. return this._stencilState.stencilFuncMask;
  12522. };
  12523. /**
  12524. * Sets the current stencil function
  12525. * @param stencilFunc defines the new stencil function to use
  12526. */
  12527. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12528. this._stencilState.stencilFunc = stencilFunc;
  12529. };
  12530. /**
  12531. * Sets the current stencil reference
  12532. * @param reference defines the new stencil reference to use
  12533. */
  12534. Engine.prototype.setStencilFunctionReference = function (reference) {
  12535. this._stencilState.stencilFuncRef = reference;
  12536. };
  12537. /**
  12538. * Sets the current stencil mask
  12539. * @param mask defines the new stencil mask to use
  12540. */
  12541. Engine.prototype.setStencilFunctionMask = function (mask) {
  12542. this._stencilState.stencilFuncMask = mask;
  12543. };
  12544. /**
  12545. * Gets the current stencil operation when stencil fails
  12546. * @returns a number defining stencil operation to use when stencil fails
  12547. */
  12548. Engine.prototype.getStencilOperationFail = function () {
  12549. return this._stencilState.stencilOpStencilFail;
  12550. };
  12551. /**
  12552. * Gets the current stencil operation when depth fails
  12553. * @returns a number defining stencil operation to use when depth fails
  12554. */
  12555. Engine.prototype.getStencilOperationDepthFail = function () {
  12556. return this._stencilState.stencilOpDepthFail;
  12557. };
  12558. /**
  12559. * Gets the current stencil operation when stencil passes
  12560. * @returns a number defining stencil operation to use when stencil passes
  12561. */
  12562. Engine.prototype.getStencilOperationPass = function () {
  12563. return this._stencilState.stencilOpStencilDepthPass;
  12564. };
  12565. /**
  12566. * Sets the stencil operation to use when stencil fails
  12567. * @param operation defines the stencil operation to use when stencil fails
  12568. */
  12569. Engine.prototype.setStencilOperationFail = function (operation) {
  12570. this._stencilState.stencilOpStencilFail = operation;
  12571. };
  12572. /**
  12573. * Sets the stencil operation to use when depth fails
  12574. * @param operation defines the stencil operation to use when depth fails
  12575. */
  12576. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12577. this._stencilState.stencilOpDepthFail = operation;
  12578. };
  12579. /**
  12580. * Sets the stencil operation to use when stencil passes
  12581. * @param operation defines the stencil operation to use when stencil passes
  12582. */
  12583. Engine.prototype.setStencilOperationPass = function (operation) {
  12584. this._stencilState.stencilOpStencilDepthPass = operation;
  12585. };
  12586. /**
  12587. * Sets a boolean indicating if the dithering state is enabled or disabled
  12588. * @param value defines the dithering state
  12589. */
  12590. Engine.prototype.setDitheringState = function (value) {
  12591. if (value) {
  12592. this._gl.enable(this._gl.DITHER);
  12593. }
  12594. else {
  12595. this._gl.disable(this._gl.DITHER);
  12596. }
  12597. };
  12598. /**
  12599. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12600. * @param value defines the rasterizer state
  12601. */
  12602. Engine.prototype.setRasterizerState = function (value) {
  12603. if (value) {
  12604. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12605. }
  12606. else {
  12607. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12608. }
  12609. };
  12610. /**
  12611. * stop executing a render loop function and remove it from the execution array
  12612. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12613. */
  12614. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12615. if (!renderFunction) {
  12616. this._activeRenderLoops = [];
  12617. return;
  12618. }
  12619. var index = this._activeRenderLoops.indexOf(renderFunction);
  12620. if (index >= 0) {
  12621. this._activeRenderLoops.splice(index, 1);
  12622. }
  12623. };
  12624. /** @hidden */
  12625. Engine.prototype._renderLoop = function () {
  12626. if (!this._contextWasLost) {
  12627. var shouldRender = true;
  12628. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12629. shouldRender = false;
  12630. }
  12631. if (shouldRender) {
  12632. // Start new frame
  12633. this.beginFrame();
  12634. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12635. var renderFunction = this._activeRenderLoops[index];
  12636. renderFunction();
  12637. }
  12638. // Present
  12639. this.endFrame();
  12640. }
  12641. }
  12642. if (this._activeRenderLoops.length > 0) {
  12643. // Register new frame
  12644. var requester = null;
  12645. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12646. requester = this._vrDisplay;
  12647. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12648. }
  12649. else {
  12650. this._renderingQueueLaunched = false;
  12651. }
  12652. };
  12653. /**
  12654. * Register and execute a render loop. The engine can have more than one render function
  12655. * @param renderFunction defines the function to continuously execute
  12656. */
  12657. Engine.prototype.runRenderLoop = function (renderFunction) {
  12658. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12659. return;
  12660. }
  12661. this._activeRenderLoops.push(renderFunction);
  12662. if (!this._renderingQueueLaunched) {
  12663. this._renderingQueueLaunched = true;
  12664. this._bindedRenderFunction = this._renderLoop.bind(this);
  12665. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12666. }
  12667. };
  12668. /**
  12669. * Toggle full screen mode
  12670. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12671. * @param options defines an option object to be sent to the requestFullscreen function
  12672. */
  12673. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12674. if (this.isFullscreen) {
  12675. BABYLON.Tools.ExitFullscreen();
  12676. }
  12677. else {
  12678. this._pointerLockRequested = requestPointerLock;
  12679. if (this._renderingCanvas) {
  12680. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12681. }
  12682. }
  12683. };
  12684. /**
  12685. * Clear the current render buffer or the current render target (if any is set up)
  12686. * @param color defines the color to use
  12687. * @param backBuffer defines if the back buffer must be cleared
  12688. * @param depth defines if the depth buffer must be cleared
  12689. * @param stencil defines if the stencil buffer must be cleared
  12690. */
  12691. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12692. if (stencil === void 0) { stencil = false; }
  12693. this.applyStates();
  12694. var mode = 0;
  12695. if (backBuffer && color) {
  12696. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12697. mode |= this._gl.COLOR_BUFFER_BIT;
  12698. }
  12699. if (depth) {
  12700. this._gl.clearDepth(1.0);
  12701. mode |= this._gl.DEPTH_BUFFER_BIT;
  12702. }
  12703. if (stencil) {
  12704. this._gl.clearStencil(0);
  12705. mode |= this._gl.STENCIL_BUFFER_BIT;
  12706. }
  12707. this._gl.clear(mode);
  12708. };
  12709. /**
  12710. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12711. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12712. * @param y defines the y-coordinate of the corner of the clear rectangle
  12713. * @param width defines the width of the clear rectangle
  12714. * @param height defines the height of the clear rectangle
  12715. * @param clearColor defines the clear color
  12716. */
  12717. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12718. var gl = this._gl;
  12719. // Save state
  12720. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12721. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12722. // Change state
  12723. gl.enable(gl.SCISSOR_TEST);
  12724. gl.scissor(x, y, width, height);
  12725. // Clear
  12726. this.clear(clearColor, true, true, true);
  12727. // Restore state
  12728. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12729. if (curScissor === true) {
  12730. gl.enable(gl.SCISSOR_TEST);
  12731. }
  12732. else {
  12733. gl.disable(gl.SCISSOR_TEST);
  12734. }
  12735. };
  12736. /**
  12737. * Set the WebGL's viewport
  12738. * @param viewport defines the viewport element to be used
  12739. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12740. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12741. */
  12742. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12743. var width = requiredWidth || this.getRenderWidth();
  12744. var height = requiredHeight || this.getRenderHeight();
  12745. var x = viewport.x || 0;
  12746. var y = viewport.y || 0;
  12747. this._cachedViewport = viewport;
  12748. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12749. };
  12750. /**
  12751. * Directly set the WebGL Viewport
  12752. * @param x defines the x coordinate of the viewport (in screen space)
  12753. * @param y defines the y coordinate of the viewport (in screen space)
  12754. * @param width defines the width of the viewport (in screen space)
  12755. * @param height defines the height of the viewport (in screen space)
  12756. * @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
  12757. */
  12758. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12759. var currentViewport = this._cachedViewport;
  12760. this._cachedViewport = null;
  12761. this._gl.viewport(x, y, width, height);
  12762. return currentViewport;
  12763. };
  12764. /**
  12765. * Begin a new frame
  12766. */
  12767. Engine.prototype.beginFrame = function () {
  12768. this.onBeginFrameObservable.notifyObservers(this);
  12769. this._measureFps();
  12770. };
  12771. /**
  12772. * Enf the current frame
  12773. */
  12774. Engine.prototype.endFrame = function () {
  12775. // Force a flush in case we are using a bad OS.
  12776. if (this._badOS) {
  12777. this.flushFramebuffer();
  12778. }
  12779. // Submit frame to the vr device, if enabled
  12780. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12781. // TODO: We should only submit the frame if we read frameData successfully.
  12782. this._vrDisplay.submitFrame();
  12783. }
  12784. this.onEndFrameObservable.notifyObservers(this);
  12785. };
  12786. /**
  12787. * Resize the view according to the canvas' size
  12788. */
  12789. Engine.prototype.resize = function () {
  12790. // We're not resizing the size of the canvas while in VR mode & presenting
  12791. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12792. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12793. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12794. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12795. }
  12796. };
  12797. /**
  12798. * Force a specific size of the canvas
  12799. * @param width defines the new canvas' width
  12800. * @param height defines the new canvas' height
  12801. */
  12802. Engine.prototype.setSize = function (width, height) {
  12803. if (!this._renderingCanvas) {
  12804. return;
  12805. }
  12806. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12807. return;
  12808. }
  12809. this._renderingCanvas.width = width;
  12810. this._renderingCanvas.height = height;
  12811. for (var index = 0; index < this.scenes.length; index++) {
  12812. var scene = this.scenes[index];
  12813. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12814. var cam = scene.cameras[camIndex];
  12815. cam._currentRenderId = 0;
  12816. }
  12817. }
  12818. if (this.onResizeObservable.hasObservers) {
  12819. this.onResizeObservable.notifyObservers(this);
  12820. }
  12821. };
  12822. // WebVR functions
  12823. /**
  12824. * Gets a boolean indicating if a webVR device was detected
  12825. * @returns true if a webVR device was detected
  12826. */
  12827. Engine.prototype.isVRDevicePresent = function () {
  12828. return !!this._vrDisplay;
  12829. };
  12830. /**
  12831. * Gets the current webVR device
  12832. * @returns the current webVR device (or null)
  12833. */
  12834. Engine.prototype.getVRDevice = function () {
  12835. return this._vrDisplay;
  12836. };
  12837. /**
  12838. * Initializes a webVR display and starts listening to display change events
  12839. * The onVRDisplayChangedObservable will be notified upon these changes
  12840. * @returns The onVRDisplayChangedObservable
  12841. */
  12842. Engine.prototype.initWebVR = function () {
  12843. this.initWebVRAsync();
  12844. return this.onVRDisplayChangedObservable;
  12845. };
  12846. /**
  12847. * Initializes a webVR display and starts listening to display change events
  12848. * The onVRDisplayChangedObservable will be notified upon these changes
  12849. * @returns A promise containing a VRDisplay and if vr is supported
  12850. */
  12851. Engine.prototype.initWebVRAsync = function () {
  12852. var _this = this;
  12853. var notifyObservers = function () {
  12854. var eventArgs = {
  12855. vrDisplay: _this._vrDisplay,
  12856. vrSupported: _this._vrSupported
  12857. };
  12858. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12859. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12860. };
  12861. if (!this._onVrDisplayConnect) {
  12862. this._onVrDisplayConnect = function (event) {
  12863. _this._vrDisplay = event.display;
  12864. notifyObservers();
  12865. };
  12866. this._onVrDisplayDisconnect = function () {
  12867. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12868. _this._vrDisplay = undefined;
  12869. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12870. notifyObservers();
  12871. };
  12872. this._onVrDisplayPresentChange = function () {
  12873. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12874. };
  12875. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12876. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12877. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12878. }
  12879. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12880. this._webVRInitPromise.then(notifyObservers);
  12881. return this._webVRInitPromise;
  12882. };
  12883. /**
  12884. * Call this function to switch to webVR mode
  12885. * Will do nothing if webVR is not supported or if there is no webVR device
  12886. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12887. */
  12888. Engine.prototype.enableVR = function () {
  12889. var _this = this;
  12890. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12891. var onResolved = function () {
  12892. _this.onVRRequestPresentComplete.notifyObservers(true);
  12893. _this._onVRFullScreenTriggered();
  12894. };
  12895. var onRejected = function () {
  12896. _this.onVRRequestPresentComplete.notifyObservers(false);
  12897. };
  12898. this.onVRRequestPresentStart.notifyObservers(this);
  12899. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12900. }
  12901. };
  12902. /**
  12903. * Call this function to leave webVR mode
  12904. * Will do nothing if webVR is not supported or if there is no webVR device
  12905. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12906. */
  12907. Engine.prototype.disableVR = function () {
  12908. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12909. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12910. }
  12911. };
  12912. Engine.prototype._getVRDisplaysAsync = function () {
  12913. var _this = this;
  12914. return new Promise(function (res, rej) {
  12915. if (navigator.getVRDisplays) {
  12916. navigator.getVRDisplays().then(function (devices) {
  12917. _this._vrSupported = true;
  12918. // note that devices may actually be an empty array. This is fine;
  12919. // we expect this._vrDisplay to be undefined in this case.
  12920. _this._vrDisplay = devices[0];
  12921. res({
  12922. vrDisplay: _this._vrDisplay,
  12923. vrSupported: _this._vrSupported
  12924. });
  12925. });
  12926. }
  12927. else {
  12928. _this._vrDisplay = undefined;
  12929. _this._vrSupported = false;
  12930. res({
  12931. vrDisplay: _this._vrDisplay,
  12932. vrSupported: _this._vrSupported
  12933. });
  12934. }
  12935. });
  12936. };
  12937. /**
  12938. * Binds the frame buffer to the specified texture.
  12939. * @param texture The texture to render to or null for the default canvas
  12940. * @param faceIndex The face of the texture to render to in case of cube texture
  12941. * @param requiredWidth The width of the target to render to
  12942. * @param requiredHeight The height of the target to render to
  12943. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12944. * @param depthStencilTexture The depth stencil texture to use to render
  12945. */
  12946. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12947. if (this._currentRenderTarget) {
  12948. this.unBindFramebuffer(this._currentRenderTarget);
  12949. }
  12950. this._currentRenderTarget = texture;
  12951. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12952. var gl = this._gl;
  12953. if (texture.isCube) {
  12954. if (faceIndex === undefined) {
  12955. faceIndex = 0;
  12956. }
  12957. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12958. if (depthStencilTexture) {
  12959. if (depthStencilTexture._generateStencilBuffer) {
  12960. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12961. }
  12962. else {
  12963. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12964. }
  12965. }
  12966. }
  12967. if (this._cachedViewport && !forceFullscreenViewport) {
  12968. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12969. }
  12970. else {
  12971. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12972. }
  12973. this.wipeCaches();
  12974. };
  12975. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12976. if (this._currentFramebuffer !== framebuffer) {
  12977. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12978. this._currentFramebuffer = framebuffer;
  12979. }
  12980. };
  12981. /**
  12982. * Unbind the current render target texture from the webGL context
  12983. * @param texture defines the render target texture to unbind
  12984. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  12985. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  12986. */
  12987. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12988. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12989. this._currentRenderTarget = null;
  12990. // If MSAA, we need to bitblt back to main texture
  12991. var gl = this._gl;
  12992. if (texture._MSAAFramebuffer) {
  12993. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12994. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12995. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12996. }
  12997. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12998. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12999. gl.generateMipmap(gl.TEXTURE_2D);
  13000. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13001. }
  13002. if (onBeforeUnbind) {
  13003. if (texture._MSAAFramebuffer) {
  13004. // Bind the correct framebuffer
  13005. this.bindUnboundFramebuffer(texture._framebuffer);
  13006. }
  13007. onBeforeUnbind();
  13008. }
  13009. this.bindUnboundFramebuffer(null);
  13010. };
  13011. /**
  13012. * Unbind a list of render target textures from the webGL context
  13013. * This is used only when drawBuffer extension or webGL2 are active
  13014. * @param textures defines the render target textures to unbind
  13015. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13016. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13017. */
  13018. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13019. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13020. this._currentRenderTarget = null;
  13021. // If MSAA, we need to bitblt back to main texture
  13022. var gl = this._gl;
  13023. if (textures[0]._MSAAFramebuffer) {
  13024. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13025. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13026. var attachments = textures[0]._attachments;
  13027. if (!attachments) {
  13028. attachments = new Array(textures.length);
  13029. textures[0]._attachments = attachments;
  13030. }
  13031. for (var i = 0; i < textures.length; i++) {
  13032. var texture = textures[i];
  13033. for (var j = 0; j < attachments.length; j++) {
  13034. attachments[j] = gl.NONE;
  13035. }
  13036. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13037. gl.readBuffer(attachments[i]);
  13038. gl.drawBuffers(attachments);
  13039. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13040. }
  13041. for (var i = 0; i < attachments.length; i++) {
  13042. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13043. }
  13044. gl.drawBuffers(attachments);
  13045. }
  13046. for (var i = 0; i < textures.length; i++) {
  13047. var texture = textures[i];
  13048. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13049. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13050. gl.generateMipmap(gl.TEXTURE_2D);
  13051. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13052. }
  13053. }
  13054. if (onBeforeUnbind) {
  13055. if (textures[0]._MSAAFramebuffer) {
  13056. // Bind the correct framebuffer
  13057. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13058. }
  13059. onBeforeUnbind();
  13060. }
  13061. this.bindUnboundFramebuffer(null);
  13062. };
  13063. /**
  13064. * Force the mipmap generation for the given render target texture
  13065. * @param texture defines the render target texture to use
  13066. */
  13067. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13068. if (texture.generateMipMaps) {
  13069. var gl = this._gl;
  13070. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13071. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13072. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13073. }
  13074. };
  13075. /**
  13076. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13077. */
  13078. Engine.prototype.flushFramebuffer = function () {
  13079. this._gl.flush();
  13080. };
  13081. /**
  13082. * Unbind the current render target and bind the default framebuffer
  13083. */
  13084. Engine.prototype.restoreDefaultFramebuffer = function () {
  13085. if (this._currentRenderTarget) {
  13086. this.unBindFramebuffer(this._currentRenderTarget);
  13087. }
  13088. else {
  13089. this.bindUnboundFramebuffer(null);
  13090. }
  13091. if (this._cachedViewport) {
  13092. this.setViewport(this._cachedViewport);
  13093. }
  13094. this.wipeCaches();
  13095. };
  13096. // UBOs
  13097. /**
  13098. * Create an uniform buffer
  13099. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13100. * @param elements defines the content of the uniform buffer
  13101. * @returns the webGL uniform buffer
  13102. */
  13103. Engine.prototype.createUniformBuffer = function (elements) {
  13104. var ubo = this._gl.createBuffer();
  13105. if (!ubo) {
  13106. throw new Error("Unable to create uniform buffer");
  13107. }
  13108. this.bindUniformBuffer(ubo);
  13109. if (elements instanceof Float32Array) {
  13110. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13111. }
  13112. else {
  13113. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13114. }
  13115. this.bindUniformBuffer(null);
  13116. ubo.references = 1;
  13117. return ubo;
  13118. };
  13119. /**
  13120. * Create a dynamic uniform buffer
  13121. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13122. * @param elements defines the content of the uniform buffer
  13123. * @returns the webGL uniform buffer
  13124. */
  13125. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13126. var ubo = this._gl.createBuffer();
  13127. if (!ubo) {
  13128. throw new Error("Unable to create dynamic uniform buffer");
  13129. }
  13130. this.bindUniformBuffer(ubo);
  13131. if (elements instanceof Float32Array) {
  13132. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13133. }
  13134. else {
  13135. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13136. }
  13137. this.bindUniformBuffer(null);
  13138. ubo.references = 1;
  13139. return ubo;
  13140. };
  13141. /**
  13142. * Update an existing uniform buffer
  13143. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13144. * @param uniformBuffer defines the target uniform buffer
  13145. * @param elements defines the content to update
  13146. * @param offset defines the offset in the uniform buffer where update should start
  13147. * @param count defines the size of the data to update
  13148. */
  13149. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13150. this.bindUniformBuffer(uniformBuffer);
  13151. if (offset === undefined) {
  13152. offset = 0;
  13153. }
  13154. if (count === undefined) {
  13155. if (elements instanceof Float32Array) {
  13156. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13157. }
  13158. else {
  13159. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13160. }
  13161. }
  13162. else {
  13163. if (elements instanceof Float32Array) {
  13164. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13165. }
  13166. else {
  13167. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13168. }
  13169. }
  13170. this.bindUniformBuffer(null);
  13171. };
  13172. // VBOs
  13173. Engine.prototype._resetVertexBufferBinding = function () {
  13174. this.bindArrayBuffer(null);
  13175. this._cachedVertexBuffers = null;
  13176. };
  13177. /**
  13178. * Creates a vertex buffer
  13179. * @param data the data for the vertex buffer
  13180. * @returns the new WebGL static buffer
  13181. */
  13182. Engine.prototype.createVertexBuffer = function (data) {
  13183. var vbo = this._gl.createBuffer();
  13184. if (!vbo) {
  13185. throw new Error("Unable to create vertex buffer");
  13186. }
  13187. this.bindArrayBuffer(vbo);
  13188. if (data instanceof Array) {
  13189. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13190. }
  13191. else {
  13192. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13193. }
  13194. this._resetVertexBufferBinding();
  13195. vbo.references = 1;
  13196. return vbo;
  13197. };
  13198. /**
  13199. * Creates a dynamic vertex buffer
  13200. * @param data the data for the dynamic vertex buffer
  13201. * @returns the new WebGL dynamic buffer
  13202. */
  13203. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13204. var vbo = this._gl.createBuffer();
  13205. if (!vbo) {
  13206. throw new Error("Unable to create dynamic vertex buffer");
  13207. }
  13208. this.bindArrayBuffer(vbo);
  13209. if (data instanceof Array) {
  13210. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13211. }
  13212. else {
  13213. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13214. }
  13215. this._resetVertexBufferBinding();
  13216. vbo.references = 1;
  13217. return vbo;
  13218. };
  13219. /**
  13220. * Update a dynamic index buffer
  13221. * @param indexBuffer defines the target index buffer
  13222. * @param indices defines the data to update
  13223. * @param offset defines the offset in the target index buffer where update should start
  13224. */
  13225. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13226. if (offset === void 0) { offset = 0; }
  13227. // Force cache update
  13228. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13229. this.bindIndexBuffer(indexBuffer);
  13230. var arrayBuffer;
  13231. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13232. arrayBuffer = indices;
  13233. }
  13234. else {
  13235. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13236. }
  13237. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13238. this._resetIndexBufferBinding();
  13239. };
  13240. /**
  13241. * Updates a dynamic vertex buffer.
  13242. * @param vertexBuffer the vertex buffer to update
  13243. * @param data the data used to update the vertex buffer
  13244. * @param byteOffset the byte offset of the data
  13245. * @param byteLength the byte length of the data
  13246. */
  13247. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13248. this.bindArrayBuffer(vertexBuffer);
  13249. if (byteOffset === undefined) {
  13250. byteOffset = 0;
  13251. }
  13252. if (byteLength === undefined) {
  13253. if (data instanceof Array) {
  13254. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13255. }
  13256. else {
  13257. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13258. }
  13259. }
  13260. else {
  13261. if (data instanceof Array) {
  13262. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13263. }
  13264. else {
  13265. if (data instanceof ArrayBuffer) {
  13266. data = new Uint8Array(data, byteOffset, byteLength);
  13267. }
  13268. else {
  13269. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13270. }
  13271. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13272. }
  13273. }
  13274. this._resetVertexBufferBinding();
  13275. };
  13276. Engine.prototype._resetIndexBufferBinding = function () {
  13277. this.bindIndexBuffer(null);
  13278. this._cachedIndexBuffer = null;
  13279. };
  13280. /**
  13281. * Creates a new index buffer
  13282. * @param indices defines the content of the index buffer
  13283. * @param updatable defines if the index buffer must be updatable
  13284. * @returns a new webGL buffer
  13285. */
  13286. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13287. var vbo = this._gl.createBuffer();
  13288. if (!vbo) {
  13289. throw new Error("Unable to create index buffer");
  13290. }
  13291. this.bindIndexBuffer(vbo);
  13292. // Check for 32 bits indices
  13293. var arrayBuffer;
  13294. var need32Bits = false;
  13295. if (indices instanceof Uint16Array) {
  13296. arrayBuffer = indices;
  13297. }
  13298. else {
  13299. //check 32 bit support
  13300. if (this._caps.uintIndices) {
  13301. if (indices instanceof Uint32Array) {
  13302. arrayBuffer = indices;
  13303. need32Bits = true;
  13304. }
  13305. else {
  13306. //number[] or Int32Array, check if 32 bit is necessary
  13307. for (var index = 0; index < indices.length; index++) {
  13308. if (indices[index] > 65535) {
  13309. need32Bits = true;
  13310. break;
  13311. }
  13312. }
  13313. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13314. }
  13315. }
  13316. else {
  13317. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13318. arrayBuffer = new Uint16Array(indices);
  13319. }
  13320. }
  13321. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13322. this._resetIndexBufferBinding();
  13323. vbo.references = 1;
  13324. vbo.is32Bits = need32Bits;
  13325. return vbo;
  13326. };
  13327. /**
  13328. * Bind a webGL buffer to the webGL context
  13329. * @param buffer defines the buffer to bind
  13330. */
  13331. Engine.prototype.bindArrayBuffer = function (buffer) {
  13332. if (!this._vaoRecordInProgress) {
  13333. this._unbindVertexArrayObject();
  13334. }
  13335. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13336. };
  13337. /**
  13338. * Bind an uniform buffer to the current webGL context
  13339. * @param buffer defines the buffer to bind
  13340. */
  13341. Engine.prototype.bindUniformBuffer = function (buffer) {
  13342. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13343. };
  13344. /**
  13345. * Bind a buffer to the current webGL context at a given location
  13346. * @param buffer defines the buffer to bind
  13347. * @param location defines the index where to bind the buffer
  13348. */
  13349. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13350. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13351. };
  13352. /**
  13353. * Bind a specific block at a given index in a specific shader program
  13354. * @param shaderProgram defines the shader program
  13355. * @param blockName defines the block name
  13356. * @param index defines the index where to bind the block
  13357. */
  13358. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13359. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13360. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13361. };
  13362. ;
  13363. Engine.prototype.bindIndexBuffer = function (buffer) {
  13364. if (!this._vaoRecordInProgress) {
  13365. this._unbindVertexArrayObject();
  13366. }
  13367. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13368. };
  13369. Engine.prototype.bindBuffer = function (buffer, target) {
  13370. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13371. this._gl.bindBuffer(target, buffer);
  13372. this._currentBoundBuffer[target] = buffer;
  13373. }
  13374. };
  13375. /**
  13376. * update the bound buffer with the given data
  13377. * @param data defines the data to update
  13378. */
  13379. Engine.prototype.updateArrayBuffer = function (data) {
  13380. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13381. };
  13382. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13383. var pointer = this._currentBufferPointers[indx];
  13384. var changed = false;
  13385. if (!pointer.active) {
  13386. changed = true;
  13387. pointer.active = true;
  13388. pointer.index = indx;
  13389. pointer.size = size;
  13390. pointer.type = type;
  13391. pointer.normalized = normalized;
  13392. pointer.stride = stride;
  13393. pointer.offset = offset;
  13394. pointer.buffer = buffer;
  13395. }
  13396. else {
  13397. if (pointer.buffer !== buffer) {
  13398. pointer.buffer = buffer;
  13399. changed = true;
  13400. }
  13401. if (pointer.size !== size) {
  13402. pointer.size = size;
  13403. changed = true;
  13404. }
  13405. if (pointer.type !== type) {
  13406. pointer.type = type;
  13407. changed = true;
  13408. }
  13409. if (pointer.normalized !== normalized) {
  13410. pointer.normalized = normalized;
  13411. changed = true;
  13412. }
  13413. if (pointer.stride !== stride) {
  13414. pointer.stride = stride;
  13415. changed = true;
  13416. }
  13417. if (pointer.offset !== offset) {
  13418. pointer.offset = offset;
  13419. changed = true;
  13420. }
  13421. }
  13422. if (changed || this._vaoRecordInProgress) {
  13423. this.bindArrayBuffer(buffer);
  13424. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13425. }
  13426. };
  13427. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13428. if (indexBuffer == null) {
  13429. return;
  13430. }
  13431. if (this._cachedIndexBuffer !== indexBuffer) {
  13432. this._cachedIndexBuffer = indexBuffer;
  13433. this.bindIndexBuffer(indexBuffer);
  13434. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13435. }
  13436. };
  13437. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13438. var attributes = effect.getAttributesNames();
  13439. if (!this._vaoRecordInProgress) {
  13440. this._unbindVertexArrayObject();
  13441. }
  13442. this.unbindAllAttributes();
  13443. for (var index = 0; index < attributes.length; index++) {
  13444. var order = effect.getAttributeLocation(index);
  13445. if (order >= 0) {
  13446. var vertexBuffer = vertexBuffers[attributes[index]];
  13447. if (!vertexBuffer) {
  13448. continue;
  13449. }
  13450. this._gl.enableVertexAttribArray(order);
  13451. if (!this._vaoRecordInProgress) {
  13452. this._vertexAttribArraysEnabled[order] = true;
  13453. }
  13454. var buffer = vertexBuffer.getBuffer();
  13455. if (buffer) {
  13456. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13457. if (vertexBuffer.getIsInstanced()) {
  13458. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13459. if (!this._vaoRecordInProgress) {
  13460. this._currentInstanceLocations.push(order);
  13461. this._currentInstanceBuffers.push(buffer);
  13462. }
  13463. }
  13464. }
  13465. }
  13466. }
  13467. };
  13468. /**
  13469. * Records a vertex array object
  13470. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13471. * @param vertexBuffers defines the list of vertex buffers to store
  13472. * @param indexBuffer defines the index buffer to store
  13473. * @param effect defines the effect to store
  13474. * @returns the new vertex array object
  13475. */
  13476. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13477. var vao = this._gl.createVertexArray();
  13478. this._vaoRecordInProgress = true;
  13479. this._gl.bindVertexArray(vao);
  13480. this._mustWipeVertexAttributes = true;
  13481. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13482. this.bindIndexBuffer(indexBuffer);
  13483. this._vaoRecordInProgress = false;
  13484. this._gl.bindVertexArray(null);
  13485. return vao;
  13486. };
  13487. /**
  13488. * Bind a specific vertex array object
  13489. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13490. * @param vertexArrayObject defines the vertex array object to bind
  13491. * @param indexBuffer defines the index buffer to bind
  13492. */
  13493. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13494. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13495. this._cachedVertexArrayObject = vertexArrayObject;
  13496. this._gl.bindVertexArray(vertexArrayObject);
  13497. this._cachedVertexBuffers = null;
  13498. this._cachedIndexBuffer = null;
  13499. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13500. this._mustWipeVertexAttributes = true;
  13501. }
  13502. };
  13503. /**
  13504. * Bind webGl buffers directly to the webGL context
  13505. * @param vertexBuffer defines the vertex buffer to bind
  13506. * @param indexBuffer defines the index buffer to bind
  13507. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13508. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13509. * @param effect defines the effect associated with the vertex buffer
  13510. */
  13511. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13512. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13513. this._cachedVertexBuffers = vertexBuffer;
  13514. this._cachedEffectForVertexBuffers = effect;
  13515. var attributesCount = effect.getAttributesCount();
  13516. this._unbindVertexArrayObject();
  13517. this.unbindAllAttributes();
  13518. var offset = 0;
  13519. for (var index = 0; index < attributesCount; index++) {
  13520. if (index < vertexDeclaration.length) {
  13521. var order = effect.getAttributeLocation(index);
  13522. if (order >= 0) {
  13523. this._gl.enableVertexAttribArray(order);
  13524. this._vertexAttribArraysEnabled[order] = true;
  13525. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13526. }
  13527. offset += vertexDeclaration[index] * 4;
  13528. }
  13529. }
  13530. }
  13531. this._bindIndexBufferWithCache(indexBuffer);
  13532. };
  13533. Engine.prototype._unbindVertexArrayObject = function () {
  13534. if (!this._cachedVertexArrayObject) {
  13535. return;
  13536. }
  13537. this._cachedVertexArrayObject = null;
  13538. this._gl.bindVertexArray(null);
  13539. };
  13540. /**
  13541. * Bind a list of vertex buffers to the webGL context
  13542. * @param vertexBuffers defines the list of vertex buffers to bind
  13543. * @param indexBuffer defines the index buffer to bind
  13544. * @param effect defines the effect associated with the vertex buffers
  13545. */
  13546. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13547. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13548. this._cachedVertexBuffers = vertexBuffers;
  13549. this._cachedEffectForVertexBuffers = effect;
  13550. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13551. }
  13552. this._bindIndexBufferWithCache(indexBuffer);
  13553. };
  13554. /**
  13555. * Unbind all instance attributes
  13556. */
  13557. Engine.prototype.unbindInstanceAttributes = function () {
  13558. var boundBuffer;
  13559. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13560. var instancesBuffer = this._currentInstanceBuffers[i];
  13561. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13562. boundBuffer = instancesBuffer;
  13563. this.bindArrayBuffer(instancesBuffer);
  13564. }
  13565. var offsetLocation = this._currentInstanceLocations[i];
  13566. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13567. }
  13568. this._currentInstanceBuffers.length = 0;
  13569. this._currentInstanceLocations.length = 0;
  13570. };
  13571. /**
  13572. * Release and free the memory of a vertex array object
  13573. * @param vao defines the vertex array object to delete
  13574. */
  13575. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13576. this._gl.deleteVertexArray(vao);
  13577. };
  13578. /** @hidden */
  13579. Engine.prototype._releaseBuffer = function (buffer) {
  13580. buffer.references--;
  13581. if (buffer.references === 0) {
  13582. this._gl.deleteBuffer(buffer);
  13583. return true;
  13584. }
  13585. return false;
  13586. };
  13587. /**
  13588. * Creates a webGL buffer to use with instanciation
  13589. * @param capacity defines the size of the buffer
  13590. * @returns the webGL buffer
  13591. */
  13592. Engine.prototype.createInstancesBuffer = function (capacity) {
  13593. var buffer = this._gl.createBuffer();
  13594. if (!buffer) {
  13595. throw new Error("Unable to create instance buffer");
  13596. }
  13597. buffer.capacity = capacity;
  13598. this.bindArrayBuffer(buffer);
  13599. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13600. return buffer;
  13601. };
  13602. /**
  13603. * Delete a webGL buffer used with instanciation
  13604. * @param buffer defines the webGL buffer to delete
  13605. */
  13606. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13607. this._gl.deleteBuffer(buffer);
  13608. };
  13609. /**
  13610. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13611. * @param instancesBuffer defines the webGL buffer to update and bind
  13612. * @param data defines the data to store in the buffer
  13613. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13614. */
  13615. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13616. this.bindArrayBuffer(instancesBuffer);
  13617. if (data) {
  13618. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13619. }
  13620. if (offsetLocations[0].index !== undefined) {
  13621. var stride = 0;
  13622. for (var i = 0; i < offsetLocations.length; i++) {
  13623. var ai = offsetLocations[i];
  13624. stride += ai.attributeSize * 4;
  13625. }
  13626. for (var i = 0; i < offsetLocations.length; i++) {
  13627. var ai = offsetLocations[i];
  13628. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13629. this._gl.enableVertexAttribArray(ai.index);
  13630. this._vertexAttribArraysEnabled[ai.index] = true;
  13631. }
  13632. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13633. this._gl.vertexAttribDivisor(ai.index, 1);
  13634. this._currentInstanceLocations.push(ai.index);
  13635. this._currentInstanceBuffers.push(instancesBuffer);
  13636. }
  13637. }
  13638. else {
  13639. for (var index = 0; index < 4; index++) {
  13640. var offsetLocation = offsetLocations[index];
  13641. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13642. this._gl.enableVertexAttribArray(offsetLocation);
  13643. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13644. }
  13645. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13646. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13647. this._currentInstanceLocations.push(offsetLocation);
  13648. this._currentInstanceBuffers.push(instancesBuffer);
  13649. }
  13650. }
  13651. };
  13652. /**
  13653. * Apply all cached states (depth, culling, stencil and alpha)
  13654. */
  13655. Engine.prototype.applyStates = function () {
  13656. this._depthCullingState.apply(this._gl);
  13657. this._stencilState.apply(this._gl);
  13658. this._alphaState.apply(this._gl);
  13659. };
  13660. /**
  13661. * Send a draw order
  13662. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13663. * @param indexStart defines the starting index
  13664. * @param indexCount defines the number of index to draw
  13665. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13666. */
  13667. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13668. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13669. };
  13670. /**
  13671. * Draw a list of points
  13672. * @param verticesStart defines the index of first vertex to draw
  13673. * @param verticesCount defines the count of vertices to draw
  13674. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13675. */
  13676. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13677. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13678. };
  13679. /**
  13680. * Draw a list of unindexed primitives
  13681. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13682. * @param verticesStart defines the index of first vertex to draw
  13683. * @param verticesCount defines the count of vertices to draw
  13684. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13685. */
  13686. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13687. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13688. };
  13689. /**
  13690. * Draw a list of indexed primitives
  13691. * @param fillMode defines the primitive to use
  13692. * @param indexStart defines the starting index
  13693. * @param indexCount defines the number of index to draw
  13694. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13695. */
  13696. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13697. // Apply states
  13698. this.applyStates();
  13699. this._drawCalls.addCount(1, false);
  13700. // Render
  13701. var drawMode = this._drawMode(fillMode);
  13702. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13703. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13704. if (instancesCount) {
  13705. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13706. }
  13707. else {
  13708. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13709. }
  13710. };
  13711. /**
  13712. * Draw a list of unindexed primitives
  13713. * @param fillMode defines the primitive to use
  13714. * @param verticesStart defines the index of first vertex to draw
  13715. * @param verticesCount defines the count of vertices to draw
  13716. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13717. */
  13718. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13719. // Apply states
  13720. this.applyStates();
  13721. this._drawCalls.addCount(1, false);
  13722. var drawMode = this._drawMode(fillMode);
  13723. if (instancesCount) {
  13724. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13725. }
  13726. else {
  13727. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13728. }
  13729. };
  13730. Engine.prototype._drawMode = function (fillMode) {
  13731. switch (fillMode) {
  13732. // Triangle views
  13733. case BABYLON.Material.TriangleFillMode:
  13734. return this._gl.TRIANGLES;
  13735. case BABYLON.Material.PointFillMode:
  13736. return this._gl.POINTS;
  13737. case BABYLON.Material.WireFrameFillMode:
  13738. return this._gl.LINES;
  13739. // Draw modes
  13740. case BABYLON.Material.PointListDrawMode:
  13741. return this._gl.POINTS;
  13742. case BABYLON.Material.LineListDrawMode:
  13743. return this._gl.LINES;
  13744. case BABYLON.Material.LineLoopDrawMode:
  13745. return this._gl.LINE_LOOP;
  13746. case BABYLON.Material.LineStripDrawMode:
  13747. return this._gl.LINE_STRIP;
  13748. case BABYLON.Material.TriangleStripDrawMode:
  13749. return this._gl.TRIANGLE_STRIP;
  13750. case BABYLON.Material.TriangleFanDrawMode:
  13751. return this._gl.TRIANGLE_FAN;
  13752. default:
  13753. return this._gl.TRIANGLES;
  13754. }
  13755. };
  13756. // Shaders
  13757. /** @hidden */
  13758. Engine.prototype._releaseEffect = function (effect) {
  13759. if (this._compiledEffects[effect._key]) {
  13760. delete this._compiledEffects[effect._key];
  13761. this._deleteProgram(effect.getProgram());
  13762. }
  13763. };
  13764. /** @hidden */
  13765. Engine.prototype._deleteProgram = function (program) {
  13766. if (program) {
  13767. program.__SPECTOR_rebuildProgram = null;
  13768. if (program.transformFeedback) {
  13769. this.deleteTransformFeedback(program.transformFeedback);
  13770. program.transformFeedback = null;
  13771. }
  13772. this._gl.deleteProgram(program);
  13773. }
  13774. };
  13775. /**
  13776. * Create a new effect (used to store vertex/fragment shaders)
  13777. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13778. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13779. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13780. * @param samplers defines an array of string used to represent textures
  13781. * @param defines defines the string containing the defines to use to compile the shaders
  13782. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13783. * @param onCompiled defines a function to call when the effect creation is successful
  13784. * @param onError defines a function to call when the effect creation has failed
  13785. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13786. * @returns the new Effect
  13787. */
  13788. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13789. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13790. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13791. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13792. if (this._compiledEffects[name]) {
  13793. var compiledEffect = this._compiledEffects[name];
  13794. if (onCompiled && compiledEffect.isReady()) {
  13795. onCompiled(compiledEffect);
  13796. }
  13797. return compiledEffect;
  13798. }
  13799. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13800. effect._key = name;
  13801. this._compiledEffects[name] = effect;
  13802. return effect;
  13803. };
  13804. /**
  13805. * Create an effect to use with particle systems
  13806. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13807. * @param uniformsNames defines a list of attribute names
  13808. * @param samplers defines an array of string used to represent textures
  13809. * @param defines defines the string containing the defines to use to compile the shaders
  13810. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13811. * @param onCompiled defines a function to call when the effect creation is successful
  13812. * @param onError defines a function to call when the effect creation has failed
  13813. * @returns the new Effect
  13814. */
  13815. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13816. if (uniformsNames === void 0) { uniformsNames = []; }
  13817. if (samplers === void 0) { samplers = []; }
  13818. if (defines === void 0) { defines = ""; }
  13819. return this.createEffect({
  13820. vertex: "particles",
  13821. fragmentElement: fragmentName
  13822. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13823. };
  13824. /**
  13825. * Directly creates a webGL program
  13826. * @param vertexCode defines the vertex shader code to use
  13827. * @param fragmentCode defines the fragment shader code to use
  13828. * @param context defines the webGL context to use (if not set, the current one will be used)
  13829. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13830. * @returns the new webGL program
  13831. */
  13832. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13833. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13834. context = context || this._gl;
  13835. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13836. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13837. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13838. };
  13839. /**
  13840. * Creates a webGL program
  13841. * @param vertexCode defines the vertex shader code to use
  13842. * @param fragmentCode defines the fragment shader code to use
  13843. * @param defines defines the string containing the defines to use to compile the shaders
  13844. * @param context defines the webGL context to use (if not set, the current one will be used)
  13845. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13846. * @returns the new webGL program
  13847. */
  13848. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13849. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13850. context = context || this._gl;
  13851. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13852. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13853. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13854. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13855. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13856. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13857. return program;
  13858. };
  13859. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13860. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13861. var shaderProgram = context.createProgram();
  13862. if (!shaderProgram) {
  13863. throw new Error("Unable to create program");
  13864. }
  13865. context.attachShader(shaderProgram, vertexShader);
  13866. context.attachShader(shaderProgram, fragmentShader);
  13867. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13868. var transformFeedback = this.createTransformFeedback();
  13869. this.bindTransformFeedback(transformFeedback);
  13870. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13871. shaderProgram.transformFeedback = transformFeedback;
  13872. }
  13873. context.linkProgram(shaderProgram);
  13874. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13875. this.bindTransformFeedback(null);
  13876. }
  13877. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13878. if (!linked) {
  13879. context.validateProgram(shaderProgram);
  13880. var error = context.getProgramInfoLog(shaderProgram);
  13881. if (error) {
  13882. throw new Error(error);
  13883. }
  13884. }
  13885. context.deleteShader(vertexShader);
  13886. context.deleteShader(fragmentShader);
  13887. return shaderProgram;
  13888. };
  13889. /**
  13890. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13891. * @param shaderProgram defines the webGL program to use
  13892. * @param uniformsNames defines the list of uniform names
  13893. * @returns an array of webGL uniform locations
  13894. */
  13895. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13896. var results = new Array();
  13897. for (var index = 0; index < uniformsNames.length; index++) {
  13898. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13899. }
  13900. return results;
  13901. };
  13902. /**
  13903. * Gets the lsit of active attributes for a given webGL program
  13904. * @param shaderProgram defines the webGL program to use
  13905. * @param attributesNames defines the list of attribute names to get
  13906. * @returns an array of indices indicating the offset of each attribute
  13907. */
  13908. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13909. var results = [];
  13910. for (var index = 0; index < attributesNames.length; index++) {
  13911. try {
  13912. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13913. }
  13914. catch (e) {
  13915. results.push(-1);
  13916. }
  13917. }
  13918. return results;
  13919. };
  13920. /**
  13921. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13922. * @param effect defines the effect to activate
  13923. */
  13924. Engine.prototype.enableEffect = function (effect) {
  13925. if (!effect) {
  13926. return;
  13927. }
  13928. // Use program
  13929. this.bindSamplers(effect);
  13930. this._currentEffect = effect;
  13931. if (effect.onBind) {
  13932. effect.onBind(effect);
  13933. }
  13934. effect.onBindObservable.notifyObservers(effect);
  13935. };
  13936. /**
  13937. * Set the value of an uniform to an array of int32
  13938. * @param uniform defines the webGL uniform location where to store the value
  13939. * @param array defines the array of int32 to store
  13940. */
  13941. Engine.prototype.setIntArray = function (uniform, array) {
  13942. if (!uniform)
  13943. return;
  13944. this._gl.uniform1iv(uniform, array);
  13945. };
  13946. /**
  13947. * Set the value of an uniform to an array of int32 (stored as vec2)
  13948. * @param uniform defines the webGL uniform location where to store the value
  13949. * @param array defines the array of int32 to store
  13950. */
  13951. Engine.prototype.setIntArray2 = function (uniform, array) {
  13952. if (!uniform || array.length % 2 !== 0)
  13953. return;
  13954. this._gl.uniform2iv(uniform, array);
  13955. };
  13956. /**
  13957. * Set the value of an uniform to an array of int32 (stored as vec3)
  13958. * @param uniform defines the webGL uniform location where to store the value
  13959. * @param array defines the array of int32 to store
  13960. */
  13961. Engine.prototype.setIntArray3 = function (uniform, array) {
  13962. if (!uniform || array.length % 3 !== 0)
  13963. return;
  13964. this._gl.uniform3iv(uniform, array);
  13965. };
  13966. /**
  13967. * Set the value of an uniform to an array of int32 (stored as vec4)
  13968. * @param uniform defines the webGL uniform location where to store the value
  13969. * @param array defines the array of int32 to store
  13970. */
  13971. Engine.prototype.setIntArray4 = function (uniform, array) {
  13972. if (!uniform || array.length % 4 !== 0)
  13973. return;
  13974. this._gl.uniform4iv(uniform, array);
  13975. };
  13976. /**
  13977. * Set the value of an uniform to an array of float32
  13978. * @param uniform defines the webGL uniform location where to store the value
  13979. * @param array defines the array of float32 to store
  13980. */
  13981. Engine.prototype.setFloatArray = function (uniform, array) {
  13982. if (!uniform)
  13983. return;
  13984. this._gl.uniform1fv(uniform, array);
  13985. };
  13986. /**
  13987. * Set the value of an uniform to an array of float32 (stored as vec2)
  13988. * @param uniform defines the webGL uniform location where to store the value
  13989. * @param array defines the array of float32 to store
  13990. */
  13991. Engine.prototype.setFloatArray2 = function (uniform, array) {
  13992. if (!uniform || array.length % 2 !== 0)
  13993. return;
  13994. this._gl.uniform2fv(uniform, array);
  13995. };
  13996. /**
  13997. * Set the value of an uniform to an array of float32 (stored as vec3)
  13998. * @param uniform defines the webGL uniform location where to store the value
  13999. * @param array defines the array of float32 to store
  14000. */
  14001. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14002. if (!uniform || array.length % 3 !== 0)
  14003. return;
  14004. this._gl.uniform3fv(uniform, array);
  14005. };
  14006. /**
  14007. * Set the value of an uniform to an array of float32 (stored as vec4)
  14008. * @param uniform defines the webGL uniform location where to store the value
  14009. * @param array defines the array of float32 to store
  14010. */
  14011. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14012. if (!uniform || array.length % 4 !== 0)
  14013. return;
  14014. this._gl.uniform4fv(uniform, array);
  14015. };
  14016. /**
  14017. * Set the value of an uniform to an array of number
  14018. * @param uniform defines the webGL uniform location where to store the value
  14019. * @param array defines the array of number to store
  14020. */
  14021. Engine.prototype.setArray = function (uniform, array) {
  14022. if (!uniform)
  14023. return;
  14024. this._gl.uniform1fv(uniform, array);
  14025. };
  14026. /**
  14027. * Set the value of an uniform to an array of number (stored as vec2)
  14028. * @param uniform defines the webGL uniform location where to store the value
  14029. * @param array defines the array of number to store
  14030. */
  14031. Engine.prototype.setArray2 = function (uniform, array) {
  14032. if (!uniform || array.length % 2 !== 0)
  14033. return;
  14034. this._gl.uniform2fv(uniform, array);
  14035. };
  14036. /**
  14037. * Set the value of an uniform to an array of number (stored as vec3)
  14038. * @param uniform defines the webGL uniform location where to store the value
  14039. * @param array defines the array of number to store
  14040. */
  14041. Engine.prototype.setArray3 = function (uniform, array) {
  14042. if (!uniform || array.length % 3 !== 0)
  14043. return;
  14044. this._gl.uniform3fv(uniform, array);
  14045. };
  14046. /**
  14047. * Set the value of an uniform to an array of number (stored as vec4)
  14048. * @param uniform defines the webGL uniform location where to store the value
  14049. * @param array defines the array of number to store
  14050. */
  14051. Engine.prototype.setArray4 = function (uniform, array) {
  14052. if (!uniform || array.length % 4 !== 0)
  14053. return;
  14054. this._gl.uniform4fv(uniform, array);
  14055. };
  14056. /**
  14057. * Set the value of an uniform to an array of float32 (stored as matrices)
  14058. * @param uniform defines the webGL uniform location where to store the value
  14059. * @param matrices defines the array of float32 to store
  14060. */
  14061. Engine.prototype.setMatrices = function (uniform, matrices) {
  14062. if (!uniform)
  14063. return;
  14064. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14065. };
  14066. /**
  14067. * Set the value of an uniform to a matrix
  14068. * @param uniform defines the webGL uniform location where to store the value
  14069. * @param matrix defines the matrix to store
  14070. */
  14071. Engine.prototype.setMatrix = function (uniform, matrix) {
  14072. if (!uniform)
  14073. return;
  14074. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14075. };
  14076. /**
  14077. * Set the value of an uniform to a matrix (3x3)
  14078. * @param uniform defines the webGL uniform location where to store the value
  14079. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14080. */
  14081. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14082. if (!uniform)
  14083. return;
  14084. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14085. };
  14086. /**
  14087. * Set the value of an uniform to a matrix (2x2)
  14088. * @param uniform defines the webGL uniform location where to store the value
  14089. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14090. */
  14091. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14092. if (!uniform)
  14093. return;
  14094. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14095. };
  14096. /**
  14097. * Set the value of an uniform to a number (int)
  14098. * @param uniform defines the webGL uniform location where to store the value
  14099. * @param value defines the int number to store
  14100. */
  14101. Engine.prototype.setInt = function (uniform, value) {
  14102. if (!uniform)
  14103. return;
  14104. this._gl.uniform1i(uniform, value);
  14105. };
  14106. /**
  14107. * Set the value of an uniform to a number (float)
  14108. * @param uniform defines the webGL uniform location where to store the value
  14109. * @param value defines the float number to store
  14110. */
  14111. Engine.prototype.setFloat = function (uniform, value) {
  14112. if (!uniform)
  14113. return;
  14114. this._gl.uniform1f(uniform, value);
  14115. };
  14116. /**
  14117. * Set the value of an uniform to a vec2
  14118. * @param uniform defines the webGL uniform location where to store the value
  14119. * @param x defines the 1st component of the value
  14120. * @param y defines the 2nd component of the value
  14121. */
  14122. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14123. if (!uniform)
  14124. return;
  14125. this._gl.uniform2f(uniform, x, y);
  14126. };
  14127. /**
  14128. * Set the value of an uniform to a vec3
  14129. * @param uniform defines the webGL uniform location where to store the value
  14130. * @param x defines the 1st component of the value
  14131. * @param y defines the 2nd component of the value
  14132. * @param z defines the 3rd component of the value
  14133. */
  14134. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14135. if (!uniform)
  14136. return;
  14137. this._gl.uniform3f(uniform, x, y, z);
  14138. };
  14139. /**
  14140. * Set the value of an uniform to a boolean
  14141. * @param uniform defines the webGL uniform location where to store the value
  14142. * @param bool defines the boolean to store
  14143. */
  14144. Engine.prototype.setBool = function (uniform, bool) {
  14145. if (!uniform)
  14146. return;
  14147. this._gl.uniform1i(uniform, bool);
  14148. };
  14149. /**
  14150. * Set the value of an uniform to a vec4
  14151. * @param uniform defines the webGL uniform location where to store the value
  14152. * @param x defines the 1st component of the value
  14153. * @param y defines the 2nd component of the value
  14154. * @param z defines the 3rd component of the value
  14155. * @param w defines the 4th component of the value
  14156. */
  14157. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14158. if (!uniform)
  14159. return;
  14160. this._gl.uniform4f(uniform, x, y, z, w);
  14161. };
  14162. /**
  14163. * Set the value of an uniform to a Color3
  14164. * @param uniform defines the webGL uniform location where to store the value
  14165. * @param color3 defines the color to store
  14166. */
  14167. Engine.prototype.setColor3 = function (uniform, color3) {
  14168. if (!uniform)
  14169. return;
  14170. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14171. };
  14172. /**
  14173. * Set the value of an uniform to a Color3 and an alpha value
  14174. * @param uniform defines the webGL uniform location where to store the value
  14175. * @param color3 defines the color to store
  14176. * @param alpha defines the alpha component to store
  14177. */
  14178. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14179. if (!uniform)
  14180. return;
  14181. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14182. };
  14183. /**
  14184. * Sets a Color4 on a uniform variable
  14185. * @param uniform defines the uniform location
  14186. * @param color4 defines the value to be set
  14187. */
  14188. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14189. if (!uniform)
  14190. return;
  14191. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14192. };
  14193. // States
  14194. /**
  14195. * Set various states to the webGL context
  14196. * @param culling defines backface culling state
  14197. * @param zOffset defines the value to apply to zOffset (0 by default)
  14198. * @param force defines if states must be applied even if cache is up to date
  14199. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14200. */
  14201. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14202. if (zOffset === void 0) { zOffset = 0; }
  14203. if (reverseSide === void 0) { reverseSide = false; }
  14204. // Culling
  14205. if (this._depthCullingState.cull !== culling || force) {
  14206. this._depthCullingState.cull = culling;
  14207. }
  14208. // Cull face
  14209. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14210. if (this._depthCullingState.cullFace !== cullFace || force) {
  14211. this._depthCullingState.cullFace = cullFace;
  14212. }
  14213. // Z offset
  14214. this.setZOffset(zOffset);
  14215. // Front face
  14216. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14217. if (this._depthCullingState.frontFace !== frontFace || force) {
  14218. this._depthCullingState.frontFace = frontFace;
  14219. }
  14220. };
  14221. /**
  14222. * Set the z offset to apply to current rendering
  14223. * @param value defines the offset to apply
  14224. */
  14225. Engine.prototype.setZOffset = function (value) {
  14226. this._depthCullingState.zOffset = value;
  14227. };
  14228. /**
  14229. * Gets the current value of the zOffset
  14230. * @returns the current zOffset state
  14231. */
  14232. Engine.prototype.getZOffset = function () {
  14233. return this._depthCullingState.zOffset;
  14234. };
  14235. /**
  14236. * Enable or disable depth buffering
  14237. * @param enable defines the state to set
  14238. */
  14239. Engine.prototype.setDepthBuffer = function (enable) {
  14240. this._depthCullingState.depthTest = enable;
  14241. };
  14242. /**
  14243. * Gets a boolean indicating if depth writing is enabled
  14244. * @returns the current depth writing state
  14245. */
  14246. Engine.prototype.getDepthWrite = function () {
  14247. return this._depthCullingState.depthMask;
  14248. };
  14249. /**
  14250. * Enable or disable depth writing
  14251. * @param enable defines the state to set
  14252. */
  14253. Engine.prototype.setDepthWrite = function (enable) {
  14254. this._depthCullingState.depthMask = enable;
  14255. };
  14256. /**
  14257. * Enable or disable color writing
  14258. * @param enable defines the state to set
  14259. */
  14260. Engine.prototype.setColorWrite = function (enable) {
  14261. this._gl.colorMask(enable, enable, enable, enable);
  14262. this._colorWrite = enable;
  14263. };
  14264. /**
  14265. * Gets a boolean indicating if color writing is enabled
  14266. * @returns the current color writing state
  14267. */
  14268. Engine.prototype.getColorWrite = function () {
  14269. return this._colorWrite;
  14270. };
  14271. /**
  14272. * Sets alpha constants used by some alpha blending modes
  14273. * @param r defines the red component
  14274. * @param g defines the green component
  14275. * @param b defines the blue component
  14276. * @param a defines the alpha component
  14277. */
  14278. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14279. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14280. };
  14281. /**
  14282. * Sets the current alpha mode
  14283. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14284. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14285. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14286. */
  14287. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14288. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14289. if (this._alphaMode === mode) {
  14290. return;
  14291. }
  14292. switch (mode) {
  14293. case Engine.ALPHA_DISABLE:
  14294. this._alphaState.alphaBlend = false;
  14295. break;
  14296. case Engine.ALPHA_PREMULTIPLIED:
  14297. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14298. this._alphaState.alphaBlend = true;
  14299. break;
  14300. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14301. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14302. this._alphaState.alphaBlend = true;
  14303. break;
  14304. case Engine.ALPHA_COMBINE:
  14305. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14306. this._alphaState.alphaBlend = true;
  14307. break;
  14308. case Engine.ALPHA_ONEONE:
  14309. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14310. this._alphaState.alphaBlend = true;
  14311. break;
  14312. case Engine.ALPHA_ADD:
  14313. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14314. this._alphaState.alphaBlend = true;
  14315. break;
  14316. case Engine.ALPHA_SUBTRACT:
  14317. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14318. this._alphaState.alphaBlend = true;
  14319. break;
  14320. case Engine.ALPHA_MULTIPLY:
  14321. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14322. this._alphaState.alphaBlend = true;
  14323. break;
  14324. case Engine.ALPHA_MAXIMIZED:
  14325. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14326. this._alphaState.alphaBlend = true;
  14327. break;
  14328. case Engine.ALPHA_INTERPOLATE:
  14329. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14330. this._alphaState.alphaBlend = true;
  14331. break;
  14332. case Engine.ALPHA_SCREENMODE:
  14333. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14334. this._alphaState.alphaBlend = true;
  14335. break;
  14336. }
  14337. if (!noDepthWriteChange) {
  14338. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14339. }
  14340. this._alphaMode = mode;
  14341. };
  14342. /**
  14343. * Gets the current alpha mode
  14344. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14345. * @returns the current alpha mode
  14346. */
  14347. Engine.prototype.getAlphaMode = function () {
  14348. return this._alphaMode;
  14349. };
  14350. // Textures
  14351. /**
  14352. * Force the entire cache to be cleared
  14353. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14354. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14355. */
  14356. Engine.prototype.wipeCaches = function (bruteForce) {
  14357. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14358. return;
  14359. }
  14360. this._currentEffect = null;
  14361. if (bruteForce) {
  14362. this.resetTextureCache();
  14363. this._currentProgram = null;
  14364. this._stencilState.reset();
  14365. this._depthCullingState.reset();
  14366. this.setDepthFunctionToLessOrEqual();
  14367. this._alphaState.reset();
  14368. }
  14369. this._resetVertexBufferBinding();
  14370. this._cachedIndexBuffer = null;
  14371. this._cachedEffectForVertexBuffers = null;
  14372. this._unbindVertexArrayObject();
  14373. this.bindIndexBuffer(null);
  14374. };
  14375. /**
  14376. * Set the compressed texture format to use, based on the formats you have, and the formats
  14377. * supported by the hardware / browser.
  14378. *
  14379. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14380. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14381. * to API arguments needed to compressed textures. This puts the burden on the container
  14382. * generator to house the arcane code for determining these for current & future formats.
  14383. *
  14384. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14385. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14386. *
  14387. * Note: The result of this call is not taken into account when a texture is base64.
  14388. *
  14389. * @param formatsAvailable defines the list of those format families you have created
  14390. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14391. *
  14392. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14393. * @returns The extension selected.
  14394. */
  14395. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14396. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14397. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14398. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14399. return this._textureFormatInUse = this._texturesSupported[i];
  14400. }
  14401. }
  14402. }
  14403. // actively set format to nothing, to allow this to be called more than once
  14404. // and possibly fail the 2nd time
  14405. this._textureFormatInUse = null;
  14406. return null;
  14407. };
  14408. /** @hidden */
  14409. Engine.prototype._createTexture = function () {
  14410. var texture = this._gl.createTexture();
  14411. if (!texture) {
  14412. throw new Error("Unable to create texture");
  14413. }
  14414. return texture;
  14415. };
  14416. /**
  14417. * Usually called from BABYLON.Texture.ts.
  14418. * Passed information to create a WebGLTexture
  14419. * @param urlArg defines a value which contains one of the following:
  14420. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14421. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14422. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14423. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14424. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14425. * @param scene needed for loading to the correct scene
  14426. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14427. * @param onLoad optional callback to be called upon successful completion
  14428. * @param onError optional callback to be called upon failure
  14429. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14430. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14431. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14432. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14433. */
  14434. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14435. var _this = this;
  14436. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14437. if (onLoad === void 0) { onLoad = null; }
  14438. if (onError === void 0) { onError = null; }
  14439. if (buffer === void 0) { buffer = null; }
  14440. if (fallback === void 0) { fallback = null; }
  14441. if (format === void 0) { format = null; }
  14442. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14443. var fromData = url.substr(0, 5) === "data:";
  14444. var fromBlob = url.substr(0, 5) === "blob:";
  14445. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14446. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14447. // establish the file extension, if possible
  14448. var lastDot = url.lastIndexOf('.');
  14449. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14450. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14451. var isTGA = (extension.indexOf(".tga") === 0);
  14452. // determine if a ktx file should be substituted
  14453. var isKTX = false;
  14454. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14455. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14456. isKTX = true;
  14457. }
  14458. if (scene) {
  14459. scene._addPendingData(texture);
  14460. }
  14461. texture.url = url;
  14462. texture.generateMipMaps = !noMipmap;
  14463. texture.samplingMode = samplingMode;
  14464. texture.invertY = invertY;
  14465. if (!this._doNotHandleContextLost) {
  14466. // Keep a link to the buffer only if we plan to handle context lost
  14467. texture._buffer = buffer;
  14468. }
  14469. var onLoadObserver = null;
  14470. if (onLoad && !fallback) {
  14471. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14472. }
  14473. if (!fallback)
  14474. this._internalTexturesCache.push(texture);
  14475. var onerror = function (message, exception) {
  14476. if (scene) {
  14477. scene._removePendingData(texture);
  14478. }
  14479. if (onLoadObserver) {
  14480. texture.onLoadedObservable.remove(onLoadObserver);
  14481. }
  14482. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14483. if (isKTX) {
  14484. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14485. }
  14486. else if (BABYLON.Tools.UseFallbackTexture) {
  14487. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14488. }
  14489. if (onError) {
  14490. onError(message || "Unknown error", exception);
  14491. }
  14492. };
  14493. var callback = null;
  14494. // processing for non-image formats
  14495. if (isKTX || isTGA || isDDS) {
  14496. if (isKTX) {
  14497. callback = function (data) {
  14498. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14499. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14500. ktx.uploadLevels(_this._gl, !noMipmap);
  14501. return false;
  14502. }, samplingMode);
  14503. };
  14504. }
  14505. else if (isTGA) {
  14506. callback = function (arrayBuffer) {
  14507. var data = new Uint8Array(arrayBuffer);
  14508. var header = BABYLON.TGATools.GetTGAHeader(data);
  14509. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14510. BABYLON.TGATools.UploadContent(_this._gl, data);
  14511. return false;
  14512. }, samplingMode);
  14513. };
  14514. }
  14515. else if (isDDS) {
  14516. callback = function (data) {
  14517. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14518. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14519. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14520. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14521. return false;
  14522. }, samplingMode);
  14523. };
  14524. }
  14525. if (!buffer) {
  14526. this._loadFile(url, function (data) {
  14527. if (callback) {
  14528. callback(data);
  14529. }
  14530. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14531. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14532. });
  14533. }
  14534. else {
  14535. if (callback) {
  14536. callback(buffer);
  14537. }
  14538. }
  14539. // image format processing
  14540. }
  14541. else {
  14542. var onload = function (img) {
  14543. if (fromBlob && !_this._doNotHandleContextLost) {
  14544. // We need to store the image if we need to rebuild the texture
  14545. // in case of a webgl context lost
  14546. texture._buffer = img;
  14547. }
  14548. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14549. var gl = _this._gl;
  14550. var isPot = (img.width === potWidth && img.height === potHeight);
  14551. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14552. if (isPot) {
  14553. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14554. return false;
  14555. }
  14556. // Using shaders to rescale because canvas.drawImage is lossy
  14557. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14558. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14559. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14560. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14561. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14562. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14563. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14564. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14565. _this._releaseTexture(source);
  14566. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14567. continuationCallback();
  14568. });
  14569. return true;
  14570. }, samplingMode);
  14571. };
  14572. if (!fromData || isBase64)
  14573. if (buffer instanceof HTMLImageElement) {
  14574. onload(buffer);
  14575. }
  14576. else {
  14577. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14578. }
  14579. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14580. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14581. else
  14582. onload(buffer);
  14583. }
  14584. return texture;
  14585. };
  14586. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14587. var _this = this;
  14588. var rtt = this.createRenderTargetTexture({
  14589. width: destination.width,
  14590. height: destination.height,
  14591. }, {
  14592. generateMipMaps: false,
  14593. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14594. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14595. generateDepthBuffer: false,
  14596. generateStencilBuffer: false
  14597. });
  14598. if (!this._rescalePostProcess) {
  14599. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14600. }
  14601. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14602. _this._rescalePostProcess.onApply = function (effect) {
  14603. effect._bindTexture("textureSampler", source);
  14604. };
  14605. var hostingScene = scene;
  14606. if (!hostingScene) {
  14607. hostingScene = _this.scenes[_this.scenes.length - 1];
  14608. }
  14609. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14610. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14611. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14612. _this.unBindFramebuffer(rtt);
  14613. _this._releaseTexture(rtt);
  14614. if (onComplete) {
  14615. onComplete();
  14616. }
  14617. });
  14618. };
  14619. /**
  14620. * Update a raw texture
  14621. * @param texture defines the texture to update
  14622. * @param data defines the data to store in the texture
  14623. * @param format defines the format of the data
  14624. * @param invertY defines if data must be stored with Y axis inverted
  14625. * @param compression defines the compression used (null by default)
  14626. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14627. */
  14628. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14629. if (compression === void 0) { compression = null; }
  14630. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14631. if (!texture) {
  14632. return;
  14633. }
  14634. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14635. var internalFormat = this._getInternalFormat(format);
  14636. var textureType = this._getWebGLTextureType(type);
  14637. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14638. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14639. if (!this._doNotHandleContextLost) {
  14640. texture._bufferView = data;
  14641. texture.format = format;
  14642. texture.type = type;
  14643. texture.invertY = invertY;
  14644. texture._compression = compression;
  14645. }
  14646. if (texture.width % 4 !== 0) {
  14647. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14648. }
  14649. if (compression && data) {
  14650. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14651. }
  14652. else {
  14653. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14654. }
  14655. if (texture.generateMipMaps) {
  14656. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14657. }
  14658. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14659. // this.resetTextureCache();
  14660. texture.isReady = true;
  14661. };
  14662. /**
  14663. * Creates a raw texture
  14664. * @param data defines the data to store in the texture
  14665. * @param width defines the width of the texture
  14666. * @param height defines the height of the texture
  14667. * @param format defines the format of the data
  14668. * @param generateMipMaps defines if the engine should generate the mip levels
  14669. * @param invertY defines if data must be stored with Y axis inverted
  14670. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14671. * @param compression defines the compression used (null by default)
  14672. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14673. * @returns the raw texture inside an InternalTexture
  14674. */
  14675. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14676. if (compression === void 0) { compression = null; }
  14677. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14678. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14679. texture.baseWidth = width;
  14680. texture.baseHeight = height;
  14681. texture.width = width;
  14682. texture.height = height;
  14683. texture.format = format;
  14684. texture.generateMipMaps = generateMipMaps;
  14685. texture.samplingMode = samplingMode;
  14686. texture.invertY = invertY;
  14687. texture._compression = compression;
  14688. texture.type = type;
  14689. if (!this._doNotHandleContextLost) {
  14690. texture._bufferView = data;
  14691. }
  14692. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14693. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14694. // Filters
  14695. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14696. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14697. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14698. if (generateMipMaps) {
  14699. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14700. }
  14701. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14702. this._internalTexturesCache.push(texture);
  14703. return texture;
  14704. };
  14705. /**
  14706. * Creates a dynamic texture
  14707. * @param width defines the width of the texture
  14708. * @param height defines the height of the texture
  14709. * @param generateMipMaps defines if the engine should generate the mip levels
  14710. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14711. * @returns the dynamic texture inside an InternalTexture
  14712. */
  14713. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14714. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14715. texture.baseWidth = width;
  14716. texture.baseHeight = height;
  14717. if (generateMipMaps) {
  14718. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14719. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14720. }
  14721. // this.resetTextureCache();
  14722. texture.width = width;
  14723. texture.height = height;
  14724. texture.isReady = false;
  14725. texture.generateMipMaps = generateMipMaps;
  14726. texture.samplingMode = samplingMode;
  14727. this.updateTextureSamplingMode(samplingMode, texture);
  14728. this._internalTexturesCache.push(texture);
  14729. return texture;
  14730. };
  14731. /**
  14732. * Update the sampling mode of a given texture
  14733. * @param samplingMode defines the required sampling mode
  14734. * @param texture defines the texture to update
  14735. */
  14736. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14737. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14738. if (texture.isCube) {
  14739. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14740. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14741. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14742. }
  14743. else if (texture.is3D) {
  14744. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14745. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14746. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14747. }
  14748. else {
  14749. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14750. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14751. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14752. }
  14753. texture.samplingMode = samplingMode;
  14754. };
  14755. /**
  14756. * Update the content of a dynamic texture
  14757. * @param texture defines the texture to update
  14758. * @param canvas defines the canvas containing the source
  14759. * @param invertY defines if data must be stored with Y axis inverted
  14760. * @param premulAlpha defines if alpha is stored as premultiplied
  14761. * @param format defines the format of the data
  14762. */
  14763. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14764. if (premulAlpha === void 0) { premulAlpha = false; }
  14765. if (!texture) {
  14766. return;
  14767. }
  14768. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14769. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14770. if (premulAlpha) {
  14771. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14772. }
  14773. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14774. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14775. if (texture.generateMipMaps) {
  14776. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14777. }
  14778. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14779. if (premulAlpha) {
  14780. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14781. }
  14782. texture.isReady = true;
  14783. };
  14784. /**
  14785. * Update a video texture
  14786. * @param texture defines the texture to update
  14787. * @param video defines the video element to use
  14788. * @param invertY defines if data must be stored with Y axis inverted
  14789. */
  14790. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14791. if (!texture || texture._isDisabled) {
  14792. return;
  14793. }
  14794. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14795. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14796. try {
  14797. // Testing video texture support
  14798. if (this._videoTextureSupported === undefined) {
  14799. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14800. if (this._gl.getError() !== 0) {
  14801. this._videoTextureSupported = false;
  14802. }
  14803. else {
  14804. this._videoTextureSupported = true;
  14805. }
  14806. }
  14807. // Copy video through the current working canvas if video texture is not supported
  14808. if (!this._videoTextureSupported) {
  14809. if (!texture._workingCanvas) {
  14810. texture._workingCanvas = document.createElement("canvas");
  14811. var context = texture._workingCanvas.getContext("2d");
  14812. if (!context) {
  14813. throw new Error("Unable to get 2d context");
  14814. }
  14815. texture._workingContext = context;
  14816. texture._workingCanvas.width = texture.width;
  14817. texture._workingCanvas.height = texture.height;
  14818. }
  14819. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14820. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14821. }
  14822. else {
  14823. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14824. }
  14825. if (texture.generateMipMaps) {
  14826. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14827. }
  14828. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14829. // this.resetTextureCache();
  14830. texture.isReady = true;
  14831. }
  14832. catch (ex) {
  14833. // Something unexpected
  14834. // Let's disable the texture
  14835. texture._isDisabled = true;
  14836. }
  14837. };
  14838. /**
  14839. * Updates a depth texture Comparison Mode and Function.
  14840. * If the comparison Function is equal to 0, the mode will be set to none.
  14841. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14842. * @param texture The texture to set the comparison function for
  14843. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14844. */
  14845. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14846. if (this.webGLVersion === 1) {
  14847. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14848. return;
  14849. }
  14850. var gl = this._gl;
  14851. if (texture.isCube) {
  14852. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14853. if (comparisonFunction === 0) {
  14854. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14855. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14856. }
  14857. else {
  14858. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14859. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14860. }
  14861. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14862. }
  14863. else {
  14864. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14865. if (comparisonFunction === 0) {
  14866. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14867. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14868. }
  14869. else {
  14870. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14871. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14872. }
  14873. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14874. }
  14875. texture._comparisonFunction = comparisonFunction;
  14876. };
  14877. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14878. var width = size.width || size;
  14879. var height = size.height || size;
  14880. internalTexture.baseWidth = width;
  14881. internalTexture.baseHeight = height;
  14882. internalTexture.width = width;
  14883. internalTexture.height = height;
  14884. internalTexture.isReady = true;
  14885. internalTexture.samples = 1;
  14886. internalTexture.generateMipMaps = false;
  14887. internalTexture._generateDepthBuffer = true;
  14888. internalTexture._generateStencilBuffer = generateStencil;
  14889. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14890. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14891. internalTexture._comparisonFunction = comparisonFunction;
  14892. var gl = this._gl;
  14893. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14894. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14895. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14896. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14897. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14898. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14899. if (comparisonFunction === 0) {
  14900. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14901. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14902. }
  14903. else {
  14904. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14905. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14906. }
  14907. };
  14908. /**
  14909. * Creates a depth stencil texture.
  14910. * This is only available in WebGL 2 or with the depth texture extension available.
  14911. * @param size The size of face edge in the texture.
  14912. * @param options The options defining the texture.
  14913. * @returns The texture
  14914. */
  14915. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14916. if (options.isCube) {
  14917. var width = size.width || size;
  14918. return this._createDepthStencilCubeTexture(width, options);
  14919. }
  14920. else {
  14921. return this._createDepthStencilTexture(size, options);
  14922. }
  14923. };
  14924. /**
  14925. * Creates a depth stencil texture.
  14926. * This is only available in WebGL 2 or with the depth texture extension available.
  14927. * @param size The size of face edge in the texture.
  14928. * @param options The options defining the texture.
  14929. * @returns The texture
  14930. */
  14931. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14932. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14933. if (!this._caps.depthTextureExtension) {
  14934. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14935. return internalTexture;
  14936. }
  14937. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14938. var gl = this._gl;
  14939. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14940. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14941. if (this.webGLVersion > 1) {
  14942. if (internalOptions.generateStencil) {
  14943. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14944. }
  14945. else {
  14946. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14947. }
  14948. }
  14949. else {
  14950. if (internalOptions.generateStencil) {
  14951. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14952. }
  14953. else {
  14954. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14955. }
  14956. }
  14957. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14958. return internalTexture;
  14959. };
  14960. /**
  14961. * Creates a depth stencil cube texture.
  14962. * This is only available in WebGL 2.
  14963. * @param size The size of face edge in the cube texture.
  14964. * @param options The options defining the cube texture.
  14965. * @returns The cube texture
  14966. */
  14967. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14968. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14969. internalTexture.isCube = true;
  14970. if (this.webGLVersion === 1) {
  14971. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14972. return internalTexture;
  14973. }
  14974. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14975. var gl = this._gl;
  14976. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14977. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14978. // Create the depth/stencil buffer
  14979. for (var face = 0; face < 6; face++) {
  14980. if (internalOptions.generateStencil) {
  14981. 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);
  14982. }
  14983. else {
  14984. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14985. }
  14986. }
  14987. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14988. return internalTexture;
  14989. };
  14990. /**
  14991. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  14992. * @param renderTarget The render target to set the frame buffer for
  14993. */
  14994. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  14995. // Create the framebuffer
  14996. var internalTexture = renderTarget.getInternalTexture();
  14997. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  14998. return;
  14999. }
  15000. var gl = this._gl;
  15001. var depthStencilTexture = renderTarget.depthStencilTexture;
  15002. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15003. if (depthStencilTexture.isCube) {
  15004. if (depthStencilTexture._generateStencilBuffer) {
  15005. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15006. }
  15007. else {
  15008. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15009. }
  15010. }
  15011. else {
  15012. if (depthStencilTexture._generateStencilBuffer) {
  15013. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15014. }
  15015. else {
  15016. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15017. }
  15018. }
  15019. this.bindUnboundFramebuffer(null);
  15020. };
  15021. /**
  15022. * Creates a new render target texture
  15023. * @param size defines the size of the texture
  15024. * @param options defines the options used to create the texture
  15025. * @returns a new render target texture stored in an InternalTexture
  15026. */
  15027. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15028. var fullOptions = new RenderTargetCreationOptions();
  15029. if (options !== undefined && typeof options === "object") {
  15030. fullOptions.generateMipMaps = options.generateMipMaps;
  15031. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15032. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15033. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15034. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15035. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15036. }
  15037. else {
  15038. fullOptions.generateMipMaps = options;
  15039. fullOptions.generateDepthBuffer = true;
  15040. fullOptions.generateStencilBuffer = false;
  15041. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15042. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15043. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15044. }
  15045. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15046. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15047. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15048. }
  15049. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15050. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15051. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15052. }
  15053. var gl = this._gl;
  15054. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15055. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15056. var width = size.width || size;
  15057. var height = size.height || size;
  15058. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15059. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15060. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15061. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15062. }
  15063. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15064. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15065. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15066. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15067. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15068. // Create the framebuffer
  15069. var framebuffer = gl.createFramebuffer();
  15070. this.bindUnboundFramebuffer(framebuffer);
  15071. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15072. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15073. if (fullOptions.generateMipMaps) {
  15074. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15075. }
  15076. // Unbind
  15077. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15078. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15079. this.bindUnboundFramebuffer(null);
  15080. texture._framebuffer = framebuffer;
  15081. texture.baseWidth = width;
  15082. texture.baseHeight = height;
  15083. texture.width = width;
  15084. texture.height = height;
  15085. texture.isReady = true;
  15086. texture.samples = 1;
  15087. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15088. texture.samplingMode = fullOptions.samplingMode;
  15089. texture.type = fullOptions.type;
  15090. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15091. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15092. // this.resetTextureCache();
  15093. this._internalTexturesCache.push(texture);
  15094. return texture;
  15095. };
  15096. /**
  15097. * Create a multi render target texture
  15098. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15099. * @param size defines the size of the texture
  15100. * @param options defines the creation options
  15101. * @returns the cube texture as an InternalTexture
  15102. */
  15103. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15104. var generateMipMaps = false;
  15105. var generateDepthBuffer = true;
  15106. var generateStencilBuffer = false;
  15107. var generateDepthTexture = false;
  15108. var textureCount = 1;
  15109. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15110. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15111. var types = new Array();
  15112. var samplingModes = new Array();
  15113. if (options !== undefined) {
  15114. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15115. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15116. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15117. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15118. textureCount = options.textureCount || 1;
  15119. if (options.types) {
  15120. types = options.types;
  15121. }
  15122. if (options.samplingModes) {
  15123. samplingModes = options.samplingModes;
  15124. }
  15125. }
  15126. var gl = this._gl;
  15127. // Create the framebuffer
  15128. var framebuffer = gl.createFramebuffer();
  15129. this.bindUnboundFramebuffer(framebuffer);
  15130. var width = size.width || size;
  15131. var height = size.height || size;
  15132. var textures = [];
  15133. var attachments = [];
  15134. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15135. for (var i = 0; i < textureCount; i++) {
  15136. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15137. var type = types[i] || defaultType;
  15138. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15139. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15140. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15141. }
  15142. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15143. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15144. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15145. }
  15146. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15147. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15148. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15149. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15150. }
  15151. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15152. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15153. textures.push(texture);
  15154. attachments.push(attachment);
  15155. gl.activeTexture(gl["TEXTURE" + i]);
  15156. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15157. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15158. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15159. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15160. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15161. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15162. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15163. if (generateMipMaps) {
  15164. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15165. }
  15166. // Unbind
  15167. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15168. texture._framebuffer = framebuffer;
  15169. texture._depthStencilBuffer = depthStencilBuffer;
  15170. texture.baseWidth = width;
  15171. texture.baseHeight = height;
  15172. texture.width = width;
  15173. texture.height = height;
  15174. texture.isReady = true;
  15175. texture.samples = 1;
  15176. texture.generateMipMaps = generateMipMaps;
  15177. texture.samplingMode = samplingMode;
  15178. texture.type = type;
  15179. texture._generateDepthBuffer = generateDepthBuffer;
  15180. texture._generateStencilBuffer = generateStencilBuffer;
  15181. texture._attachments = attachments;
  15182. this._internalTexturesCache.push(texture);
  15183. }
  15184. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15185. // Depth texture
  15186. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15187. gl.activeTexture(gl.TEXTURE0);
  15188. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15189. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15190. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15191. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15192. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15193. 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);
  15194. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15195. depthTexture._framebuffer = framebuffer;
  15196. depthTexture.baseWidth = width;
  15197. depthTexture.baseHeight = height;
  15198. depthTexture.width = width;
  15199. depthTexture.height = height;
  15200. depthTexture.isReady = true;
  15201. depthTexture.samples = 1;
  15202. depthTexture.generateMipMaps = generateMipMaps;
  15203. depthTexture.samplingMode = gl.NEAREST;
  15204. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15205. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15206. textures.push(depthTexture);
  15207. this._internalTexturesCache.push(depthTexture);
  15208. }
  15209. gl.drawBuffers(attachments);
  15210. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15211. this.bindUnboundFramebuffer(null);
  15212. this.resetTextureCache();
  15213. return textures;
  15214. };
  15215. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15216. if (samples === void 0) { samples = 1; }
  15217. var depthStencilBuffer = null;
  15218. var gl = this._gl;
  15219. // Create the depth/stencil buffer
  15220. if (generateStencilBuffer) {
  15221. depthStencilBuffer = gl.createRenderbuffer();
  15222. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15223. if (samples > 1) {
  15224. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15225. }
  15226. else {
  15227. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15228. }
  15229. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15230. }
  15231. else if (generateDepthBuffer) {
  15232. depthStencilBuffer = gl.createRenderbuffer();
  15233. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15234. if (samples > 1) {
  15235. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15236. }
  15237. else {
  15238. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15239. }
  15240. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15241. }
  15242. return depthStencilBuffer;
  15243. };
  15244. /**
  15245. * Updates the sample count of a render target texture
  15246. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15247. * @param texture defines the texture to update
  15248. * @param samples defines the sample count to set
  15249. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15250. */
  15251. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15252. if (this.webGLVersion < 2 || !texture) {
  15253. return 1;
  15254. }
  15255. if (texture.samples === samples) {
  15256. return samples;
  15257. }
  15258. var gl = this._gl;
  15259. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15260. // Dispose previous render buffers
  15261. if (texture._depthStencilBuffer) {
  15262. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15263. texture._depthStencilBuffer = null;
  15264. }
  15265. if (texture._MSAAFramebuffer) {
  15266. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15267. texture._MSAAFramebuffer = null;
  15268. }
  15269. if (texture._MSAARenderBuffer) {
  15270. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15271. texture._MSAARenderBuffer = null;
  15272. }
  15273. if (samples > 1) {
  15274. var framebuffer = gl.createFramebuffer();
  15275. if (!framebuffer) {
  15276. throw new Error("Unable to create multi sampled framebuffer");
  15277. }
  15278. texture._MSAAFramebuffer = framebuffer;
  15279. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15280. var colorRenderbuffer = gl.createRenderbuffer();
  15281. if (!colorRenderbuffer) {
  15282. throw new Error("Unable to create multi sampled framebuffer");
  15283. }
  15284. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15285. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15286. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15287. texture._MSAARenderBuffer = colorRenderbuffer;
  15288. }
  15289. else {
  15290. this.bindUnboundFramebuffer(texture._framebuffer);
  15291. }
  15292. texture.samples = samples;
  15293. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15294. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15295. this.bindUnboundFramebuffer(null);
  15296. return samples;
  15297. };
  15298. /**
  15299. * Update the sample count for a given multiple render target texture
  15300. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15301. * @param textures defines the textures to update
  15302. * @param samples defines the sample count to set
  15303. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15304. */
  15305. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15306. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15307. return 1;
  15308. }
  15309. if (textures[0].samples === samples) {
  15310. return samples;
  15311. }
  15312. var gl = this._gl;
  15313. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15314. // Dispose previous render buffers
  15315. if (textures[0]._depthStencilBuffer) {
  15316. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15317. textures[0]._depthStencilBuffer = null;
  15318. }
  15319. if (textures[0]._MSAAFramebuffer) {
  15320. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15321. textures[0]._MSAAFramebuffer = null;
  15322. }
  15323. for (var i = 0; i < textures.length; i++) {
  15324. if (textures[i]._MSAARenderBuffer) {
  15325. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15326. textures[i]._MSAARenderBuffer = null;
  15327. }
  15328. }
  15329. if (samples > 1) {
  15330. var framebuffer = gl.createFramebuffer();
  15331. if (!framebuffer) {
  15332. throw new Error("Unable to create multi sampled framebuffer");
  15333. }
  15334. this.bindUnboundFramebuffer(framebuffer);
  15335. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15336. var attachments = [];
  15337. for (var i = 0; i < textures.length; i++) {
  15338. var texture = textures[i];
  15339. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15340. var colorRenderbuffer = gl.createRenderbuffer();
  15341. if (!colorRenderbuffer) {
  15342. throw new Error("Unable to create multi sampled framebuffer");
  15343. }
  15344. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15345. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15346. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15347. texture._MSAAFramebuffer = framebuffer;
  15348. texture._MSAARenderBuffer = colorRenderbuffer;
  15349. texture.samples = samples;
  15350. texture._depthStencilBuffer = depthStencilBuffer;
  15351. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15352. attachments.push(attachment);
  15353. }
  15354. gl.drawBuffers(attachments);
  15355. }
  15356. else {
  15357. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15358. }
  15359. this.bindUnboundFramebuffer(null);
  15360. return samples;
  15361. };
  15362. /** @hidden */
  15363. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15364. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15365. };
  15366. /** @hidden */
  15367. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15368. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15369. };
  15370. /**
  15371. * Creates a new render target cube texture
  15372. * @param size defines the size of the texture
  15373. * @param options defines the options used to create the texture
  15374. * @returns a new render target cube texture stored in an InternalTexture
  15375. */
  15376. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15377. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15378. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15379. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15380. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15381. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15382. }
  15383. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15384. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15385. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15386. }
  15387. var gl = this._gl;
  15388. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15389. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15390. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15391. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15392. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15393. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15394. }
  15395. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15396. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15397. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15398. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15399. for (var face = 0; face < 6; face++) {
  15400. 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);
  15401. }
  15402. // Create the framebuffer
  15403. var framebuffer = gl.createFramebuffer();
  15404. this.bindUnboundFramebuffer(framebuffer);
  15405. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15406. // MipMaps
  15407. if (fullOptions.generateMipMaps) {
  15408. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15409. }
  15410. // Unbind
  15411. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15412. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15413. this.bindUnboundFramebuffer(null);
  15414. texture._framebuffer = framebuffer;
  15415. texture.width = size;
  15416. texture.height = size;
  15417. texture.isReady = true;
  15418. texture.isCube = true;
  15419. texture.samples = 1;
  15420. texture.generateMipMaps = fullOptions.generateMipMaps;
  15421. texture.samplingMode = fullOptions.samplingMode;
  15422. texture.type = fullOptions.type;
  15423. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15424. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15425. this._internalTexturesCache.push(texture);
  15426. return texture;
  15427. };
  15428. /**
  15429. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15430. * @param rootUrl defines the url where the file to load is located
  15431. * @param scene defines the current scene
  15432. * @param scale defines scale to apply to the mip map selection
  15433. * @param offset defines offset to apply to the mip map selection
  15434. * @param onLoad defines an optional callback raised when the texture is loaded
  15435. * @param onError defines an optional callback raised if there is an issue to load the texture
  15436. * @param format defines the format of the data
  15437. * @param forcedExtension defines the extension to use to pick the right loader
  15438. * @returns the cube texture as an InternalTexture
  15439. */
  15440. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15441. var _this = this;
  15442. if (onLoad === void 0) { onLoad = null; }
  15443. if (onError === void 0) { onError = null; }
  15444. if (forcedExtension === void 0) { forcedExtension = null; }
  15445. var callback = function (loadData) {
  15446. if (!loadData) {
  15447. if (onLoad) {
  15448. onLoad(null);
  15449. }
  15450. return;
  15451. }
  15452. var texture = loadData.texture;
  15453. if (loadData.info.sphericalPolynomial) {
  15454. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15455. }
  15456. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15457. texture._lodGenerationScale = scale;
  15458. texture._lodGenerationOffset = offset;
  15459. if (_this._caps.textureLOD) {
  15460. // Do not add extra process if texture lod is supported.
  15461. if (onLoad) {
  15462. onLoad(texture);
  15463. }
  15464. return;
  15465. }
  15466. var mipSlices = 3;
  15467. var gl = _this._gl;
  15468. var width = loadData.width;
  15469. if (!width) {
  15470. return;
  15471. }
  15472. var textures = [];
  15473. for (var i = 0; i < mipSlices; i++) {
  15474. //compute LOD from even spacing in smoothness (matching shader calculation)
  15475. var smoothness = i / (mipSlices - 1);
  15476. var roughness = 1 - smoothness;
  15477. var minLODIndex = offset; // roughness = 0
  15478. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15479. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15480. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15481. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15482. glTextureFromLod.isCube = true;
  15483. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15484. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15485. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15486. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15487. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15488. if (loadData.isDDS) {
  15489. var info = loadData.info;
  15490. var data = loadData.data;
  15491. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15492. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15493. }
  15494. else {
  15495. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15496. }
  15497. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15498. // Wrap in a base texture for easy binding.
  15499. var lodTexture = new BABYLON.BaseTexture(scene);
  15500. lodTexture.isCube = true;
  15501. lodTexture._texture = glTextureFromLod;
  15502. glTextureFromLod.isReady = true;
  15503. textures.push(lodTexture);
  15504. }
  15505. texture._lodTextureHigh = textures[2];
  15506. texture._lodTextureMid = textures[1];
  15507. texture._lodTextureLow = textures[0];
  15508. if (onLoad) {
  15509. onLoad(texture);
  15510. }
  15511. };
  15512. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, true);
  15513. };
  15514. /**
  15515. * Creates a cube texture
  15516. * @param rootUrl defines the url where the files to load is located
  15517. * @param scene defines the current scene
  15518. * @param files defines the list of files to load (1 per face)
  15519. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15520. * @param onLoad defines an optional callback raised when the texture is loaded
  15521. * @param onError defines an optional callback raised if there is an issue to load the texture
  15522. * @param format defines the format of the data
  15523. * @param forcedExtension defines the extension to use to pick the right loader
  15524. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15525. * @returns the cube texture as an InternalTexture
  15526. */
  15527. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15528. var _this = this;
  15529. if (onLoad === void 0) { onLoad = null; }
  15530. if (onError === void 0) { onError = null; }
  15531. if (forcedExtension === void 0) { forcedExtension = null; }
  15532. if (createPolynomials === void 0) { createPolynomials = false; }
  15533. var gl = this._gl;
  15534. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15535. texture.isCube = true;
  15536. texture.url = rootUrl;
  15537. texture.generateMipMaps = !noMipmap;
  15538. if (!this._doNotHandleContextLost) {
  15539. texture._extension = forcedExtension;
  15540. texture._files = files;
  15541. }
  15542. var isKTX = false;
  15543. var isDDS = false;
  15544. var lastDot = rootUrl.lastIndexOf('.');
  15545. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15546. if (this._textureFormatInUse) {
  15547. extension = this._textureFormatInUse;
  15548. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15549. isKTX = true;
  15550. }
  15551. else {
  15552. isDDS = (extension === ".dds");
  15553. }
  15554. var onerror = function (request, exception) {
  15555. if (onError && request) {
  15556. onError(request.status + " " + request.statusText, exception);
  15557. }
  15558. };
  15559. if (isKTX) {
  15560. this._loadFile(rootUrl, function (data) {
  15561. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15562. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15563. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15564. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15565. ktx.uploadLevels(_this._gl, !noMipmap);
  15566. _this.setCubeMapTextureParams(gl, loadMipmap);
  15567. texture.width = ktx.pixelWidth;
  15568. texture.height = ktx.pixelHeight;
  15569. texture.isReady = true;
  15570. }, undefined, undefined, true, onerror);
  15571. }
  15572. else if (isDDS) {
  15573. if (files && files.length === 6) {
  15574. this._cascadeLoadFiles(scene, function (imgs) {
  15575. var info;
  15576. var loadMipmap = false;
  15577. var width = 0;
  15578. for (var index = 0; index < imgs.length; index++) {
  15579. var data = imgs[index];
  15580. info = BABYLON.DDSTools.GetDDSInfo(data);
  15581. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15582. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15583. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15584. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15585. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15586. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15587. }
  15588. texture.width = info.width;
  15589. texture.height = info.height;
  15590. texture.type = info.textureType;
  15591. width = info.width;
  15592. }
  15593. _this.setCubeMapTextureParams(gl, loadMipmap);
  15594. texture.isReady = true;
  15595. if (onLoad) {
  15596. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15597. }
  15598. }, files, onError);
  15599. }
  15600. else {
  15601. this._loadFile(rootUrl, function (data) {
  15602. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15603. if (createPolynomials) {
  15604. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15605. }
  15606. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15607. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15608. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15609. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15610. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15611. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15612. }
  15613. _this.setCubeMapTextureParams(gl, loadMipmap);
  15614. texture.width = info.width;
  15615. texture.height = info.height;
  15616. texture.isReady = true;
  15617. texture.type = info.textureType;
  15618. if (onLoad) {
  15619. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15620. }
  15621. }, undefined, undefined, true, onerror);
  15622. }
  15623. }
  15624. else {
  15625. if (!files) {
  15626. throw new Error("Cannot load cubemap because files were not defined");
  15627. }
  15628. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15629. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15630. var height = width;
  15631. _this._prepareWorkingCanvas();
  15632. if (!_this._workingCanvas || !_this._workingContext) {
  15633. return;
  15634. }
  15635. _this._workingCanvas.width = width;
  15636. _this._workingCanvas.height = height;
  15637. var faces = [
  15638. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15639. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15640. ];
  15641. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15642. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15643. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15644. for (var index = 0; index < faces.length; index++) {
  15645. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15646. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15647. }
  15648. if (!noMipmap) {
  15649. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15650. }
  15651. _this.setCubeMapTextureParams(gl, !noMipmap);
  15652. texture.width = width;
  15653. texture.height = height;
  15654. texture.isReady = true;
  15655. if (format) {
  15656. texture.format = format;
  15657. }
  15658. texture.onLoadedObservable.notifyObservers(texture);
  15659. texture.onLoadedObservable.clear();
  15660. if (onLoad) {
  15661. onLoad();
  15662. }
  15663. }, files, onError);
  15664. }
  15665. this._internalTexturesCache.push(texture);
  15666. return texture;
  15667. };
  15668. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15669. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15670. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15671. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15672. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15673. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15674. // this.resetTextureCache();
  15675. };
  15676. /**
  15677. * Update a raw cube texture
  15678. * @param texture defines the texture to udpdate
  15679. * @param data defines the data to store
  15680. * @param format defines the data format
  15681. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15682. * @param invertY defines if data must be stored with Y axis inverted
  15683. * @param compression defines the compression used (null by default)
  15684. * @param level defines which level of the texture to update
  15685. */
  15686. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15687. if (compression === void 0) { compression = null; }
  15688. if (level === void 0) { level = 0; }
  15689. texture._bufferViewArray = data;
  15690. texture.format = format;
  15691. texture.type = type;
  15692. texture.invertY = invertY;
  15693. texture._compression = compression;
  15694. var gl = this._gl;
  15695. var textureType = this._getWebGLTextureType(type);
  15696. var internalFormat = this._getInternalFormat(format);
  15697. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15698. var needConversion = false;
  15699. if (internalFormat === gl.RGB) {
  15700. internalFormat = gl.RGBA;
  15701. needConversion = true;
  15702. }
  15703. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15704. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15705. if (texture.width % 4 !== 0) {
  15706. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15707. }
  15708. // Data are known to be in +X +Y +Z -X -Y -Z
  15709. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15710. var faceData = data[faceIndex];
  15711. if (compression) {
  15712. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15713. }
  15714. else {
  15715. if (needConversion) {
  15716. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15717. }
  15718. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15719. }
  15720. }
  15721. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15722. if (isPot && texture.generateMipMaps && level === 0) {
  15723. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15724. }
  15725. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15726. // this.resetTextureCache();
  15727. texture.isReady = true;
  15728. };
  15729. /**
  15730. * Creates a new raw cube texture
  15731. * @param data defines the array of data to use to create each face
  15732. * @param size defines the size of the textures
  15733. * @param format defines the format of the data
  15734. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15735. * @param generateMipMaps defines if the engine should generate the mip levels
  15736. * @param invertY defines if data must be stored with Y axis inverted
  15737. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15738. * @param compression defines the compression used (null by default)
  15739. * @returns the cube texture as an InternalTexture
  15740. */
  15741. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15742. if (compression === void 0) { compression = null; }
  15743. var gl = this._gl;
  15744. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15745. texture.isCube = true;
  15746. texture.generateMipMaps = generateMipMaps;
  15747. texture.format = format;
  15748. texture.type = type;
  15749. if (!this._doNotHandleContextLost) {
  15750. texture._bufferViewArray = data;
  15751. }
  15752. var textureType = this._getWebGLTextureType(type);
  15753. var internalFormat = this._getInternalFormat(format);
  15754. if (internalFormat === gl.RGB) {
  15755. internalFormat = gl.RGBA;
  15756. }
  15757. var width = size;
  15758. var height = width;
  15759. texture.width = width;
  15760. texture.height = height;
  15761. // Double check on POT to generate Mips.
  15762. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15763. if (!isPot) {
  15764. generateMipMaps = false;
  15765. }
  15766. // Upload data if needed. The texture won't be ready until then.
  15767. if (data) {
  15768. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15769. }
  15770. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15771. // Filters
  15772. if (data && generateMipMaps) {
  15773. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15774. }
  15775. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15776. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15777. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15778. }
  15779. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15780. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15781. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15782. }
  15783. else {
  15784. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15785. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15786. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15787. }
  15788. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15789. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15790. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15791. return texture;
  15792. };
  15793. /**
  15794. * Creates a new raw cube texture from a specified url
  15795. * @param url defines the url where the data is located
  15796. * @param scene defines the current scene
  15797. * @param size defines the size of the textures
  15798. * @param format defines the format of the data
  15799. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15800. * @param noMipmap defines if the engine should avoid generating the mip levels
  15801. * @param callback defines a callback used to extract texture data from loaded data
  15802. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15803. * @param onLoad defines a callback called when texture is loaded
  15804. * @param onError defines a callback called if there is an error
  15805. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15806. * @param invertY defines if data must be stored with Y axis inverted
  15807. * @returns the cube texture as an InternalTexture
  15808. */
  15809. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15810. var _this = this;
  15811. if (onLoad === void 0) { onLoad = null; }
  15812. if (onError === void 0) { onError = null; }
  15813. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15814. if (invertY === void 0) { invertY = false; }
  15815. var gl = this._gl;
  15816. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15817. scene._addPendingData(texture);
  15818. texture.url = url;
  15819. this._internalTexturesCache.push(texture);
  15820. var onerror = function (request, exception) {
  15821. scene._removePendingData(texture);
  15822. if (onError && request) {
  15823. onError(request.status + " " + request.statusText, exception);
  15824. }
  15825. };
  15826. var internalCallback = function (data) {
  15827. var width = texture.width;
  15828. var faceDataArrays = callback(data);
  15829. if (!faceDataArrays) {
  15830. return;
  15831. }
  15832. if (mipmapGenerator) {
  15833. var textureType = _this._getWebGLTextureType(type);
  15834. var internalFormat = _this._getInternalFormat(format);
  15835. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15836. var needConversion = false;
  15837. if (internalFormat === gl.RGB) {
  15838. internalFormat = gl.RGBA;
  15839. needConversion = true;
  15840. }
  15841. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15842. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15843. var mipData = mipmapGenerator(faceDataArrays);
  15844. for (var level = 0; level < mipData.length; level++) {
  15845. var mipSize = width >> level;
  15846. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15847. var mipFaceData = mipData[level][faceIndex];
  15848. if (needConversion) {
  15849. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15850. }
  15851. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15852. }
  15853. }
  15854. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15855. }
  15856. else {
  15857. texture.generateMipMaps = !noMipmap;
  15858. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15859. }
  15860. texture.isReady = true;
  15861. // this.resetTextureCache();
  15862. scene._removePendingData(texture);
  15863. if (onLoad) {
  15864. onLoad();
  15865. }
  15866. };
  15867. this._loadFile(url, function (data) {
  15868. internalCallback(data);
  15869. }, undefined, scene.database, true, onerror);
  15870. return texture;
  15871. };
  15872. ;
  15873. /**
  15874. * Update a raw 3D texture
  15875. * @param texture defines the texture to update
  15876. * @param data defines the data to store
  15877. * @param format defines the data format
  15878. * @param invertY defines if data must be stored with Y axis inverted
  15879. * @param compression defines the used compression (can be null)
  15880. */
  15881. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15882. if (compression === void 0) { compression = null; }
  15883. var internalFormat = this._getInternalFormat(format);
  15884. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15885. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15886. if (!this._doNotHandleContextLost) {
  15887. texture._bufferView = data;
  15888. texture.format = format;
  15889. texture.invertY = invertY;
  15890. texture._compression = compression;
  15891. }
  15892. if (texture.width % 4 !== 0) {
  15893. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15894. }
  15895. if (compression && data) {
  15896. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15897. }
  15898. else {
  15899. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15900. }
  15901. if (texture.generateMipMaps) {
  15902. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15903. }
  15904. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15905. // this.resetTextureCache();
  15906. texture.isReady = true;
  15907. };
  15908. /**
  15909. * Creates a new raw 3D texture
  15910. * @param data defines the data used to create the texture
  15911. * @param width defines the width of the texture
  15912. * @param height defines the height of the texture
  15913. * @param depth defines the depth of the texture
  15914. * @param format defines the format of the texture
  15915. * @param generateMipMaps defines if the engine must generate mip levels
  15916. * @param invertY defines if data must be stored with Y axis inverted
  15917. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15918. * @param compression defines the compressed used (can be null)
  15919. * @returns a new raw 3D texture (stored in an InternalTexture)
  15920. */
  15921. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15922. if (compression === void 0) { compression = null; }
  15923. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15924. texture.baseWidth = width;
  15925. texture.baseHeight = height;
  15926. texture.baseDepth = depth;
  15927. texture.width = width;
  15928. texture.height = height;
  15929. texture.depth = depth;
  15930. texture.format = format;
  15931. texture.generateMipMaps = generateMipMaps;
  15932. texture.samplingMode = samplingMode;
  15933. texture.is3D = true;
  15934. if (!this._doNotHandleContextLost) {
  15935. texture._bufferView = data;
  15936. }
  15937. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15938. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15939. // Filters
  15940. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15941. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15942. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15943. if (generateMipMaps) {
  15944. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15945. }
  15946. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15947. this._internalTexturesCache.push(texture);
  15948. return texture;
  15949. };
  15950. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15951. var gl = this._gl;
  15952. if (!gl) {
  15953. return;
  15954. }
  15955. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  15956. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15957. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15958. if (!noMipmap && !isCompressed) {
  15959. gl.generateMipmap(gl.TEXTURE_2D);
  15960. }
  15961. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15962. // this.resetTextureCache();
  15963. if (scene) {
  15964. scene._removePendingData(texture);
  15965. }
  15966. texture.onLoadedObservable.notifyObservers(texture);
  15967. texture.onLoadedObservable.clear();
  15968. };
  15969. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15970. var _this = this;
  15971. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15972. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  15973. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  15974. var gl = this._gl;
  15975. if (!gl) {
  15976. return;
  15977. }
  15978. if (!texture._webGLTexture) {
  15979. // this.resetTextureCache();
  15980. if (scene) {
  15981. scene._removePendingData(texture);
  15982. }
  15983. return;
  15984. }
  15985. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15986. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15987. texture.baseWidth = width;
  15988. texture.baseHeight = height;
  15989. texture.width = potWidth;
  15990. texture.height = potHeight;
  15991. texture.isReady = true;
  15992. if (processFunction(potWidth, potHeight, function () {
  15993. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15994. })) {
  15995. // Returning as texture needs extra async steps
  15996. return;
  15997. }
  15998. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  15999. };
  16000. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16001. // Create new RGBA data container.
  16002. var rgbaData;
  16003. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16004. rgbaData = new Float32Array(width * height * 4);
  16005. }
  16006. else {
  16007. rgbaData = new Uint32Array(width * height * 4);
  16008. }
  16009. // Convert each pixel.
  16010. for (var x = 0; x < width; x++) {
  16011. for (var y = 0; y < height; y++) {
  16012. var index = (y * width + x) * 3;
  16013. var newIndex = (y * width + x) * 4;
  16014. // Map Old Value to new value.
  16015. rgbaData[newIndex + 0] = rgbData[index + 0];
  16016. rgbaData[newIndex + 1] = rgbData[index + 1];
  16017. rgbaData[newIndex + 2] = rgbData[index + 2];
  16018. // Add fully opaque alpha channel.
  16019. rgbaData[newIndex + 3] = 1;
  16020. }
  16021. }
  16022. return rgbaData;
  16023. };
  16024. /** @hidden */
  16025. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16026. var gl = this._gl;
  16027. if (texture._framebuffer) {
  16028. gl.deleteFramebuffer(texture._framebuffer);
  16029. texture._framebuffer = null;
  16030. }
  16031. if (texture._depthStencilBuffer) {
  16032. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16033. texture._depthStencilBuffer = null;
  16034. }
  16035. if (texture._MSAAFramebuffer) {
  16036. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16037. texture._MSAAFramebuffer = null;
  16038. }
  16039. if (texture._MSAARenderBuffer) {
  16040. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16041. texture._MSAARenderBuffer = null;
  16042. }
  16043. };
  16044. /** @hidden */
  16045. Engine.prototype._releaseTexture = function (texture) {
  16046. var gl = this._gl;
  16047. this._releaseFramebufferObjects(texture);
  16048. gl.deleteTexture(texture._webGLTexture);
  16049. // Unbind channels
  16050. this.unbindAllTextures();
  16051. var index = this._internalTexturesCache.indexOf(texture);
  16052. if (index !== -1) {
  16053. this._internalTexturesCache.splice(index, 1);
  16054. }
  16055. // Integrated fixed lod samplers.
  16056. if (texture._lodTextureHigh) {
  16057. texture._lodTextureHigh.dispose();
  16058. }
  16059. if (texture._lodTextureMid) {
  16060. texture._lodTextureMid.dispose();
  16061. }
  16062. if (texture._lodTextureLow) {
  16063. texture._lodTextureLow.dispose();
  16064. }
  16065. // Set output texture of post process to null if the texture has been released/disposed
  16066. this.scenes.forEach(function (scene) {
  16067. scene.postProcesses.forEach(function (postProcess) {
  16068. if (postProcess._outputTexture == texture) {
  16069. postProcess._outputTexture = null;
  16070. }
  16071. });
  16072. scene.cameras.forEach(function (camera) {
  16073. camera._postProcesses.forEach(function (postProcess) {
  16074. if (postProcess) {
  16075. if (postProcess._outputTexture == texture) {
  16076. postProcess._outputTexture = null;
  16077. }
  16078. }
  16079. });
  16080. });
  16081. });
  16082. };
  16083. Engine.prototype.setProgram = function (program) {
  16084. if (this._currentProgram !== program) {
  16085. this._gl.useProgram(program);
  16086. this._currentProgram = program;
  16087. }
  16088. };
  16089. /**
  16090. * Binds an effect to the webGL context
  16091. * @param effect defines the effect to bind
  16092. */
  16093. Engine.prototype.bindSamplers = function (effect) {
  16094. this.setProgram(effect.getProgram());
  16095. var samplers = effect.getSamplers();
  16096. for (var index = 0; index < samplers.length; index++) {
  16097. var uniform = effect.getUniform(samplers[index]);
  16098. if (uniform) {
  16099. this._boundUniforms[index] = uniform;
  16100. }
  16101. }
  16102. this._currentEffect = null;
  16103. };
  16104. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16105. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16106. return;
  16107. }
  16108. // Remove
  16109. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16110. // Bind last to it
  16111. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16112. // Bind to dummy
  16113. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16114. };
  16115. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16116. if (!internalTexture) {
  16117. return -1;
  16118. }
  16119. internalTexture._initialSlot = channel;
  16120. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16121. if (channel !== internalTexture._designatedSlot) {
  16122. this._textureCollisions.addCount(1, false);
  16123. }
  16124. }
  16125. else {
  16126. if (channel !== internalTexture._designatedSlot) {
  16127. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16128. return internalTexture._designatedSlot;
  16129. }
  16130. else {
  16131. // No slot for this texture, let's pick a new one (if we find a free slot)
  16132. if (this._nextFreeTextureSlots.length) {
  16133. return this._nextFreeTextureSlots[0];
  16134. }
  16135. // We need to recycle the oldest bound texture, sorry.
  16136. this._textureCollisions.addCount(1, false);
  16137. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16138. }
  16139. }
  16140. }
  16141. return channel;
  16142. };
  16143. Engine.prototype._linkTrackers = function (previous, next) {
  16144. previous.next = next;
  16145. next.previous = previous;
  16146. };
  16147. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16148. var currentSlot = internalTexture._designatedSlot;
  16149. if (currentSlot === -1) {
  16150. return -1;
  16151. }
  16152. internalTexture._designatedSlot = -1;
  16153. if (this.disableTextureBindingOptimization) {
  16154. return -1;
  16155. }
  16156. // Remove from bound list
  16157. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16158. // Free the slot
  16159. this._boundTexturesCache[currentSlot] = null;
  16160. this._nextFreeTextureSlots.push(currentSlot);
  16161. return currentSlot;
  16162. };
  16163. Engine.prototype._activateCurrentTexture = function () {
  16164. if (this._currentTextureChannel !== this._activeChannel) {
  16165. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16166. this._currentTextureChannel = this._activeChannel;
  16167. }
  16168. };
  16169. /** @hidden */
  16170. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16171. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16172. if (force === void 0) { force = false; }
  16173. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16174. this._activeChannel = texture._designatedSlot;
  16175. }
  16176. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16177. var isTextureForRendering = texture && texture._initialSlot > -1;
  16178. if (currentTextureBound !== texture || force) {
  16179. if (currentTextureBound) {
  16180. this._removeDesignatedSlot(currentTextureBound);
  16181. }
  16182. this._activateCurrentTexture();
  16183. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16184. this._boundTexturesCache[this._activeChannel] = texture;
  16185. if (texture) {
  16186. if (!this.disableTextureBindingOptimization) {
  16187. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16188. if (slotIndex > -1) {
  16189. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16190. }
  16191. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16192. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16193. }
  16194. texture._designatedSlot = this._activeChannel;
  16195. }
  16196. }
  16197. else if (forTextureDataUpdate) {
  16198. this._activateCurrentTexture();
  16199. }
  16200. if (isTextureForRendering && !forTextureDataUpdate) {
  16201. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16202. }
  16203. };
  16204. /** @hidden */
  16205. Engine.prototype._bindTexture = function (channel, texture) {
  16206. if (channel < 0) {
  16207. return;
  16208. }
  16209. if (texture) {
  16210. channel = this._getCorrectTextureChannel(channel, texture);
  16211. }
  16212. this._activeChannel = channel;
  16213. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16214. };
  16215. /**
  16216. * Sets a texture to the webGL context from a postprocess
  16217. * @param channel defines the channel to use
  16218. * @param postProcess defines the source postprocess
  16219. */
  16220. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16221. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16222. };
  16223. /**
  16224. * Binds the output of the passed in post process to the texture channel specified
  16225. * @param channel The channel the texture should be bound to
  16226. * @param postProcess The post process which's output should be bound
  16227. */
  16228. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16229. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16230. };
  16231. /**
  16232. * Unbind all textures from the webGL context
  16233. */
  16234. Engine.prototype.unbindAllTextures = function () {
  16235. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16236. this._activeChannel = channel;
  16237. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16238. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16239. if (this.webGLVersion > 1) {
  16240. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16241. }
  16242. }
  16243. };
  16244. /**
  16245. * Sets a texture to the according uniform.
  16246. * @param channel The texture channel
  16247. * @param uniform The uniform to set
  16248. * @param texture The texture to apply
  16249. */
  16250. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16251. if (channel < 0) {
  16252. return;
  16253. }
  16254. if (uniform) {
  16255. this._boundUniforms[channel] = uniform;
  16256. }
  16257. this._setTexture(channel, texture);
  16258. };
  16259. /**
  16260. * Sets a depth stencil texture from a render target to the according uniform.
  16261. * @param channel The texture channel
  16262. * @param uniform The uniform to set
  16263. * @param texture The render target texture containing the depth stencil texture to apply
  16264. */
  16265. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16266. if (channel < 0) {
  16267. return;
  16268. }
  16269. if (uniform) {
  16270. this._boundUniforms[channel] = uniform;
  16271. }
  16272. if (!texture || !texture.depthStencilTexture) {
  16273. this._setTexture(channel, null);
  16274. }
  16275. else {
  16276. this._setTexture(channel, texture, false, true);
  16277. }
  16278. };
  16279. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16280. var uniform = this._boundUniforms[sourceSlot];
  16281. if (uniform._currentState === destination) {
  16282. return;
  16283. }
  16284. this._gl.uniform1i(uniform, destination);
  16285. uniform._currentState = destination;
  16286. };
  16287. Engine.prototype._getTextureWrapMode = function (mode) {
  16288. switch (mode) {
  16289. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16290. return this._gl.REPEAT;
  16291. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16292. return this._gl.CLAMP_TO_EDGE;
  16293. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16294. return this._gl.MIRRORED_REPEAT;
  16295. }
  16296. return this._gl.REPEAT;
  16297. };
  16298. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16299. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16300. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16301. // Not ready?
  16302. if (!texture) {
  16303. if (this._boundTexturesCache[channel] != null) {
  16304. this._activeChannel = channel;
  16305. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16306. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16307. if (this.webGLVersion > 1) {
  16308. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16309. }
  16310. }
  16311. return false;
  16312. }
  16313. // Video
  16314. if (texture.video) {
  16315. this._activeChannel = channel;
  16316. texture.update();
  16317. }
  16318. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16319. texture.delayLoad();
  16320. return false;
  16321. }
  16322. var internalTexture;
  16323. if (depthStencilTexture) {
  16324. internalTexture = texture.depthStencilTexture;
  16325. }
  16326. else if (texture.isReady()) {
  16327. internalTexture = texture.getInternalTexture();
  16328. }
  16329. else if (texture.isCube) {
  16330. internalTexture = this.emptyCubeTexture;
  16331. }
  16332. else if (texture.is3D) {
  16333. internalTexture = this.emptyTexture3D;
  16334. }
  16335. else {
  16336. internalTexture = this.emptyTexture;
  16337. }
  16338. if (!isPartOfTextureArray) {
  16339. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16340. }
  16341. var needToBind = true;
  16342. if (this._boundTexturesCache[channel] === internalTexture) {
  16343. this._moveBoundTextureOnTop(internalTexture);
  16344. if (!isPartOfTextureArray) {
  16345. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16346. }
  16347. needToBind = false;
  16348. }
  16349. this._activeChannel = channel;
  16350. if (internalTexture && internalTexture.is3D) {
  16351. if (needToBind) {
  16352. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16353. }
  16354. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16355. internalTexture._cachedWrapU = texture.wrapU;
  16356. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16357. }
  16358. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16359. internalTexture._cachedWrapV = texture.wrapV;
  16360. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16361. }
  16362. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16363. internalTexture._cachedWrapR = texture.wrapR;
  16364. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16365. }
  16366. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16367. }
  16368. else if (internalTexture && internalTexture.isCube) {
  16369. if (needToBind) {
  16370. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16371. }
  16372. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16373. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16374. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16375. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16376. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16377. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16378. }
  16379. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16380. }
  16381. else {
  16382. if (needToBind) {
  16383. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16384. }
  16385. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16386. internalTexture._cachedWrapU = texture.wrapU;
  16387. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16388. }
  16389. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16390. internalTexture._cachedWrapV = texture.wrapV;
  16391. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16392. }
  16393. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16394. }
  16395. return true;
  16396. };
  16397. /**
  16398. * Sets an array of texture to the webGL context
  16399. * @param channel defines the channel where the texture array must be set
  16400. * @param uniform defines the associated uniform location
  16401. * @param textures defines the array of textures to bind
  16402. */
  16403. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16404. if (channel < 0 || !uniform) {
  16405. return;
  16406. }
  16407. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16408. this._textureUnits = new Int32Array(textures.length);
  16409. }
  16410. for (var i = 0; i < textures.length; i++) {
  16411. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16412. }
  16413. this._gl.uniform1iv(uniform, this._textureUnits);
  16414. for (var index = 0; index < textures.length; index++) {
  16415. this._setTexture(this._textureUnits[index], textures[index], true);
  16416. }
  16417. };
  16418. /** @hidden */
  16419. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16420. var internalTexture = texture.getInternalTexture();
  16421. if (!internalTexture) {
  16422. return;
  16423. }
  16424. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16425. var value = texture.anisotropicFilteringLevel;
  16426. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16427. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16428. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16429. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16430. }
  16431. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16432. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16433. internalTexture._cachedAnisotropicFilteringLevel = value;
  16434. }
  16435. };
  16436. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16437. this._bindTextureDirectly(target, texture, true, true);
  16438. this._gl.texParameterf(target, parameter, value);
  16439. };
  16440. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16441. if (texture) {
  16442. this._bindTextureDirectly(target, texture, true, true);
  16443. }
  16444. this._gl.texParameteri(target, parameter, value);
  16445. };
  16446. /**
  16447. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16448. * @param x defines the x coordinate of the rectangle where pixels must be read
  16449. * @param y defines the y coordinate of the rectangle where pixels must be read
  16450. * @param width defines the width of the rectangle where pixels must be read
  16451. * @param height defines the height of the rectangle where pixels must be read
  16452. * @returns a Uint8Array containing RGBA colors
  16453. */
  16454. Engine.prototype.readPixels = function (x, y, width, height) {
  16455. var data = new Uint8Array(height * width * 4);
  16456. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16457. return data;
  16458. };
  16459. /**
  16460. * Add an externaly attached data from its key.
  16461. * This method call will fail and return false, if such key already exists.
  16462. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16463. * @param key the unique key that identifies the data
  16464. * @param data the data object to associate to the key for this Engine instance
  16465. * @return true if no such key were already present and the data was added successfully, false otherwise
  16466. */
  16467. Engine.prototype.addExternalData = function (key, data) {
  16468. if (!this._externalData) {
  16469. this._externalData = new BABYLON.StringDictionary();
  16470. }
  16471. return this._externalData.add(key, data);
  16472. };
  16473. /**
  16474. * Get an externaly attached data from its key
  16475. * @param key the unique key that identifies the data
  16476. * @return the associated data, if present (can be null), or undefined if not present
  16477. */
  16478. Engine.prototype.getExternalData = function (key) {
  16479. if (!this._externalData) {
  16480. this._externalData = new BABYLON.StringDictionary();
  16481. }
  16482. return this._externalData.get(key);
  16483. };
  16484. /**
  16485. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16486. * @param key the unique key that identifies the data
  16487. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16488. * @return the associated data, can be null if the factory returned null.
  16489. */
  16490. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16491. if (!this._externalData) {
  16492. this._externalData = new BABYLON.StringDictionary();
  16493. }
  16494. return this._externalData.getOrAddWithFactory(key, factory);
  16495. };
  16496. /**
  16497. * Remove an externaly attached data from the Engine instance
  16498. * @param key the unique key that identifies the data
  16499. * @return true if the data was successfully removed, false if it doesn't exist
  16500. */
  16501. Engine.prototype.removeExternalData = function (key) {
  16502. if (!this._externalData) {
  16503. this._externalData = new BABYLON.StringDictionary();
  16504. }
  16505. return this._externalData.remove(key);
  16506. };
  16507. /**
  16508. * Unbind all vertex attributes from the webGL context
  16509. */
  16510. Engine.prototype.unbindAllAttributes = function () {
  16511. if (this._mustWipeVertexAttributes) {
  16512. this._mustWipeVertexAttributes = false;
  16513. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16514. this._gl.disableVertexAttribArray(i);
  16515. this._vertexAttribArraysEnabled[i] = false;
  16516. this._currentBufferPointers[i].active = false;
  16517. }
  16518. return;
  16519. }
  16520. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16521. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16522. continue;
  16523. }
  16524. this._gl.disableVertexAttribArray(i);
  16525. this._vertexAttribArraysEnabled[i] = false;
  16526. this._currentBufferPointers[i].active = false;
  16527. }
  16528. };
  16529. /**
  16530. * 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
  16531. */
  16532. Engine.prototype.releaseEffects = function () {
  16533. for (var name in this._compiledEffects) {
  16534. this._deleteProgram(this._compiledEffects[name]._program);
  16535. }
  16536. this._compiledEffects = {};
  16537. };
  16538. /**
  16539. * Dispose and release all associated resources
  16540. */
  16541. Engine.prototype.dispose = function () {
  16542. this.hideLoadingUI();
  16543. this.stopRenderLoop();
  16544. // Release postProcesses
  16545. while (this.postProcesses.length) {
  16546. this.postProcesses[0].dispose();
  16547. }
  16548. // Empty texture
  16549. if (this._emptyTexture) {
  16550. this._releaseTexture(this._emptyTexture);
  16551. this._emptyTexture = null;
  16552. }
  16553. if (this._emptyCubeTexture) {
  16554. this._releaseTexture(this._emptyCubeTexture);
  16555. this._emptyCubeTexture = null;
  16556. }
  16557. // Rescale PP
  16558. if (this._rescalePostProcess) {
  16559. this._rescalePostProcess.dispose();
  16560. }
  16561. // Release scenes
  16562. while (this.scenes.length) {
  16563. this.scenes[0].dispose();
  16564. }
  16565. // Release audio engine
  16566. if (Engine.audioEngine) {
  16567. Engine.audioEngine.dispose();
  16568. }
  16569. // Release effects
  16570. this.releaseEffects();
  16571. // Unbind
  16572. this.unbindAllAttributes();
  16573. this._boundUniforms = [];
  16574. if (this._dummyFramebuffer) {
  16575. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16576. }
  16577. //WebVR
  16578. this.disableVR();
  16579. // Events
  16580. if (BABYLON.Tools.IsWindowObjectExist()) {
  16581. window.removeEventListener("blur", this._onBlur);
  16582. window.removeEventListener("focus", this._onFocus);
  16583. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16584. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16585. if (this._renderingCanvas) {
  16586. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16587. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16588. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16589. if (!this._doNotHandleContextLost) {
  16590. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16591. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16592. }
  16593. }
  16594. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16595. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16596. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16597. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16598. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16599. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16600. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16601. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16602. if (this._onVrDisplayConnect) {
  16603. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16604. if (this._onVrDisplayDisconnect) {
  16605. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16606. }
  16607. if (this._onVrDisplayPresentChange) {
  16608. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16609. }
  16610. this._onVrDisplayConnect = null;
  16611. this._onVrDisplayDisconnect = null;
  16612. }
  16613. }
  16614. // Remove from Instances
  16615. var index = Engine.Instances.indexOf(this);
  16616. if (index >= 0) {
  16617. Engine.Instances.splice(index, 1);
  16618. }
  16619. this._workingCanvas = null;
  16620. this._workingContext = null;
  16621. this._currentBufferPointers = [];
  16622. this._renderingCanvas = null;
  16623. this._currentProgram = null;
  16624. this._bindedRenderFunction = null;
  16625. this.onResizeObservable.clear();
  16626. this.onCanvasBlurObservable.clear();
  16627. this.onCanvasFocusObservable.clear();
  16628. this.onCanvasPointerOutObservable.clear();
  16629. this.onBeginFrameObservable.clear();
  16630. this.onEndFrameObservable.clear();
  16631. BABYLON.Effect.ResetCache();
  16632. // Abort active requests
  16633. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16634. var request = _a[_i];
  16635. request.abort();
  16636. }
  16637. };
  16638. // Loading screen
  16639. /**
  16640. * Display the loading screen
  16641. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16642. */
  16643. Engine.prototype.displayLoadingUI = function () {
  16644. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16645. return;
  16646. }
  16647. var loadingScreen = this.loadingScreen;
  16648. if (loadingScreen) {
  16649. loadingScreen.displayLoadingUI();
  16650. }
  16651. };
  16652. /**
  16653. * Hide the loading screen
  16654. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16655. */
  16656. Engine.prototype.hideLoadingUI = function () {
  16657. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16658. return;
  16659. }
  16660. var loadingScreen = this.loadingScreen;
  16661. if (loadingScreen) {
  16662. loadingScreen.hideLoadingUI();
  16663. }
  16664. };
  16665. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16666. /**
  16667. * Gets the current loading screen object
  16668. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16669. */
  16670. get: function () {
  16671. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16672. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16673. return this._loadingScreen;
  16674. },
  16675. /**
  16676. * Sets the current loading screen object
  16677. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16678. */
  16679. set: function (loadingScreen) {
  16680. this._loadingScreen = loadingScreen;
  16681. },
  16682. enumerable: true,
  16683. configurable: true
  16684. });
  16685. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16686. /**
  16687. * Sets the current loading screen text
  16688. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16689. */
  16690. set: function (text) {
  16691. this.loadingScreen.loadingUIText = text;
  16692. },
  16693. enumerable: true,
  16694. configurable: true
  16695. });
  16696. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16697. /**
  16698. * Sets the current loading screen background color
  16699. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16700. */
  16701. set: function (color) {
  16702. this.loadingScreen.loadingUIBackgroundColor = color;
  16703. },
  16704. enumerable: true,
  16705. configurable: true
  16706. });
  16707. /**
  16708. * Attach a new callback raised when context lost event is fired
  16709. * @param callback defines the callback to call
  16710. */
  16711. Engine.prototype.attachContextLostEvent = function (callback) {
  16712. if (this._renderingCanvas) {
  16713. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16714. }
  16715. };
  16716. /**
  16717. * Attach a new callback raised when context restored event is fired
  16718. * @param callback defines the callback to call
  16719. */
  16720. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16721. if (this._renderingCanvas) {
  16722. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16723. }
  16724. };
  16725. /**
  16726. * Gets the source code of the vertex shader associated with a specific webGL program
  16727. * @param program defines the program to use
  16728. * @returns a string containing the source code of the vertex shader associated with the program
  16729. */
  16730. Engine.prototype.getVertexShaderSource = function (program) {
  16731. var shaders = this._gl.getAttachedShaders(program);
  16732. if (!shaders) {
  16733. return null;
  16734. }
  16735. return this._gl.getShaderSource(shaders[0]);
  16736. };
  16737. /**
  16738. * Gets the source code of the fragment shader associated with a specific webGL program
  16739. * @param program defines the program to use
  16740. * @returns a string containing the source code of the fragment shader associated with the program
  16741. */
  16742. Engine.prototype.getFragmentShaderSource = function (program) {
  16743. var shaders = this._gl.getAttachedShaders(program);
  16744. if (!shaders) {
  16745. return null;
  16746. }
  16747. return this._gl.getShaderSource(shaders[1]);
  16748. };
  16749. /**
  16750. * Get the current error code of the webGL context
  16751. * @returns the error code
  16752. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16753. */
  16754. Engine.prototype.getError = function () {
  16755. return this._gl.getError();
  16756. };
  16757. // FPS
  16758. /**
  16759. * Gets the current framerate
  16760. * @returns a number representing the framerate
  16761. */
  16762. Engine.prototype.getFps = function () {
  16763. return this._fps;
  16764. };
  16765. /**
  16766. * Gets the time spent between current and previous frame
  16767. * @returns a number representing the delta time in ms
  16768. */
  16769. Engine.prototype.getDeltaTime = function () {
  16770. return this._deltaTime;
  16771. };
  16772. Engine.prototype._measureFps = function () {
  16773. this._performanceMonitor.sampleFrame();
  16774. this._fps = this._performanceMonitor.averageFPS;
  16775. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16776. };
  16777. /** @hidden */
  16778. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16779. if (faceIndex === void 0) { faceIndex = -1; }
  16780. var gl = this._gl;
  16781. if (!this._dummyFramebuffer) {
  16782. var dummy = gl.createFramebuffer();
  16783. if (!dummy) {
  16784. throw new Error("Unable to create dummy framebuffer");
  16785. }
  16786. this._dummyFramebuffer = dummy;
  16787. }
  16788. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16789. if (faceIndex > -1) {
  16790. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16791. }
  16792. else {
  16793. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16794. }
  16795. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16796. var buffer;
  16797. switch (readType) {
  16798. case gl.UNSIGNED_BYTE:
  16799. buffer = new Uint8Array(4 * width * height);
  16800. readType = gl.UNSIGNED_BYTE;
  16801. break;
  16802. default:
  16803. buffer = new Float32Array(4 * width * height);
  16804. readType = gl.FLOAT;
  16805. break;
  16806. }
  16807. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16808. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16809. return buffer;
  16810. };
  16811. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16812. if (this._webGLVersion > 1) {
  16813. return this._caps.colorBufferFloat;
  16814. }
  16815. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16816. };
  16817. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16818. if (this._webGLVersion > 1) {
  16819. return this._caps.colorBufferFloat;
  16820. }
  16821. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16822. };
  16823. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16824. Engine.prototype._canRenderToFramebuffer = function (type) {
  16825. var gl = this._gl;
  16826. //clear existing errors
  16827. while (gl.getError() !== gl.NO_ERROR) { }
  16828. var successful = true;
  16829. var texture = gl.createTexture();
  16830. gl.bindTexture(gl.TEXTURE_2D, texture);
  16831. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16832. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16833. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16834. var fb = gl.createFramebuffer();
  16835. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16836. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16837. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16838. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16839. successful = successful && (gl.getError() === gl.NO_ERROR);
  16840. //try render by clearing frame buffer's color buffer
  16841. if (successful) {
  16842. gl.clear(gl.COLOR_BUFFER_BIT);
  16843. successful = successful && (gl.getError() === gl.NO_ERROR);
  16844. }
  16845. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16846. if (successful) {
  16847. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16848. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16849. var readFormat = gl.RGBA;
  16850. var readType = gl.UNSIGNED_BYTE;
  16851. var buffer = new Uint8Array(4);
  16852. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16853. successful = successful && (gl.getError() === gl.NO_ERROR);
  16854. }
  16855. //clean up
  16856. gl.deleteTexture(texture);
  16857. gl.deleteFramebuffer(fb);
  16858. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16859. //clear accumulated errors
  16860. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16861. return successful;
  16862. };
  16863. /** @hidden */
  16864. Engine.prototype._getWebGLTextureType = function (type) {
  16865. if (type === Engine.TEXTURETYPE_FLOAT) {
  16866. return this._gl.FLOAT;
  16867. }
  16868. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16869. // Add Half Float Constant.
  16870. return this._gl.HALF_FLOAT_OES;
  16871. }
  16872. return this._gl.UNSIGNED_BYTE;
  16873. };
  16874. ;
  16875. Engine.prototype._getInternalFormat = function (format) {
  16876. var internalFormat = this._gl.RGBA;
  16877. switch (format) {
  16878. case Engine.TEXTUREFORMAT_ALPHA:
  16879. internalFormat = this._gl.ALPHA;
  16880. break;
  16881. case Engine.TEXTUREFORMAT_LUMINANCE:
  16882. internalFormat = this._gl.LUMINANCE;
  16883. break;
  16884. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16885. internalFormat = this._gl.LUMINANCE_ALPHA;
  16886. break;
  16887. case Engine.TEXTUREFORMAT_RGB:
  16888. case Engine.TEXTUREFORMAT_RGB32F:
  16889. internalFormat = this._gl.RGB;
  16890. break;
  16891. case Engine.TEXTUREFORMAT_RGBA:
  16892. case Engine.TEXTUREFORMAT_RGBA32F:
  16893. internalFormat = this._gl.RGBA;
  16894. break;
  16895. case Engine.TEXTUREFORMAT_R32F:
  16896. internalFormat = this._gl.RED;
  16897. break;
  16898. case Engine.TEXTUREFORMAT_RG32F:
  16899. internalFormat = this._gl.RG;
  16900. break;
  16901. }
  16902. return internalFormat;
  16903. };
  16904. /** @hidden */
  16905. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16906. if (this._webGLVersion === 1) {
  16907. if (format) {
  16908. switch (format) {
  16909. case Engine.TEXTUREFORMAT_LUMINANCE:
  16910. return this._gl.LUMINANCE;
  16911. }
  16912. }
  16913. return this._gl.RGBA;
  16914. }
  16915. if (type === Engine.TEXTURETYPE_FLOAT) {
  16916. if (format) {
  16917. switch (format) {
  16918. case Engine.TEXTUREFORMAT_R32F:
  16919. return this._gl.R32F;
  16920. case Engine.TEXTUREFORMAT_RG32F:
  16921. return this._gl.RG32F;
  16922. case Engine.TEXTUREFORMAT_RGB32F:
  16923. return this._gl.RGB32F;
  16924. }
  16925. }
  16926. return this._gl.RGBA32F;
  16927. }
  16928. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16929. return this._gl.RGBA16F;
  16930. }
  16931. if (format) {
  16932. switch (format) {
  16933. case Engine.TEXTUREFORMAT_LUMINANCE:
  16934. return this._gl.LUMINANCE;
  16935. case Engine.TEXTUREFORMAT_RGB:
  16936. return this._gl.RGB;
  16937. }
  16938. }
  16939. return this._gl.RGBA;
  16940. };
  16941. ;
  16942. /** @hidden */
  16943. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16944. if (type === Engine.TEXTURETYPE_FLOAT) {
  16945. return this._gl.RGBA32F;
  16946. }
  16947. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16948. return this._gl.RGBA16F;
  16949. }
  16950. return this._gl.RGBA8;
  16951. };
  16952. ;
  16953. /**
  16954. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  16955. * @return the new query
  16956. */
  16957. Engine.prototype.createQuery = function () {
  16958. return this._gl.createQuery();
  16959. };
  16960. /**
  16961. * Delete and release a webGL query
  16962. * @param query defines the query to delete
  16963. * @return the current engine
  16964. */
  16965. Engine.prototype.deleteQuery = function (query) {
  16966. this._gl.deleteQuery(query);
  16967. return this;
  16968. };
  16969. /**
  16970. * Check if a given query has resolved and got its value
  16971. * @param query defines the query to check
  16972. * @returns true if the query got its value
  16973. */
  16974. Engine.prototype.isQueryResultAvailable = function (query) {
  16975. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  16976. };
  16977. /**
  16978. * Gets the value of a given query
  16979. * @param query defines the query to check
  16980. * @returns the value of the query
  16981. */
  16982. Engine.prototype.getQueryResult = function (query) {
  16983. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  16984. };
  16985. /**
  16986. * Initiates an occlusion query
  16987. * @param algorithmType defines the algorithm to use
  16988. * @param query defines the query to use
  16989. * @returns the current engine
  16990. * @see http://doc.babylonjs.com/features/occlusionquery
  16991. */
  16992. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  16993. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  16994. this._gl.beginQuery(glAlgorithm, query);
  16995. return this;
  16996. };
  16997. /**
  16998. * Ends an occlusion query
  16999. * @see http://doc.babylonjs.com/features/occlusionquery
  17000. * @param algorithmType defines the algorithm to use
  17001. * @returns the current engine
  17002. */
  17003. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17004. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17005. this._gl.endQuery(glAlgorithm);
  17006. return this;
  17007. };
  17008. /* Time queries */
  17009. Engine.prototype._createTimeQuery = function () {
  17010. var timerQuery = this._caps.timerQuery;
  17011. if (timerQuery.createQueryEXT) {
  17012. return timerQuery.createQueryEXT();
  17013. }
  17014. return this.createQuery();
  17015. };
  17016. Engine.prototype._deleteTimeQuery = function (query) {
  17017. var timerQuery = this._caps.timerQuery;
  17018. if (timerQuery.deleteQueryEXT) {
  17019. timerQuery.deleteQueryEXT(query);
  17020. return;
  17021. }
  17022. this.deleteQuery(query);
  17023. };
  17024. Engine.prototype._getTimeQueryResult = function (query) {
  17025. var timerQuery = this._caps.timerQuery;
  17026. if (timerQuery.getQueryObjectEXT) {
  17027. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17028. }
  17029. return this.getQueryResult(query);
  17030. };
  17031. Engine.prototype._getTimeQueryAvailability = function (query) {
  17032. var timerQuery = this._caps.timerQuery;
  17033. if (timerQuery.getQueryObjectEXT) {
  17034. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17035. }
  17036. return this.isQueryResultAvailable(query);
  17037. };
  17038. /**
  17039. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17040. * Please note that only one query can be issued at a time
  17041. * @returns a time token used to track the time span
  17042. */
  17043. Engine.prototype.startTimeQuery = function () {
  17044. var timerQuery = this._caps.timerQuery;
  17045. if (!timerQuery) {
  17046. return null;
  17047. }
  17048. var token = new BABYLON._TimeToken();
  17049. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17050. if (this._caps.canUseTimestampForTimerQuery) {
  17051. token._startTimeQuery = this._createTimeQuery();
  17052. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17053. }
  17054. else {
  17055. if (this._currentNonTimestampToken) {
  17056. return this._currentNonTimestampToken;
  17057. }
  17058. token._timeElapsedQuery = this._createTimeQuery();
  17059. if (timerQuery.beginQueryEXT) {
  17060. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17061. }
  17062. else {
  17063. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17064. }
  17065. this._currentNonTimestampToken = token;
  17066. }
  17067. return token;
  17068. };
  17069. /**
  17070. * Ends a time query
  17071. * @param token defines the token used to measure the time span
  17072. * @returns the time spent (in ns)
  17073. */
  17074. Engine.prototype.endTimeQuery = function (token) {
  17075. var timerQuery = this._caps.timerQuery;
  17076. if (!timerQuery || !token) {
  17077. return -1;
  17078. }
  17079. if (this._caps.canUseTimestampForTimerQuery) {
  17080. if (!token._startTimeQuery) {
  17081. return -1;
  17082. }
  17083. if (!token._endTimeQuery) {
  17084. token._endTimeQuery = this._createTimeQuery();
  17085. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17086. }
  17087. }
  17088. else if (!token._timeElapsedQueryEnded) {
  17089. if (!token._timeElapsedQuery) {
  17090. return -1;
  17091. }
  17092. if (timerQuery.endQueryEXT) {
  17093. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17094. }
  17095. else {
  17096. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17097. }
  17098. token._timeElapsedQueryEnded = true;
  17099. }
  17100. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17101. var available = false;
  17102. if (token._endTimeQuery) {
  17103. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17104. }
  17105. else if (token._timeElapsedQuery) {
  17106. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17107. }
  17108. if (available && !disjoint) {
  17109. var result = 0;
  17110. if (this._caps.canUseTimestampForTimerQuery) {
  17111. if (!token._startTimeQuery || !token._endTimeQuery) {
  17112. return -1;
  17113. }
  17114. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17115. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17116. result = timeEnd - timeStart;
  17117. this._deleteTimeQuery(token._startTimeQuery);
  17118. this._deleteTimeQuery(token._endTimeQuery);
  17119. token._startTimeQuery = null;
  17120. token._endTimeQuery = null;
  17121. }
  17122. else {
  17123. if (!token._timeElapsedQuery) {
  17124. return -1;
  17125. }
  17126. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17127. this._deleteTimeQuery(token._timeElapsedQuery);
  17128. token._timeElapsedQuery = null;
  17129. token._timeElapsedQueryEnded = false;
  17130. this._currentNonTimestampToken = null;
  17131. }
  17132. return result;
  17133. }
  17134. return -1;
  17135. };
  17136. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17137. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17138. };
  17139. // Transform feedback
  17140. /**
  17141. * Creates a webGL transform feedback object
  17142. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17143. * @returns the webGL transform feedback object
  17144. */
  17145. Engine.prototype.createTransformFeedback = function () {
  17146. return this._gl.createTransformFeedback();
  17147. };
  17148. /**
  17149. * Delete a webGL transform feedback object
  17150. * @param value defines the webGL transform feedback object to delete
  17151. */
  17152. Engine.prototype.deleteTransformFeedback = function (value) {
  17153. this._gl.deleteTransformFeedback(value);
  17154. };
  17155. /**
  17156. * Bind a webGL transform feedback object to the webgl context
  17157. * @param value defines the webGL transform feedback object to bind
  17158. */
  17159. Engine.prototype.bindTransformFeedback = function (value) {
  17160. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17161. };
  17162. /**
  17163. * Begins a transform feedback operation
  17164. * @param usePoints defines if points or triangles must be used
  17165. */
  17166. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17167. if (usePoints === void 0) { usePoints = true; }
  17168. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17169. };
  17170. /**
  17171. * Ends a transform feedback operation
  17172. */
  17173. Engine.prototype.endTransformFeedback = function () {
  17174. this._gl.endTransformFeedback();
  17175. };
  17176. /**
  17177. * Specify the varyings to use with transform feedback
  17178. * @param program defines the associated webGL program
  17179. * @param value defines the list of strings representing the varying names
  17180. */
  17181. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17182. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17183. };
  17184. /**
  17185. * Bind a webGL buffer for a transform feedback operation
  17186. * @param value defines the webGL buffer to bind
  17187. */
  17188. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17189. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17190. };
  17191. /** @hidden */
  17192. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17193. var _this = this;
  17194. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17195. this._activeRequests.push(request);
  17196. request.onCompleteObservable.add(function (request) {
  17197. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17198. });
  17199. return request;
  17200. };
  17201. /** @hidden */
  17202. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17203. var _this = this;
  17204. return new Promise(function (resolve, reject) {
  17205. _this._loadFile(url, function (data) {
  17206. resolve(data);
  17207. }, undefined, database, useArrayBuffer, function (request, exception) {
  17208. reject(exception);
  17209. });
  17210. });
  17211. };
  17212. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17213. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17214. var onload = function (data) {
  17215. loadedFiles[index] = data;
  17216. loadedFiles._internalCount++;
  17217. if (loadedFiles._internalCount === 6) {
  17218. onfinish(loadedFiles);
  17219. }
  17220. };
  17221. var onerror = function (request, exception) {
  17222. if (onErrorCallBack && request) {
  17223. onErrorCallBack(request.status + " " + request.statusText, exception);
  17224. }
  17225. };
  17226. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17227. };
  17228. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17229. if (onError === void 0) { onError = null; }
  17230. var loadedFiles = [];
  17231. loadedFiles._internalCount = 0;
  17232. for (var index = 0; index < 6; index++) {
  17233. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17234. }
  17235. };
  17236. // Statics
  17237. /**
  17238. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17239. * @returns true if the engine can be created
  17240. * @ignorenaming
  17241. */
  17242. Engine.isSupported = function () {
  17243. try {
  17244. var tempcanvas = document.createElement("canvas");
  17245. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17246. return gl != null && !!window.WebGLRenderingContext;
  17247. }
  17248. catch (e) {
  17249. return false;
  17250. }
  17251. };
  17252. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17253. Engine.ExceptionList = [
  17254. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17255. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17256. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17257. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17258. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17259. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17260. ];
  17261. /** Gets the list of created engines */
  17262. Engine.Instances = new Array();
  17263. // Const statics
  17264. Engine._ALPHA_DISABLE = 0;
  17265. Engine._ALPHA_ADD = 1;
  17266. Engine._ALPHA_COMBINE = 2;
  17267. Engine._ALPHA_SUBTRACT = 3;
  17268. Engine._ALPHA_MULTIPLY = 4;
  17269. Engine._ALPHA_MAXIMIZED = 5;
  17270. Engine._ALPHA_ONEONE = 6;
  17271. Engine._ALPHA_PREMULTIPLIED = 7;
  17272. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17273. Engine._ALPHA_INTERPOLATE = 9;
  17274. Engine._ALPHA_SCREENMODE = 10;
  17275. Engine._DELAYLOADSTATE_NONE = 0;
  17276. Engine._DELAYLOADSTATE_LOADED = 1;
  17277. Engine._DELAYLOADSTATE_LOADING = 2;
  17278. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17279. Engine._TEXTUREFORMAT_ALPHA = 0;
  17280. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17281. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17282. Engine._TEXTUREFORMAT_RGB = 4;
  17283. Engine._TEXTUREFORMAT_RGBA = 5;
  17284. Engine._TEXTUREFORMAT_R32F = 6;
  17285. Engine._TEXTUREFORMAT_RG32F = 7;
  17286. Engine._TEXTUREFORMAT_RGB32F = 8;
  17287. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17288. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17289. Engine._TEXTURETYPE_FLOAT = 1;
  17290. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17291. // Depht or Stencil test Constants.
  17292. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17293. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  17294. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  17295. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  17296. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  17297. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  17298. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  17299. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  17300. // Stencil Actions Constants.
  17301. Engine._KEEP = 0x1E00;
  17302. Engine._REPLACE = 0x1E01;
  17303. Engine._INCR = 0x1E02;
  17304. Engine._DECR = 0x1E03;
  17305. Engine._INVERT = 0x150A;
  17306. Engine._INCR_WRAP = 0x8507;
  17307. Engine._DECR_WRAP = 0x8508;
  17308. // Texture rescaling mode
  17309. Engine._SCALEMODE_FLOOR = 1;
  17310. Engine._SCALEMODE_NEAREST = 2;
  17311. Engine._SCALEMODE_CEILING = 3;
  17312. // Updatable statics so stick with vars here
  17313. /**
  17314. * Gets or sets the epsilon value used by collision engine
  17315. */
  17316. Engine.CollisionsEpsilon = 0.001;
  17317. /**
  17318. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17319. */
  17320. Engine.CodeRepository = "src/";
  17321. /**
  17322. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17323. */
  17324. Engine.ShadersRepository = "src/Shaders/";
  17325. return Engine;
  17326. }());
  17327. BABYLON.Engine = Engine;
  17328. })(BABYLON || (BABYLON = {}));
  17329. //# sourceMappingURL=babylon.engine.js.map
  17330. var BABYLON;
  17331. (function (BABYLON) {
  17332. /**
  17333. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17334. */
  17335. var Node = /** @class */ (function () {
  17336. /**
  17337. * Creates a new Node
  17338. * @param {string} name - the name and id to be given to this node
  17339. * @param {BABYLON.Scene} the scene this node will be added to
  17340. */
  17341. function Node(name, scene) {
  17342. if (scene === void 0) { scene = null; }
  17343. /**
  17344. * Gets or sets a string used to store user defined state for the node
  17345. */
  17346. this.state = "";
  17347. /**
  17348. * Gets or sets an object used to store user defined information for the node
  17349. */
  17350. this.metadata = null;
  17351. /**
  17352. * Gets or sets a boolean used to define if the node must be serialized
  17353. */
  17354. this.doNotSerialize = false;
  17355. /** @hidden */
  17356. this._isDisposed = false;
  17357. /**
  17358. * Gets a list of Animations associated with the node
  17359. */
  17360. this.animations = new Array();
  17361. this._ranges = {};
  17362. this._isEnabled = true;
  17363. this._isReady = true;
  17364. /** @hidden */
  17365. this._currentRenderId = -1;
  17366. this._parentRenderId = -1;
  17367. this._childRenderId = -1;
  17368. this._animationPropertiesOverride = null;
  17369. /**
  17370. * An event triggered when the mesh is disposed
  17371. */
  17372. this.onDisposeObservable = new BABYLON.Observable();
  17373. // Behaviors
  17374. this._behaviors = new Array();
  17375. this.name = name;
  17376. this.id = name;
  17377. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17378. this.uniqueId = this._scene.getUniqueId();
  17379. this._initCache();
  17380. }
  17381. /**
  17382. * Gets a boolean indicating if the node has been disposed
  17383. * @returns true if the node was disposed
  17384. */
  17385. Node.prototype.isDisposed = function () {
  17386. return this._isDisposed;
  17387. };
  17388. Object.defineProperty(Node.prototype, "parent", {
  17389. get: function () {
  17390. return this._parentNode;
  17391. },
  17392. /**
  17393. * Gets or sets the parent of the node
  17394. */
  17395. set: function (parent) {
  17396. if (this._parentNode === parent) {
  17397. return;
  17398. }
  17399. // Remove self from list of children of parent
  17400. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17401. var index = this._parentNode._children.indexOf(this);
  17402. if (index !== -1) {
  17403. this._parentNode._children.splice(index, 1);
  17404. }
  17405. }
  17406. // Store new parent
  17407. this._parentNode = parent;
  17408. // Add as child to new parent
  17409. if (this._parentNode) {
  17410. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17411. this._parentNode._children = new Array();
  17412. }
  17413. this._parentNode._children.push(this);
  17414. }
  17415. },
  17416. enumerable: true,
  17417. configurable: true
  17418. });
  17419. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17420. /**
  17421. * Gets or sets the animation properties override
  17422. */
  17423. get: function () {
  17424. if (!this._animationPropertiesOverride) {
  17425. return this._scene.animationPropertiesOverride;
  17426. }
  17427. return this._animationPropertiesOverride;
  17428. },
  17429. set: function (value) {
  17430. this._animationPropertiesOverride = value;
  17431. },
  17432. enumerable: true,
  17433. configurable: true
  17434. });
  17435. /**
  17436. * Gets a string idenfifying the name of the class
  17437. * @returns "Node" string
  17438. */
  17439. Node.prototype.getClassName = function () {
  17440. return "Node";
  17441. };
  17442. Object.defineProperty(Node.prototype, "onDispose", {
  17443. /**
  17444. * Sets a callback that will be raised when the node will be disposed
  17445. */
  17446. set: function (callback) {
  17447. if (this._onDisposeObserver) {
  17448. this.onDisposeObservable.remove(this._onDisposeObserver);
  17449. }
  17450. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17451. },
  17452. enumerable: true,
  17453. configurable: true
  17454. });
  17455. /**
  17456. * Gets the scene of the node
  17457. * @returns a {BABYLON.Scene}
  17458. */
  17459. Node.prototype.getScene = function () {
  17460. return this._scene;
  17461. };
  17462. /**
  17463. * Gets the engine of the node
  17464. * @returns a {BABYLON.Engine}
  17465. */
  17466. Node.prototype.getEngine = function () {
  17467. return this._scene.getEngine();
  17468. };
  17469. /**
  17470. * Attach a behavior to the node
  17471. * @see http://doc.babylonjs.com/features/behaviour
  17472. * @param behavior defines the behavior to attach
  17473. * @returns the current Node
  17474. */
  17475. Node.prototype.addBehavior = function (behavior) {
  17476. var _this = this;
  17477. var index = this._behaviors.indexOf(behavior);
  17478. if (index !== -1) {
  17479. return this;
  17480. }
  17481. behavior.init();
  17482. if (this._scene.isLoading) {
  17483. // We defer the attach when the scene will be loaded
  17484. var observer = this._scene.onDataLoadedObservable.add(function () {
  17485. behavior.attach(_this);
  17486. setTimeout(function () {
  17487. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17488. _this._scene.onDataLoadedObservable.remove(observer);
  17489. }, 0);
  17490. });
  17491. }
  17492. else {
  17493. behavior.attach(this);
  17494. }
  17495. this._behaviors.push(behavior);
  17496. return this;
  17497. };
  17498. /**
  17499. * Remove an attached behavior
  17500. * @see http://doc.babylonjs.com/features/behaviour
  17501. * @param behavior defines the behavior to attach
  17502. * @returns the current Node
  17503. */
  17504. Node.prototype.removeBehavior = function (behavior) {
  17505. var index = this._behaviors.indexOf(behavior);
  17506. if (index === -1) {
  17507. return this;
  17508. }
  17509. this._behaviors[index].detach();
  17510. this._behaviors.splice(index, 1);
  17511. return this;
  17512. };
  17513. Object.defineProperty(Node.prototype, "behaviors", {
  17514. /**
  17515. * Gets the list of attached behaviors
  17516. * @see http://doc.babylonjs.com/features/behaviour
  17517. */
  17518. get: function () {
  17519. return this._behaviors;
  17520. },
  17521. enumerable: true,
  17522. configurable: true
  17523. });
  17524. /**
  17525. * Gets an attached behavior by name
  17526. * @param name defines the name of the behavior to look for
  17527. * @see http://doc.babylonjs.com/features/behaviour
  17528. * @returns null if behavior was not found else the requested behavior
  17529. */
  17530. Node.prototype.getBehaviorByName = function (name) {
  17531. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17532. var behavior = _a[_i];
  17533. if (behavior.name === name) {
  17534. return behavior;
  17535. }
  17536. }
  17537. return null;
  17538. };
  17539. /**
  17540. * Returns the world matrix of the node
  17541. * @returns a matrix containing the node's world matrix
  17542. */
  17543. Node.prototype.getWorldMatrix = function () {
  17544. return BABYLON.Matrix.Identity();
  17545. };
  17546. /** @hidden */
  17547. Node.prototype._getWorldMatrixDeterminant = function () {
  17548. return 1;
  17549. };
  17550. // override it in derived class if you add new variables to the cache
  17551. // and call the parent class method
  17552. /** @hidden */
  17553. Node.prototype._initCache = function () {
  17554. this._cache = {};
  17555. this._cache.parent = undefined;
  17556. };
  17557. /** @hidden */
  17558. Node.prototype.updateCache = function (force) {
  17559. if (!force && this.isSynchronized())
  17560. return;
  17561. this._cache.parent = this.parent;
  17562. this._updateCache();
  17563. };
  17564. // override it in derived class if you add new variables to the cache
  17565. // and call the parent class method if !ignoreParentClass
  17566. /** @hidden */
  17567. Node.prototype._updateCache = function (ignoreParentClass) {
  17568. };
  17569. // override it in derived class if you add new variables to the cache
  17570. /** @hidden */
  17571. Node.prototype._isSynchronized = function () {
  17572. return true;
  17573. };
  17574. /** @hidden */
  17575. Node.prototype._markSyncedWithParent = function () {
  17576. if (this.parent) {
  17577. this._parentRenderId = this.parent._childRenderId;
  17578. }
  17579. };
  17580. /** @hidden */
  17581. Node.prototype.isSynchronizedWithParent = function () {
  17582. if (!this.parent) {
  17583. return true;
  17584. }
  17585. if (this._parentRenderId !== this.parent._childRenderId) {
  17586. return false;
  17587. }
  17588. return this.parent.isSynchronized();
  17589. };
  17590. /** @hidden */
  17591. Node.prototype.isSynchronized = function (updateCache) {
  17592. var check = this.hasNewParent();
  17593. check = check || !this.isSynchronizedWithParent();
  17594. check = check || !this._isSynchronized();
  17595. if (updateCache)
  17596. this.updateCache(true);
  17597. return !check;
  17598. };
  17599. /** @hidden */
  17600. Node.prototype.hasNewParent = function (update) {
  17601. if (this._cache.parent === this.parent)
  17602. return false;
  17603. if (update)
  17604. this._cache.parent = this.parent;
  17605. return true;
  17606. };
  17607. /**
  17608. * Is this node ready to be used/rendered
  17609. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17610. * @return true if the node is ready
  17611. */
  17612. Node.prototype.isReady = function (completeCheck) {
  17613. if (completeCheck === void 0) { completeCheck = false; }
  17614. return this._isReady;
  17615. };
  17616. /**
  17617. * Is this node enabled?
  17618. * 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
  17619. * @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
  17620. * @return whether this node (and its parent) is enabled
  17621. */
  17622. Node.prototype.isEnabled = function (checkAncestors) {
  17623. if (checkAncestors === void 0) { checkAncestors = true; }
  17624. if (checkAncestors === false) {
  17625. return this._isEnabled;
  17626. }
  17627. if (this._isEnabled === false) {
  17628. return false;
  17629. }
  17630. if (this.parent !== undefined && this.parent !== null) {
  17631. return this.parent.isEnabled(checkAncestors);
  17632. }
  17633. return true;
  17634. };
  17635. /**
  17636. * Set the enabled state of this node
  17637. * @param value defines the new enabled state
  17638. */
  17639. Node.prototype.setEnabled = function (value) {
  17640. this._isEnabled = value;
  17641. };
  17642. /**
  17643. * Is this node a descendant of the given node?
  17644. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17645. * @param ancestor defines the parent node to inspect
  17646. * @returns a boolean indicating if this node is a descendant of the given node
  17647. */
  17648. Node.prototype.isDescendantOf = function (ancestor) {
  17649. if (this.parent) {
  17650. if (this.parent === ancestor) {
  17651. return true;
  17652. }
  17653. return this.parent.isDescendantOf(ancestor);
  17654. }
  17655. return false;
  17656. };
  17657. /** @hidden */
  17658. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17659. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17660. if (!this._children) {
  17661. return;
  17662. }
  17663. for (var index = 0; index < this._children.length; index++) {
  17664. var item = this._children[index];
  17665. if (!predicate || predicate(item)) {
  17666. results.push(item);
  17667. }
  17668. if (!directDescendantsOnly) {
  17669. item._getDescendants(results, false, predicate);
  17670. }
  17671. }
  17672. };
  17673. /**
  17674. * Will return all nodes that have this node as ascendant
  17675. * @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
  17676. * @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
  17677. * @return all children nodes of all types
  17678. */
  17679. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17680. var results = new Array();
  17681. this._getDescendants(results, directDescendantsOnly, predicate);
  17682. return results;
  17683. };
  17684. /**
  17685. * Get all child-meshes of this node
  17686. * @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
  17687. * @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
  17688. * @returns an array of {BABYLON.AbstractMesh}
  17689. */
  17690. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17691. var results = [];
  17692. this._getDescendants(results, directDescendantsOnly, function (node) {
  17693. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17694. });
  17695. return results;
  17696. };
  17697. /**
  17698. * Get all child-transformNodes of this node
  17699. * @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
  17700. * @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
  17701. * @returns an array of {BABYLON.TransformNode}
  17702. */
  17703. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17704. var results = [];
  17705. this._getDescendants(results, directDescendantsOnly, function (node) {
  17706. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17707. });
  17708. return results;
  17709. };
  17710. /**
  17711. * Get all direct children of this node
  17712. * @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
  17713. * @returns an array of {BABYLON.Node}
  17714. */
  17715. Node.prototype.getChildren = function (predicate) {
  17716. return this.getDescendants(true, predicate);
  17717. };
  17718. /** @hidden */
  17719. Node.prototype._setReady = function (state) {
  17720. if (state === this._isReady) {
  17721. return;
  17722. }
  17723. if (!state) {
  17724. this._isReady = false;
  17725. return;
  17726. }
  17727. if (this.onReady) {
  17728. this.onReady(this);
  17729. }
  17730. this._isReady = true;
  17731. };
  17732. /**
  17733. * Get an animation by name
  17734. * @param name defines the name of the animation to look for
  17735. * @returns null if not found else the requested animation
  17736. */
  17737. Node.prototype.getAnimationByName = function (name) {
  17738. for (var i = 0; i < this.animations.length; i++) {
  17739. var animation = this.animations[i];
  17740. if (animation.name === name) {
  17741. return animation;
  17742. }
  17743. }
  17744. return null;
  17745. };
  17746. /**
  17747. * Creates an animation range for this node
  17748. * @param name defines the name of the range
  17749. * @param from defines the starting key
  17750. * @param to defines the end key
  17751. */
  17752. Node.prototype.createAnimationRange = function (name, from, to) {
  17753. // check name not already in use
  17754. if (!this._ranges[name]) {
  17755. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17756. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17757. if (this.animations[i]) {
  17758. this.animations[i].createRange(name, from, to);
  17759. }
  17760. }
  17761. }
  17762. };
  17763. /**
  17764. * Delete a specific animation range
  17765. * @param name defines the name of the range to delete
  17766. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17767. */
  17768. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17769. if (deleteFrames === void 0) { deleteFrames = true; }
  17770. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17771. if (this.animations[i]) {
  17772. this.animations[i].deleteRange(name, deleteFrames);
  17773. }
  17774. }
  17775. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17776. };
  17777. /**
  17778. * Get an animation range by name
  17779. * @param name defines the name of the animation range to look for
  17780. * @returns null if not found else the requested animation range
  17781. */
  17782. Node.prototype.getAnimationRange = function (name) {
  17783. return this._ranges[name];
  17784. };
  17785. /**
  17786. * Will start the animation sequence
  17787. * @param name defines the range frames for animation sequence
  17788. * @param loop defines if the animation should loop (false by default)
  17789. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17790. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17791. * @returns the object created for this animation. If range does not exist, it will return null
  17792. */
  17793. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17794. var range = this.getAnimationRange(name);
  17795. if (!range) {
  17796. return null;
  17797. }
  17798. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17799. };
  17800. /**
  17801. * Serialize animation ranges into a JSON compatible object
  17802. * @returns serialization object
  17803. */
  17804. Node.prototype.serializeAnimationRanges = function () {
  17805. var serializationRanges = [];
  17806. for (var name in this._ranges) {
  17807. var localRange = this._ranges[name];
  17808. if (!localRange) {
  17809. continue;
  17810. }
  17811. var range = {};
  17812. range.name = name;
  17813. range.from = localRange.from;
  17814. range.to = localRange.to;
  17815. serializationRanges.push(range);
  17816. }
  17817. return serializationRanges;
  17818. };
  17819. /**
  17820. * Computes the world matrix of the node
  17821. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17822. * @returns the world matrix
  17823. */
  17824. Node.prototype.computeWorldMatrix = function (force) {
  17825. return BABYLON.Matrix.Identity();
  17826. };
  17827. /**
  17828. * Releases resources associated with this node.
  17829. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17830. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17831. */
  17832. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17833. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17834. if (!doNotRecurse) {
  17835. var nodes = this.getDescendants(true);
  17836. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17837. var node = nodes_1[_i];
  17838. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17839. }
  17840. }
  17841. else {
  17842. var transformNodes = this.getChildTransformNodes(true);
  17843. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17844. var transformNode = transformNodes_1[_a];
  17845. transformNode.parent = null;
  17846. transformNode.computeWorldMatrix(true);
  17847. }
  17848. }
  17849. this.parent = null;
  17850. // Callback
  17851. this.onDisposeObservable.notifyObservers(this);
  17852. this.onDisposeObservable.clear();
  17853. // Behaviors
  17854. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17855. var behavior = _c[_b];
  17856. behavior.detach();
  17857. }
  17858. this._behaviors = [];
  17859. this._isDisposed = true;
  17860. };
  17861. /**
  17862. * Parse animation range data from a serialization object and store them into a given node
  17863. * @param node defines where to store the animation ranges
  17864. * @param parsedNode defines the serialization object to read data from
  17865. * @param scene defines the hosting scene
  17866. */
  17867. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17868. if (parsedNode.ranges) {
  17869. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17870. var data = parsedNode.ranges[index];
  17871. node.createAnimationRange(data.name, data.from, data.to);
  17872. }
  17873. }
  17874. };
  17875. __decorate([
  17876. BABYLON.serialize()
  17877. ], Node.prototype, "name", void 0);
  17878. __decorate([
  17879. BABYLON.serialize()
  17880. ], Node.prototype, "id", void 0);
  17881. __decorate([
  17882. BABYLON.serialize()
  17883. ], Node.prototype, "uniqueId", void 0);
  17884. __decorate([
  17885. BABYLON.serialize()
  17886. ], Node.prototype, "state", void 0);
  17887. __decorate([
  17888. BABYLON.serialize()
  17889. ], Node.prototype, "metadata", void 0);
  17890. return Node;
  17891. }());
  17892. BABYLON.Node = Node;
  17893. })(BABYLON || (BABYLON = {}));
  17894. //# sourceMappingURL=babylon.node.js.map
  17895. var BABYLON;
  17896. (function (BABYLON) {
  17897. var BoundingSphere = /** @class */ (function () {
  17898. /**
  17899. * Creates a new bounding sphere
  17900. * @param min defines the minimum vector (in local space)
  17901. * @param max defines the maximum vector (in local space)
  17902. */
  17903. function BoundingSphere(min, max) {
  17904. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17905. this.reConstruct(min, max);
  17906. }
  17907. /**
  17908. * Recreates the entire bounding sphere from scratch
  17909. * @param min defines the new minimum vector (in local space)
  17910. * @param max defines the new maximum vector (in local space)
  17911. */
  17912. BoundingSphere.prototype.reConstruct = function (min, max) {
  17913. this.minimum = min.clone();
  17914. this.maximum = max.clone();
  17915. var distance = BABYLON.Vector3.Distance(min, max);
  17916. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17917. this.radius = distance * 0.5;
  17918. this.centerWorld = BABYLON.Vector3.Zero();
  17919. this._update(BABYLON.Matrix.Identity());
  17920. };
  17921. // Methods
  17922. BoundingSphere.prototype._update = function (world) {
  17923. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17924. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17925. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17926. };
  17927. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17928. for (var i = 0; i < 6; i++) {
  17929. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17930. return false;
  17931. }
  17932. return true;
  17933. };
  17934. BoundingSphere.prototype.intersectsPoint = function (point) {
  17935. var x = this.centerWorld.x - point.x;
  17936. var y = this.centerWorld.y - point.y;
  17937. var z = this.centerWorld.z - point.z;
  17938. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17939. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17940. return false;
  17941. return true;
  17942. };
  17943. // Statics
  17944. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17945. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17946. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17947. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17948. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17949. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17950. return false;
  17951. return true;
  17952. };
  17953. return BoundingSphere;
  17954. }());
  17955. BABYLON.BoundingSphere = BoundingSphere;
  17956. })(BABYLON || (BABYLON = {}));
  17957. //# sourceMappingURL=babylon.boundingSphere.js.map
  17958. var BABYLON;
  17959. (function (BABYLON) {
  17960. var BoundingBox = /** @class */ (function () {
  17961. /**
  17962. * Creates a new bounding box
  17963. * @param min defines the minimum vector (in local space)
  17964. * @param max defines the maximum vector (in local space)
  17965. */
  17966. function BoundingBox(min, max) {
  17967. this.vectorsWorld = new Array();
  17968. this.reConstruct(min, max);
  17969. }
  17970. // Methods
  17971. /**
  17972. * Recreates the entire bounding box from scratch
  17973. * @param min defines the new minimum vector (in local space)
  17974. * @param max defines the new maximum vector (in local space)
  17975. */
  17976. BoundingBox.prototype.reConstruct = function (min, max) {
  17977. this.minimum = min.clone();
  17978. this.maximum = max.clone();
  17979. // Bounding vectors
  17980. this.vectors = new Array();
  17981. this.vectors.push(this.minimum.clone());
  17982. this.vectors.push(this.maximum.clone());
  17983. this.vectors.push(this.minimum.clone());
  17984. this.vectors[2].x = this.maximum.x;
  17985. this.vectors.push(this.minimum.clone());
  17986. this.vectors[3].y = this.maximum.y;
  17987. this.vectors.push(this.minimum.clone());
  17988. this.vectors[4].z = this.maximum.z;
  17989. this.vectors.push(this.maximum.clone());
  17990. this.vectors[5].z = this.minimum.z;
  17991. this.vectors.push(this.maximum.clone());
  17992. this.vectors[6].x = this.minimum.x;
  17993. this.vectors.push(this.maximum.clone());
  17994. this.vectors[7].y = this.minimum.y;
  17995. // OBB
  17996. this.center = this.maximum.add(this.minimum).scale(0.5);
  17997. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  17998. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  17999. // World
  18000. for (var index = 0; index < this.vectors.length; index++) {
  18001. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18002. }
  18003. this.minimumWorld = BABYLON.Vector3.Zero();
  18004. this.maximumWorld = BABYLON.Vector3.Zero();
  18005. this.centerWorld = BABYLON.Vector3.Zero();
  18006. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18007. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18008. };
  18009. BoundingBox.prototype.getWorldMatrix = function () {
  18010. return this._worldMatrix;
  18011. };
  18012. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18013. this._worldMatrix.copyFrom(matrix);
  18014. return this;
  18015. };
  18016. BoundingBox.prototype._update = function (world) {
  18017. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18018. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18019. for (var index = 0; index < this.vectors.length; index++) {
  18020. var v = this.vectorsWorld[index];
  18021. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18022. if (v.x < this.minimumWorld.x)
  18023. this.minimumWorld.x = v.x;
  18024. if (v.y < this.minimumWorld.y)
  18025. this.minimumWorld.y = v.y;
  18026. if (v.z < this.minimumWorld.z)
  18027. this.minimumWorld.z = v.z;
  18028. if (v.x > this.maximumWorld.x)
  18029. this.maximumWorld.x = v.x;
  18030. if (v.y > this.maximumWorld.y)
  18031. this.maximumWorld.y = v.y;
  18032. if (v.z > this.maximumWorld.z)
  18033. this.maximumWorld.z = v.z;
  18034. }
  18035. // Extend
  18036. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18037. this.extendSizeWorld.scaleInPlace(0.5);
  18038. // OBB
  18039. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18040. this.centerWorld.scaleInPlace(0.5);
  18041. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18042. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18043. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18044. this._worldMatrix = world;
  18045. };
  18046. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18047. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18048. };
  18049. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18050. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18051. };
  18052. BoundingBox.prototype.intersectsPoint = function (point) {
  18053. var delta = -BABYLON.Epsilon;
  18054. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18055. return false;
  18056. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18057. return false;
  18058. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18059. return false;
  18060. return true;
  18061. };
  18062. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18063. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18064. };
  18065. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18066. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18067. return false;
  18068. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18069. return false;
  18070. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18071. return false;
  18072. return true;
  18073. };
  18074. // Statics
  18075. BoundingBox.Intersects = function (box0, box1) {
  18076. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18077. return false;
  18078. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18079. return false;
  18080. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18081. return false;
  18082. return true;
  18083. };
  18084. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18085. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18086. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18087. return (num <= (sphereRadius * sphereRadius));
  18088. };
  18089. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18090. for (var p = 0; p < 6; p++) {
  18091. for (var i = 0; i < 8; i++) {
  18092. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18093. return false;
  18094. }
  18095. }
  18096. }
  18097. return true;
  18098. };
  18099. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18100. for (var p = 0; p < 6; p++) {
  18101. var inCount = 8;
  18102. for (var i = 0; i < 8; i++) {
  18103. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18104. --inCount;
  18105. }
  18106. else {
  18107. break;
  18108. }
  18109. }
  18110. if (inCount === 0)
  18111. return false;
  18112. }
  18113. return true;
  18114. };
  18115. return BoundingBox;
  18116. }());
  18117. BABYLON.BoundingBox = BoundingBox;
  18118. })(BABYLON || (BABYLON = {}));
  18119. //# sourceMappingURL=babylon.boundingBox.js.map
  18120. var BABYLON;
  18121. (function (BABYLON) {
  18122. var computeBoxExtents = function (axis, box) {
  18123. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18124. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18125. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18126. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18127. var r = r0 + r1 + r2;
  18128. return {
  18129. min: p - r,
  18130. max: p + r
  18131. };
  18132. };
  18133. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18134. var axisOverlap = function (axis, box0, box1) {
  18135. var result0 = computeBoxExtents(axis, box0);
  18136. var result1 = computeBoxExtents(axis, box1);
  18137. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18138. };
  18139. var BoundingInfo = /** @class */ (function () {
  18140. function BoundingInfo(minimum, maximum) {
  18141. this.minimum = minimum;
  18142. this.maximum = maximum;
  18143. this._isLocked = false;
  18144. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18145. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18146. }
  18147. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18148. get: function () {
  18149. return this._isLocked;
  18150. },
  18151. set: function (value) {
  18152. this._isLocked = value;
  18153. },
  18154. enumerable: true,
  18155. configurable: true
  18156. });
  18157. // Methods
  18158. BoundingInfo.prototype.update = function (world) {
  18159. if (this._isLocked) {
  18160. return;
  18161. }
  18162. this.boundingBox._update(world);
  18163. this.boundingSphere._update(world);
  18164. };
  18165. /**
  18166. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18167. * @param center New center of the bounding info
  18168. * @param extend New extend of the bounding info
  18169. */
  18170. BoundingInfo.prototype.centerOn = function (center, extend) {
  18171. this.minimum = center.subtract(extend);
  18172. this.maximum = center.add(extend);
  18173. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18174. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18175. return this;
  18176. };
  18177. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18178. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18179. return false;
  18180. return this.boundingBox.isInFrustum(frustumPlanes);
  18181. };
  18182. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18183. /**
  18184. * Gets the world distance between the min and max points of the bounding box
  18185. */
  18186. get: function () {
  18187. var boundingBox = this.boundingBox;
  18188. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18189. return size.length();
  18190. },
  18191. enumerable: true,
  18192. configurable: true
  18193. });
  18194. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18195. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18196. };
  18197. BoundingInfo.prototype._checkCollision = function (collider) {
  18198. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18199. };
  18200. BoundingInfo.prototype.intersectsPoint = function (point) {
  18201. if (!this.boundingSphere.centerWorld) {
  18202. return false;
  18203. }
  18204. if (!this.boundingSphere.intersectsPoint(point)) {
  18205. return false;
  18206. }
  18207. if (!this.boundingBox.intersectsPoint(point)) {
  18208. return false;
  18209. }
  18210. return true;
  18211. };
  18212. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18213. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18214. return false;
  18215. }
  18216. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18217. return false;
  18218. }
  18219. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18220. return false;
  18221. }
  18222. if (!precise) {
  18223. return true;
  18224. }
  18225. var box0 = this.boundingBox;
  18226. var box1 = boundingInfo.boundingBox;
  18227. if (!axisOverlap(box0.directions[0], box0, box1))
  18228. return false;
  18229. if (!axisOverlap(box0.directions[1], box0, box1))
  18230. return false;
  18231. if (!axisOverlap(box0.directions[2], box0, box1))
  18232. return false;
  18233. if (!axisOverlap(box1.directions[0], box0, box1))
  18234. return false;
  18235. if (!axisOverlap(box1.directions[1], box0, box1))
  18236. return false;
  18237. if (!axisOverlap(box1.directions[2], box0, box1))
  18238. return false;
  18239. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18240. return false;
  18241. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18242. return false;
  18243. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18244. return false;
  18245. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18246. return false;
  18247. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18248. return false;
  18249. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18250. return false;
  18251. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18252. return false;
  18253. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18254. return false;
  18255. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18256. return false;
  18257. return true;
  18258. };
  18259. return BoundingInfo;
  18260. }());
  18261. BABYLON.BoundingInfo = BoundingInfo;
  18262. })(BABYLON || (BABYLON = {}));
  18263. //# sourceMappingURL=babylon.boundingInfo.js.map
  18264. var BABYLON;
  18265. (function (BABYLON) {
  18266. var TransformNode = /** @class */ (function (_super) {
  18267. __extends(TransformNode, _super);
  18268. function TransformNode(name, scene, isPure) {
  18269. if (scene === void 0) { scene = null; }
  18270. if (isPure === void 0) { isPure = true; }
  18271. var _this = _super.call(this, name, scene) || this;
  18272. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18273. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18274. _this._up = new BABYLON.Vector3(0, 1, 0);
  18275. _this._right = new BABYLON.Vector3(1, 0, 0);
  18276. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18277. // Properties
  18278. _this._rotation = BABYLON.Vector3.Zero();
  18279. _this._scaling = BABYLON.Vector3.One();
  18280. _this._isDirty = false;
  18281. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18282. _this.scalingDeterminant = 1;
  18283. _this.infiniteDistance = false;
  18284. _this.position = BABYLON.Vector3.Zero();
  18285. _this._localWorld = BABYLON.Matrix.Zero();
  18286. _this._worldMatrix = BABYLON.Matrix.Zero();
  18287. _this._worldMatrixDeterminant = 0;
  18288. _this._absolutePosition = BABYLON.Vector3.Zero();
  18289. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18290. _this._postMultiplyPivotMatrix = false;
  18291. _this._isWorldMatrixFrozen = false;
  18292. /**
  18293. * An event triggered after the world matrix is updated
  18294. */
  18295. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18296. _this._nonUniformScaling = false;
  18297. if (isPure) {
  18298. _this.getScene().addTransformNode(_this);
  18299. }
  18300. return _this;
  18301. }
  18302. /**
  18303. * Gets a string idenfifying the name of the class
  18304. * @returns "TransformNode" string
  18305. */
  18306. TransformNode.prototype.getClassName = function () {
  18307. return "TransformNode";
  18308. };
  18309. Object.defineProperty(TransformNode.prototype, "rotation", {
  18310. /**
  18311. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18312. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18313. * Default : (0.0, 0.0, 0.0)
  18314. */
  18315. get: function () {
  18316. return this._rotation;
  18317. },
  18318. set: function (newRotation) {
  18319. this._rotation = newRotation;
  18320. },
  18321. enumerable: true,
  18322. configurable: true
  18323. });
  18324. Object.defineProperty(TransformNode.prototype, "scaling", {
  18325. /**
  18326. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18327. * Default : (1.0, 1.0, 1.0)
  18328. */
  18329. get: function () {
  18330. return this._scaling;
  18331. },
  18332. /**
  18333. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18334. * Default : (1.0, 1.0, 1.0)
  18335. */
  18336. set: function (newScaling) {
  18337. this._scaling = newScaling;
  18338. },
  18339. enumerable: true,
  18340. configurable: true
  18341. });
  18342. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18343. /**
  18344. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18345. * It's null by default.
  18346. * 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)
  18347. */
  18348. get: function () {
  18349. return this._rotationQuaternion;
  18350. },
  18351. set: function (quaternion) {
  18352. this._rotationQuaternion = quaternion;
  18353. //reset the rotation vector.
  18354. if (quaternion && this.rotation.length()) {
  18355. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18356. }
  18357. },
  18358. enumerable: true,
  18359. configurable: true
  18360. });
  18361. Object.defineProperty(TransformNode.prototype, "forward", {
  18362. /**
  18363. * The forward direction of that transform in world space.
  18364. */
  18365. get: function () {
  18366. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18367. },
  18368. enumerable: true,
  18369. configurable: true
  18370. });
  18371. Object.defineProperty(TransformNode.prototype, "up", {
  18372. /**
  18373. * The up direction of that transform in world space.
  18374. */
  18375. get: function () {
  18376. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18377. },
  18378. enumerable: true,
  18379. configurable: true
  18380. });
  18381. Object.defineProperty(TransformNode.prototype, "right", {
  18382. /**
  18383. * The right direction of that transform in world space.
  18384. */
  18385. get: function () {
  18386. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18387. },
  18388. enumerable: true,
  18389. configurable: true
  18390. });
  18391. /**
  18392. * Returns the latest update of the World matrix
  18393. * Returns a Matrix.
  18394. */
  18395. TransformNode.prototype.getWorldMatrix = function () {
  18396. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18397. this.computeWorldMatrix();
  18398. }
  18399. return this._worldMatrix;
  18400. };
  18401. /** @hidden */
  18402. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18403. return this._worldMatrixDeterminant;
  18404. };
  18405. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18406. /**
  18407. * Returns directly the latest state of the mesh World matrix.
  18408. * A Matrix is returned.
  18409. */
  18410. get: function () {
  18411. return this._worldMatrix;
  18412. },
  18413. enumerable: true,
  18414. configurable: true
  18415. });
  18416. /**
  18417. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18418. * Returns the TransformNode.
  18419. */
  18420. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18421. this._poseMatrix.copyFrom(matrix);
  18422. return this;
  18423. };
  18424. /**
  18425. * Returns the mesh Pose matrix.
  18426. * Returned object : Matrix
  18427. */
  18428. TransformNode.prototype.getPoseMatrix = function () {
  18429. return this._poseMatrix;
  18430. };
  18431. TransformNode.prototype._isSynchronized = function () {
  18432. if (this._isDirty) {
  18433. return false;
  18434. }
  18435. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18436. return false;
  18437. if (this._cache.pivotMatrixUpdated) {
  18438. return false;
  18439. }
  18440. if (this.infiniteDistance) {
  18441. return false;
  18442. }
  18443. if (!this._cache.position.equals(this.position))
  18444. return false;
  18445. if (this.rotationQuaternion) {
  18446. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18447. return false;
  18448. }
  18449. if (!this._cache.rotation.equals(this.rotation))
  18450. return false;
  18451. if (!this._cache.scaling.equals(this.scaling))
  18452. return false;
  18453. return true;
  18454. };
  18455. TransformNode.prototype._initCache = function () {
  18456. _super.prototype._initCache.call(this);
  18457. this._cache.localMatrixUpdated = false;
  18458. this._cache.position = BABYLON.Vector3.Zero();
  18459. this._cache.scaling = BABYLON.Vector3.Zero();
  18460. this._cache.rotation = BABYLON.Vector3.Zero();
  18461. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18462. this._cache.billboardMode = -1;
  18463. };
  18464. TransformNode.prototype.markAsDirty = function (property) {
  18465. if (property === "rotation") {
  18466. this.rotationQuaternion = null;
  18467. }
  18468. this._currentRenderId = Number.MAX_VALUE;
  18469. this._isDirty = true;
  18470. return this;
  18471. };
  18472. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18473. /**
  18474. * Returns the current mesh absolute position.
  18475. * Retuns a Vector3.
  18476. */
  18477. get: function () {
  18478. return this._absolutePosition;
  18479. },
  18480. enumerable: true,
  18481. configurable: true
  18482. });
  18483. /**
  18484. * Sets a new matrix to apply before all other transformation
  18485. * @param matrix defines the transform matrix
  18486. * @returns the current TransformNode
  18487. */
  18488. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18489. return this.setPivotMatrix(matrix, false);
  18490. };
  18491. /**
  18492. * Sets a new pivot matrix to the current node
  18493. * @param matrix defines the new pivot matrix to use
  18494. * @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
  18495. * @returns the current TransformNode
  18496. */
  18497. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18498. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18499. this._pivotMatrix = matrix.clone();
  18500. this._cache.pivotMatrixUpdated = true;
  18501. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18502. if (this._postMultiplyPivotMatrix) {
  18503. if (!this._pivotMatrixInverse) {
  18504. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18505. }
  18506. else {
  18507. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18508. }
  18509. }
  18510. return this;
  18511. };
  18512. /**
  18513. * Returns the mesh pivot matrix.
  18514. * Default : Identity.
  18515. * A Matrix is returned.
  18516. */
  18517. TransformNode.prototype.getPivotMatrix = function () {
  18518. return this._pivotMatrix;
  18519. };
  18520. /**
  18521. * Prevents the World matrix to be computed any longer.
  18522. * Returns the TransformNode.
  18523. */
  18524. TransformNode.prototype.freezeWorldMatrix = function () {
  18525. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18526. this.computeWorldMatrix(true);
  18527. this._isWorldMatrixFrozen = true;
  18528. return this;
  18529. };
  18530. /**
  18531. * Allows back the World matrix computation.
  18532. * Returns the TransformNode.
  18533. */
  18534. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18535. this._isWorldMatrixFrozen = false;
  18536. this.computeWorldMatrix(true);
  18537. return this;
  18538. };
  18539. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18540. /**
  18541. * True if the World matrix has been frozen.
  18542. * Returns a boolean.
  18543. */
  18544. get: function () {
  18545. return this._isWorldMatrixFrozen;
  18546. },
  18547. enumerable: true,
  18548. configurable: true
  18549. });
  18550. /**
  18551. * Retuns the mesh absolute position in the World.
  18552. * Returns a Vector3.
  18553. */
  18554. TransformNode.prototype.getAbsolutePosition = function () {
  18555. this.computeWorldMatrix();
  18556. return this._absolutePosition;
  18557. };
  18558. /**
  18559. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18560. * Returns the TransformNode.
  18561. */
  18562. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18563. if (!absolutePosition) {
  18564. return this;
  18565. }
  18566. var absolutePositionX;
  18567. var absolutePositionY;
  18568. var absolutePositionZ;
  18569. if (absolutePosition.x === undefined) {
  18570. if (arguments.length < 3) {
  18571. return this;
  18572. }
  18573. absolutePositionX = arguments[0];
  18574. absolutePositionY = arguments[1];
  18575. absolutePositionZ = arguments[2];
  18576. }
  18577. else {
  18578. absolutePositionX = absolutePosition.x;
  18579. absolutePositionY = absolutePosition.y;
  18580. absolutePositionZ = absolutePosition.z;
  18581. }
  18582. if (this.parent) {
  18583. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18584. invertParentWorldMatrix.invert();
  18585. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18586. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18587. }
  18588. else {
  18589. this.position.x = absolutePositionX;
  18590. this.position.y = absolutePositionY;
  18591. this.position.z = absolutePositionZ;
  18592. }
  18593. return this;
  18594. };
  18595. /**
  18596. * Sets the mesh position in its local space.
  18597. * Returns the TransformNode.
  18598. */
  18599. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18600. this.computeWorldMatrix();
  18601. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18602. return this;
  18603. };
  18604. /**
  18605. * Returns the mesh position in the local space from the current World matrix values.
  18606. * Returns a new Vector3.
  18607. */
  18608. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18609. this.computeWorldMatrix();
  18610. var invLocalWorldMatrix = this._localWorld.clone();
  18611. invLocalWorldMatrix.invert();
  18612. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18613. };
  18614. /**
  18615. * Translates the mesh along the passed Vector3 in its local space.
  18616. * Returns the TransformNode.
  18617. */
  18618. TransformNode.prototype.locallyTranslate = function (vector3) {
  18619. this.computeWorldMatrix(true);
  18620. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18621. return this;
  18622. };
  18623. /**
  18624. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18625. * @param targetPoint the position (must be in same space as current mesh) to look at
  18626. * @param yawCor optional yaw (y-axis) correction in radians
  18627. * @param pitchCor optional pitch (x-axis) correction in radians
  18628. * @param rollCor optional roll (z-axis) correction in radians
  18629. * @param space the choosen space of the target
  18630. * @returns the TransformNode.
  18631. */
  18632. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18633. if (yawCor === void 0) { yawCor = 0; }
  18634. if (pitchCor === void 0) { pitchCor = 0; }
  18635. if (rollCor === void 0) { rollCor = 0; }
  18636. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18637. var dv = TransformNode._lookAtVectorCache;
  18638. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18639. targetPoint.subtractToRef(pos, dv);
  18640. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18641. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18642. var pitch = Math.atan2(dv.y, len);
  18643. if (this.rotationQuaternion) {
  18644. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18645. }
  18646. else {
  18647. this.rotation.x = pitch + pitchCor;
  18648. this.rotation.y = yaw + yawCor;
  18649. this.rotation.z = rollCor;
  18650. }
  18651. return this;
  18652. };
  18653. /**
  18654. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18655. * This Vector3 is expressed in the World space.
  18656. */
  18657. TransformNode.prototype.getDirection = function (localAxis) {
  18658. var result = BABYLON.Vector3.Zero();
  18659. this.getDirectionToRef(localAxis, result);
  18660. return result;
  18661. };
  18662. /**
  18663. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18664. * localAxis is expressed in the mesh local space.
  18665. * result is computed in the Wordl space from the mesh World matrix.
  18666. * Returns the TransformNode.
  18667. */
  18668. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18669. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18670. return this;
  18671. };
  18672. /**
  18673. * Sets a new pivot point to the current node
  18674. * @param point defines the new pivot point to use
  18675. * @param space defines if the point is in world or local space (local by default)
  18676. * @returns the current TransformNode
  18677. */
  18678. TransformNode.prototype.setPivotPoint = function (point, space) {
  18679. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18680. if (this.getScene().getRenderId() == 0) {
  18681. this.computeWorldMatrix(true);
  18682. }
  18683. var wm = this.getWorldMatrix();
  18684. if (space == BABYLON.Space.WORLD) {
  18685. var tmat = BABYLON.Tmp.Matrix[0];
  18686. wm.invertToRef(tmat);
  18687. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18688. }
  18689. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18690. };
  18691. /**
  18692. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18693. */
  18694. TransformNode.prototype.getPivotPoint = function () {
  18695. var point = BABYLON.Vector3.Zero();
  18696. this.getPivotPointToRef(point);
  18697. return point;
  18698. };
  18699. /**
  18700. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18701. * Returns the TransformNode.
  18702. */
  18703. TransformNode.prototype.getPivotPointToRef = function (result) {
  18704. result.x = -this._pivotMatrix.m[12];
  18705. result.y = -this._pivotMatrix.m[13];
  18706. result.z = -this._pivotMatrix.m[14];
  18707. return this;
  18708. };
  18709. /**
  18710. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18711. */
  18712. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18713. var point = BABYLON.Vector3.Zero();
  18714. this.getAbsolutePivotPointToRef(point);
  18715. return point;
  18716. };
  18717. /**
  18718. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18719. * Returns the TransformNode.
  18720. */
  18721. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18722. result.x = this._pivotMatrix.m[12];
  18723. result.y = this._pivotMatrix.m[13];
  18724. result.z = this._pivotMatrix.m[14];
  18725. this.getPivotPointToRef(result);
  18726. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18727. return this;
  18728. };
  18729. /**
  18730. * Defines the passed node as the parent of the current node.
  18731. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18732. * Returns the TransformNode.
  18733. */
  18734. TransformNode.prototype.setParent = function (node) {
  18735. if (node === null) {
  18736. var rotation = BABYLON.Tmp.Quaternion[0];
  18737. var position = BABYLON.Tmp.Vector3[0];
  18738. var scale = BABYLON.Tmp.Vector3[1];
  18739. if (this.parent && this.parent.computeWorldMatrix) {
  18740. this.parent.computeWorldMatrix(true);
  18741. }
  18742. this.computeWorldMatrix(true);
  18743. this.getWorldMatrix().decompose(scale, rotation, position);
  18744. if (this.rotationQuaternion) {
  18745. this.rotationQuaternion.copyFrom(rotation);
  18746. }
  18747. else {
  18748. rotation.toEulerAnglesToRef(this.rotation);
  18749. }
  18750. this.scaling.x = scale.x;
  18751. this.scaling.y = scale.y;
  18752. this.scaling.z = scale.z;
  18753. this.position.x = position.x;
  18754. this.position.y = position.y;
  18755. this.position.z = position.z;
  18756. }
  18757. else {
  18758. var rotation = BABYLON.Tmp.Quaternion[0];
  18759. var position = BABYLON.Tmp.Vector3[0];
  18760. var scale = BABYLON.Tmp.Vector3[1];
  18761. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18762. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18763. this.computeWorldMatrix(true);
  18764. node.computeWorldMatrix(true);
  18765. node.getWorldMatrix().invertToRef(invParentMatrix);
  18766. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18767. diffMatrix.decompose(scale, rotation, position);
  18768. if (this.rotationQuaternion) {
  18769. this.rotationQuaternion.copyFrom(rotation);
  18770. }
  18771. else {
  18772. rotation.toEulerAnglesToRef(this.rotation);
  18773. }
  18774. this.position.x = position.x;
  18775. this.position.y = position.y;
  18776. this.position.z = position.z;
  18777. this.scaling.x = scale.x;
  18778. this.scaling.y = scale.y;
  18779. this.scaling.z = scale.z;
  18780. }
  18781. this.parent = node;
  18782. return this;
  18783. };
  18784. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18785. get: function () {
  18786. return this._nonUniformScaling;
  18787. },
  18788. enumerable: true,
  18789. configurable: true
  18790. });
  18791. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18792. if (this._nonUniformScaling === value) {
  18793. return false;
  18794. }
  18795. this._nonUniformScaling = true;
  18796. return true;
  18797. };
  18798. /**
  18799. * Attach the current TransformNode to another TransformNode associated with a bone
  18800. * @param bone Bone affecting the TransformNode
  18801. * @param affectedTransformNode TransformNode associated with the bone
  18802. */
  18803. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18804. this._transformToBoneReferal = affectedTransformNode;
  18805. this.parent = bone;
  18806. if (bone.getWorldMatrix().determinant() < 0) {
  18807. this.scalingDeterminant *= -1;
  18808. }
  18809. return this;
  18810. };
  18811. TransformNode.prototype.detachFromBone = function () {
  18812. if (!this.parent) {
  18813. return this;
  18814. }
  18815. if (this.parent.getWorldMatrix().determinant() < 0) {
  18816. this.scalingDeterminant *= -1;
  18817. }
  18818. this._transformToBoneReferal = null;
  18819. this.parent = null;
  18820. return this;
  18821. };
  18822. /**
  18823. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18824. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18825. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18826. * The passed axis is also normalized.
  18827. * Returns the TransformNode.
  18828. */
  18829. TransformNode.prototype.rotate = function (axis, amount, space) {
  18830. axis.normalize();
  18831. if (!this.rotationQuaternion) {
  18832. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18833. this.rotation = BABYLON.Vector3.Zero();
  18834. }
  18835. var rotationQuaternion;
  18836. if (!space || space === BABYLON.Space.LOCAL) {
  18837. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18838. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18839. }
  18840. else {
  18841. if (this.parent) {
  18842. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18843. invertParentWorldMatrix.invert();
  18844. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18845. }
  18846. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18847. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18848. }
  18849. return this;
  18850. };
  18851. /**
  18852. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18853. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18854. * The passed axis is also normalized.
  18855. * Returns the TransformNode.
  18856. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18857. */
  18858. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18859. axis.normalize();
  18860. if (!this.rotationQuaternion) {
  18861. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18862. this.rotation.copyFromFloats(0, 0, 0);
  18863. }
  18864. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18865. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18866. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18867. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18868. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18869. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18870. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18871. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18872. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18873. return this;
  18874. };
  18875. /**
  18876. * Translates the mesh along the axis vector for the passed distance in the given space.
  18877. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18878. * Returns the TransformNode.
  18879. */
  18880. TransformNode.prototype.translate = function (axis, distance, space) {
  18881. var displacementVector = axis.scale(distance);
  18882. if (!space || space === BABYLON.Space.LOCAL) {
  18883. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18884. this.setPositionWithLocalVector(tempV3);
  18885. }
  18886. else {
  18887. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18888. }
  18889. return this;
  18890. };
  18891. /**
  18892. * Adds a rotation step to the mesh current rotation.
  18893. * x, y, z are Euler angles expressed in radians.
  18894. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18895. * This means this rotation is made in the mesh local space only.
  18896. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18897. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18898. * ```javascript
  18899. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18900. * ```
  18901. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18902. * 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.
  18903. * Returns the TransformNode.
  18904. */
  18905. TransformNode.prototype.addRotation = function (x, y, z) {
  18906. var rotationQuaternion;
  18907. if (this.rotationQuaternion) {
  18908. rotationQuaternion = this.rotationQuaternion;
  18909. }
  18910. else {
  18911. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18912. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18913. }
  18914. var accumulation = BABYLON.Tmp.Quaternion[0];
  18915. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18916. rotationQuaternion.multiplyInPlace(accumulation);
  18917. if (!this.rotationQuaternion) {
  18918. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18919. }
  18920. return this;
  18921. };
  18922. /**
  18923. * Computes the mesh World matrix and returns it.
  18924. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18925. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18926. * If the parameter `force`is set to `true`, the actual computation is done.
  18927. * Returns the mesh World Matrix.
  18928. */
  18929. TransformNode.prototype.computeWorldMatrix = function (force) {
  18930. if (this._isWorldMatrixFrozen) {
  18931. return this._worldMatrix;
  18932. }
  18933. if (!force && this.isSynchronized(true)) {
  18934. this._currentRenderId = this.getScene().getRenderId();
  18935. return this._worldMatrix;
  18936. }
  18937. this._cache.position.copyFrom(this.position);
  18938. this._cache.scaling.copyFrom(this.scaling);
  18939. this._cache.pivotMatrixUpdated = false;
  18940. this._cache.billboardMode = this.billboardMode;
  18941. this._currentRenderId = this.getScene().getRenderId();
  18942. this._childRenderId = this.getScene().getRenderId();
  18943. this._isDirty = false;
  18944. // Scaling
  18945. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18946. // Rotation
  18947. //rotate, if quaternion is set and rotation was used
  18948. if (this.rotationQuaternion) {
  18949. var len = this.rotation.length();
  18950. if (len) {
  18951. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18952. this.rotation.copyFromFloats(0, 0, 0);
  18953. }
  18954. }
  18955. if (this.rotationQuaternion) {
  18956. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18957. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18958. }
  18959. else {
  18960. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18961. this._cache.rotation.copyFrom(this.rotation);
  18962. }
  18963. // Translation
  18964. var camera = this.getScene().activeCamera;
  18965. if (this.infiniteDistance && !this.parent && camera) {
  18966. var cameraWorldMatrix = camera.getWorldMatrix();
  18967. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18968. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18969. }
  18970. else {
  18971. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18972. }
  18973. // Composing transformations
  18974. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18975. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18976. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18977. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  18978. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  18979. // Need to decompose each rotation here
  18980. var currentPosition = BABYLON.Tmp.Vector3[3];
  18981. if (this.parent && this.parent.getWorldMatrix) {
  18982. if (this._transformToBoneReferal) {
  18983. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  18984. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  18985. }
  18986. else {
  18987. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  18988. }
  18989. }
  18990. else {
  18991. currentPosition.copyFrom(this.position);
  18992. }
  18993. currentPosition.subtractInPlace(camera.globalPosition);
  18994. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  18995. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  18996. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  18997. }
  18998. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  18999. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19000. }
  19001. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19002. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19003. }
  19004. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19005. }
  19006. else {
  19007. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19008. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19009. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19010. }
  19011. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19012. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19013. }
  19014. // Local world
  19015. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19016. // Parent
  19017. if (this.parent && this.parent.getWorldMatrix) {
  19018. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19019. if (this._transformToBoneReferal) {
  19020. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19021. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19022. }
  19023. else {
  19024. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19025. }
  19026. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19027. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19028. this._worldMatrix.copyFrom(this._localWorld);
  19029. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19030. }
  19031. else {
  19032. if (this._transformToBoneReferal) {
  19033. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19034. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19035. }
  19036. else {
  19037. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19038. }
  19039. }
  19040. this._markSyncedWithParent();
  19041. }
  19042. else {
  19043. this._worldMatrix.copyFrom(this._localWorld);
  19044. }
  19045. // Post multiply inverse of pivotMatrix
  19046. if (this._postMultiplyPivotMatrix) {
  19047. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19048. }
  19049. // Normal matrix
  19050. if (this.scaling.isNonUniform) {
  19051. this._updateNonUniformScalingState(true);
  19052. }
  19053. else if (this.parent && this.parent._nonUniformScaling) {
  19054. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19055. }
  19056. else {
  19057. this._updateNonUniformScalingState(false);
  19058. }
  19059. this._afterComputeWorldMatrix();
  19060. // Absolute position
  19061. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19062. // Callbacks
  19063. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19064. if (!this._poseMatrix) {
  19065. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19066. }
  19067. // Cache the determinant
  19068. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19069. return this._worldMatrix;
  19070. };
  19071. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19072. };
  19073. /**
  19074. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19075. * @param func: callback function to add
  19076. *
  19077. * Returns the TransformNode.
  19078. */
  19079. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19080. this.onAfterWorldMatrixUpdateObservable.add(func);
  19081. return this;
  19082. };
  19083. /**
  19084. * Removes a registered callback function.
  19085. * Returns the TransformNode.
  19086. */
  19087. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19088. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19089. return this;
  19090. };
  19091. /**
  19092. * Clone the current transform node
  19093. * Returns the new transform node
  19094. * @param name Name of the new clone
  19095. * @param newParent New parent for the clone
  19096. * @param doNotCloneChildren Do not clone children hierarchy
  19097. */
  19098. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19099. var _this = this;
  19100. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19101. result.name = name;
  19102. result.id = name;
  19103. if (newParent) {
  19104. result.parent = newParent;
  19105. }
  19106. if (!doNotCloneChildren) {
  19107. // Children
  19108. var directDescendants = this.getDescendants(true);
  19109. for (var index = 0; index < directDescendants.length; index++) {
  19110. var child = directDescendants[index];
  19111. if (child.clone) {
  19112. child.clone(name + "." + child.name, result);
  19113. }
  19114. }
  19115. }
  19116. return result;
  19117. };
  19118. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19119. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19120. serializationObject.type = this.getClassName();
  19121. // Parent
  19122. if (this.parent) {
  19123. serializationObject.parentId = this.parent.id;
  19124. }
  19125. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19126. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19127. }
  19128. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19129. serializationObject.isEnabled = this.isEnabled();
  19130. // Parent
  19131. if (this.parent) {
  19132. serializationObject.parentId = this.parent.id;
  19133. }
  19134. return serializationObject;
  19135. };
  19136. // Statics
  19137. /**
  19138. * Returns a new TransformNode object parsed from the source provided.
  19139. * The parameter `parsedMesh` is the source.
  19140. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19141. */
  19142. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19143. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19144. if (BABYLON.Tags) {
  19145. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19146. }
  19147. if (parsedTransformNode.localMatrix) {
  19148. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19149. }
  19150. else if (parsedTransformNode.pivotMatrix) {
  19151. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19152. }
  19153. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19154. // Parent
  19155. if (parsedTransformNode.parentId) {
  19156. transformNode._waitingParentId = parsedTransformNode.parentId;
  19157. }
  19158. return transformNode;
  19159. };
  19160. /**
  19161. * Releases resources associated with this transform node.
  19162. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19163. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19164. */
  19165. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19166. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19167. // Animations
  19168. this.getScene().stopAnimation(this);
  19169. // Remove from scene
  19170. this.getScene().removeTransformNode(this);
  19171. this.onAfterWorldMatrixUpdateObservable.clear();
  19172. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19173. };
  19174. // Statics
  19175. TransformNode.BILLBOARDMODE_NONE = 0;
  19176. TransformNode.BILLBOARDMODE_X = 1;
  19177. TransformNode.BILLBOARDMODE_Y = 2;
  19178. TransformNode.BILLBOARDMODE_Z = 4;
  19179. TransformNode.BILLBOARDMODE_ALL = 7;
  19180. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19181. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19182. __decorate([
  19183. BABYLON.serializeAsVector3()
  19184. ], TransformNode.prototype, "_rotation", void 0);
  19185. __decorate([
  19186. BABYLON.serializeAsQuaternion()
  19187. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19188. __decorate([
  19189. BABYLON.serializeAsVector3()
  19190. ], TransformNode.prototype, "_scaling", void 0);
  19191. __decorate([
  19192. BABYLON.serialize()
  19193. ], TransformNode.prototype, "billboardMode", void 0);
  19194. __decorate([
  19195. BABYLON.serialize()
  19196. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19197. __decorate([
  19198. BABYLON.serialize()
  19199. ], TransformNode.prototype, "infiniteDistance", void 0);
  19200. __decorate([
  19201. BABYLON.serializeAsVector3()
  19202. ], TransformNode.prototype, "position", void 0);
  19203. return TransformNode;
  19204. }(BABYLON.Node));
  19205. BABYLON.TransformNode = TransformNode;
  19206. })(BABYLON || (BABYLON = {}));
  19207. //# sourceMappingURL=babylon.transformNode.js.map
  19208. var BABYLON;
  19209. (function (BABYLON) {
  19210. /**
  19211. * Class used to store all common mesh properties
  19212. */
  19213. var AbstractMesh = /** @class */ (function (_super) {
  19214. __extends(AbstractMesh, _super);
  19215. // Constructor
  19216. /**
  19217. * Creates a new AbstractMesh
  19218. * @param name defines the name of the mesh
  19219. * @param scene defines the hosting scene
  19220. */
  19221. function AbstractMesh(name, scene) {
  19222. if (scene === void 0) { scene = null; }
  19223. var _this = _super.call(this, name, scene, false) || this;
  19224. _this._facetNb = 0; // facet number
  19225. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19226. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19227. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19228. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19229. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19230. _this._subDiv = {
  19231. max: 1,
  19232. X: 1,
  19233. Y: 1,
  19234. Z: 1
  19235. };
  19236. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19237. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19238. // Events
  19239. /**
  19240. * An event triggered when this mesh collides with another one
  19241. */
  19242. _this.onCollideObservable = new BABYLON.Observable();
  19243. /**
  19244. * An event triggered when the collision's position changes
  19245. */
  19246. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19247. /**
  19248. * An event triggered when material is changed
  19249. */
  19250. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19251. // Properties
  19252. /**
  19253. * Gets or sets the orientation for POV movement & rotation
  19254. */
  19255. _this.definedFacingForward = true;
  19256. /**
  19257. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19258. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19259. * * 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.
  19260. * @see http://doc.babylonjs.com/features/occlusionquery
  19261. */
  19262. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19263. /**
  19264. * 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:
  19265. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19266. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19267. * * 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.
  19268. * @see http://doc.babylonjs.com/features/occlusionquery
  19269. */
  19270. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19271. /**
  19272. * 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.
  19273. * The default value is -1 which means don't break the query and wait till the result
  19274. * @see http://doc.babylonjs.com/features/occlusionquery
  19275. */
  19276. _this.occlusionRetryCount = -1;
  19277. _this._occlusionInternalRetryCounter = 0;
  19278. _this._isOccluded = false;
  19279. _this._isOcclusionQueryInProgress = false;
  19280. _this._visibility = 1.0;
  19281. /** Gets or sets the alpha index used to sort transparent meshes
  19282. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19283. */
  19284. _this.alphaIndex = Number.MAX_VALUE;
  19285. /**
  19286. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19287. */
  19288. _this.isVisible = true;
  19289. /**
  19290. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19291. */
  19292. _this.isPickable = true;
  19293. /**
  19294. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19295. */
  19296. _this.showBoundingBox = false;
  19297. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19298. _this.showSubMeshesBoundingBox = false;
  19299. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19300. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19301. */
  19302. _this.isBlocker = false;
  19303. /**
  19304. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19305. */
  19306. _this.enablePointerMoveEvents = false;
  19307. /**
  19308. * Specifies the rendering group id for this mesh (0 by default)
  19309. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19310. */
  19311. _this.renderingGroupId = 0;
  19312. _this._receiveShadows = false;
  19313. /**
  19314. * Gets or sets a boolean indicating if the outline must be rendered as well
  19315. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19316. */
  19317. _this.renderOutline = false;
  19318. /** Defines color to use when rendering outline */
  19319. _this.outlineColor = BABYLON.Color3.Red();
  19320. /** Define width to use when rendering outline */
  19321. _this.outlineWidth = 0.02;
  19322. /**
  19323. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19324. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19325. */
  19326. _this.renderOverlay = false;
  19327. /** Defines color to use when rendering overlay */
  19328. _this.overlayColor = BABYLON.Color3.Red();
  19329. /** Defines alpha to use when rendering overlay */
  19330. _this.overlayAlpha = 0.5;
  19331. _this._hasVertexAlpha = false;
  19332. _this._useVertexColors = true;
  19333. _this._computeBonesUsingShaders = true;
  19334. _this._numBoneInfluencers = 4;
  19335. _this._applyFog = true;
  19336. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19337. _this.useOctreeForRenderingSelection = true;
  19338. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19339. _this.useOctreeForPicking = true;
  19340. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19341. _this.useOctreeForCollisions = true;
  19342. _this._layerMask = 0x0FFFFFFF;
  19343. /**
  19344. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19345. */
  19346. _this.alwaysSelectAsActiveMesh = false;
  19347. /**
  19348. * Gets or sets the current action manager
  19349. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19350. */
  19351. _this.actionManager = null;
  19352. /**
  19353. * Gets or sets impostor used for physic simulation
  19354. * @see http://doc.babylonjs.com/features/physics_engine
  19355. */
  19356. _this.physicsImpostor = null;
  19357. // Collisions
  19358. _this._checkCollisions = false;
  19359. _this._collisionMask = -1;
  19360. _this._collisionGroup = -1;
  19361. /**
  19362. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19363. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19364. */
  19365. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19366. /**
  19367. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19368. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19369. */
  19370. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19371. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19372. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19373. // Edges
  19374. /**
  19375. * Defines edge width used when edgesRenderer is enabled
  19376. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19377. */
  19378. _this.edgesWidth = 1;
  19379. /**
  19380. * Defines edge color used when edgesRenderer is enabled
  19381. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19382. */
  19383. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19384. // Cache
  19385. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19386. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19387. /** @hidden */
  19388. _this._renderId = 0;
  19389. /** @hidden */
  19390. _this._intersectionsInProgress = new Array();
  19391. /** @hidden */
  19392. _this._unIndexed = false;
  19393. /** @hidden */
  19394. _this._lightSources = new Array();
  19395. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19396. if (collidedMesh === void 0) { collidedMesh = null; }
  19397. //TODO move this to the collision coordinator!
  19398. if (_this.getScene().workerCollisions)
  19399. newPosition.multiplyInPlace(_this._collider._radius);
  19400. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19401. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19402. _this.position.addInPlace(_this._diffPositionForCollisions);
  19403. }
  19404. if (collidedMesh) {
  19405. _this.onCollideObservable.notifyObservers(collidedMesh);
  19406. }
  19407. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19408. };
  19409. _this.getScene().addMesh(_this);
  19410. _this._resyncLightSources();
  19411. return _this;
  19412. }
  19413. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19414. /**
  19415. * No billboard
  19416. */
  19417. get: function () {
  19418. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19419. },
  19420. enumerable: true,
  19421. configurable: true
  19422. });
  19423. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19424. /** Billboard on X axis */
  19425. get: function () {
  19426. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19427. },
  19428. enumerable: true,
  19429. configurable: true
  19430. });
  19431. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19432. /** Billboard on Y axis */
  19433. get: function () {
  19434. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19435. },
  19436. enumerable: true,
  19437. configurable: true
  19438. });
  19439. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19440. /** Billboard on Z axis */
  19441. get: function () {
  19442. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19443. },
  19444. enumerable: true,
  19445. configurable: true
  19446. });
  19447. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19448. /** Billboard on all axes */
  19449. get: function () {
  19450. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19451. },
  19452. enumerable: true,
  19453. configurable: true
  19454. });
  19455. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19456. /**
  19457. * Gets the number of facets in the mesh
  19458. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19459. */
  19460. get: function () {
  19461. return this._facetNb;
  19462. },
  19463. enumerable: true,
  19464. configurable: true
  19465. });
  19466. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19467. /**
  19468. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19469. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19470. */
  19471. get: function () {
  19472. return this._partitioningSubdivisions;
  19473. },
  19474. set: function (nb) {
  19475. this._partitioningSubdivisions = nb;
  19476. },
  19477. enumerable: true,
  19478. configurable: true
  19479. });
  19480. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19481. /**
  19482. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19483. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19484. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19485. */
  19486. get: function () {
  19487. return this._partitioningBBoxRatio;
  19488. },
  19489. set: function (ratio) {
  19490. this._partitioningBBoxRatio = ratio;
  19491. },
  19492. enumerable: true,
  19493. configurable: true
  19494. });
  19495. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19496. /**
  19497. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19498. * Works only for updatable meshes.
  19499. * Doesn't work with multi-materials
  19500. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19501. */
  19502. get: function () {
  19503. return this._facetDepthSort;
  19504. },
  19505. set: function (sort) {
  19506. this._facetDepthSort = sort;
  19507. },
  19508. enumerable: true,
  19509. configurable: true
  19510. });
  19511. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19512. /**
  19513. * The location (Vector3) where the facet depth sort must be computed from.
  19514. * By default, the active camera position.
  19515. * Used only when facet depth sort is enabled
  19516. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19517. */
  19518. get: function () {
  19519. return this._facetDepthSortFrom;
  19520. },
  19521. set: function (location) {
  19522. this._facetDepthSortFrom = location;
  19523. },
  19524. enumerable: true,
  19525. configurable: true
  19526. });
  19527. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19528. /**
  19529. * gets a boolean indicating if facetData is enabled
  19530. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19531. */
  19532. get: function () {
  19533. return this._facetDataEnabled;
  19534. },
  19535. enumerable: true,
  19536. configurable: true
  19537. });
  19538. /** @hidden */
  19539. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19540. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19541. return false;
  19542. }
  19543. this._markSubMeshesAsMiscDirty();
  19544. return true;
  19545. };
  19546. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19547. /** Set a function to call when this mesh collides with another one */
  19548. set: function (callback) {
  19549. if (this._onCollideObserver) {
  19550. this.onCollideObservable.remove(this._onCollideObserver);
  19551. }
  19552. this._onCollideObserver = this.onCollideObservable.add(callback);
  19553. },
  19554. enumerable: true,
  19555. configurable: true
  19556. });
  19557. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19558. /** Set a function to call when the collision's position changes */
  19559. set: function (callback) {
  19560. if (this._onCollisionPositionChangeObserver) {
  19561. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19562. }
  19563. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19564. },
  19565. enumerable: true,
  19566. configurable: true
  19567. });
  19568. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19569. /**
  19570. * 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
  19571. * @see http://doc.babylonjs.com/features/occlusionquery
  19572. */
  19573. get: function () {
  19574. return this._isOccluded;
  19575. },
  19576. set: function (value) {
  19577. this._isOccluded = value;
  19578. },
  19579. enumerable: true,
  19580. configurable: true
  19581. });
  19582. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19583. /**
  19584. * Flag to check the progress status of the query
  19585. * @see http://doc.babylonjs.com/features/occlusionquery
  19586. */
  19587. get: function () {
  19588. return this._isOcclusionQueryInProgress;
  19589. },
  19590. enumerable: true,
  19591. configurable: true
  19592. });
  19593. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19594. /**
  19595. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19596. */
  19597. get: function () {
  19598. return this._visibility;
  19599. },
  19600. /**
  19601. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19602. */
  19603. set: function (value) {
  19604. if (this._visibility === value) {
  19605. return;
  19606. }
  19607. this._visibility = value;
  19608. this._markSubMeshesAsMiscDirty();
  19609. },
  19610. enumerable: true,
  19611. configurable: true
  19612. });
  19613. Object.defineProperty(AbstractMesh.prototype, "material", {
  19614. /** Gets or sets current material */
  19615. get: function () {
  19616. return this._material;
  19617. },
  19618. set: function (value) {
  19619. if (this._material === value) {
  19620. return;
  19621. }
  19622. this._material = value;
  19623. if (this.onMaterialChangedObservable.hasObservers) {
  19624. this.onMaterialChangedObservable.notifyObservers(this);
  19625. }
  19626. if (!this.subMeshes) {
  19627. return;
  19628. }
  19629. this._unBindEffect();
  19630. },
  19631. enumerable: true,
  19632. configurable: true
  19633. });
  19634. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19635. /**
  19636. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19637. * @see http://doc.babylonjs.com/babylon101/shadows
  19638. */
  19639. get: function () {
  19640. return this._receiveShadows;
  19641. },
  19642. set: function (value) {
  19643. if (this._receiveShadows === value) {
  19644. return;
  19645. }
  19646. this._receiveShadows = value;
  19647. this._markSubMeshesAsLightDirty();
  19648. },
  19649. enumerable: true,
  19650. configurable: true
  19651. });
  19652. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19653. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19654. get: function () {
  19655. return this._hasVertexAlpha;
  19656. },
  19657. set: function (value) {
  19658. if (this._hasVertexAlpha === value) {
  19659. return;
  19660. }
  19661. this._hasVertexAlpha = value;
  19662. this._markSubMeshesAsAttributesDirty();
  19663. this._markSubMeshesAsMiscDirty();
  19664. },
  19665. enumerable: true,
  19666. configurable: true
  19667. });
  19668. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19669. /** 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) */
  19670. get: function () {
  19671. return this._useVertexColors;
  19672. },
  19673. set: function (value) {
  19674. if (this._useVertexColors === value) {
  19675. return;
  19676. }
  19677. this._useVertexColors = value;
  19678. this._markSubMeshesAsAttributesDirty();
  19679. },
  19680. enumerable: true,
  19681. configurable: true
  19682. });
  19683. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19684. /**
  19685. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19686. */
  19687. get: function () {
  19688. return this._computeBonesUsingShaders;
  19689. },
  19690. set: function (value) {
  19691. if (this._computeBonesUsingShaders === value) {
  19692. return;
  19693. }
  19694. this._computeBonesUsingShaders = value;
  19695. this._markSubMeshesAsAttributesDirty();
  19696. },
  19697. enumerable: true,
  19698. configurable: true
  19699. });
  19700. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19701. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19702. get: function () {
  19703. return this._numBoneInfluencers;
  19704. },
  19705. set: function (value) {
  19706. if (this._numBoneInfluencers === value) {
  19707. return;
  19708. }
  19709. this._numBoneInfluencers = value;
  19710. this._markSubMeshesAsAttributesDirty();
  19711. },
  19712. enumerable: true,
  19713. configurable: true
  19714. });
  19715. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19716. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19717. get: function () {
  19718. return this._applyFog;
  19719. },
  19720. set: function (value) {
  19721. if (this._applyFog === value) {
  19722. return;
  19723. }
  19724. this._applyFog = value;
  19725. this._markSubMeshesAsMiscDirty();
  19726. },
  19727. enumerable: true,
  19728. configurable: true
  19729. });
  19730. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19731. /**
  19732. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19733. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19734. */
  19735. get: function () {
  19736. return this._layerMask;
  19737. },
  19738. set: function (value) {
  19739. if (value === this._layerMask) {
  19740. return;
  19741. }
  19742. this._layerMask = value;
  19743. this._resyncLightSources();
  19744. },
  19745. enumerable: true,
  19746. configurable: true
  19747. });
  19748. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19749. /**
  19750. * Gets or sets a collision mask used to mask collisions (default is -1).
  19751. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19752. */
  19753. get: function () {
  19754. return this._collisionMask;
  19755. },
  19756. set: function (mask) {
  19757. this._collisionMask = !isNaN(mask) ? mask : -1;
  19758. },
  19759. enumerable: true,
  19760. configurable: true
  19761. });
  19762. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19763. /**
  19764. * Gets or sets the current collision group mask (-1 by default).
  19765. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19766. */
  19767. get: function () {
  19768. return this._collisionGroup;
  19769. },
  19770. set: function (mask) {
  19771. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19772. },
  19773. enumerable: true,
  19774. configurable: true
  19775. });
  19776. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19777. /** @hidden */
  19778. get: function () {
  19779. return null;
  19780. },
  19781. enumerable: true,
  19782. configurable: true
  19783. });
  19784. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19785. get: function () {
  19786. return this._skeleton;
  19787. },
  19788. /**
  19789. * Gets or sets a skeleton to apply skining transformations
  19790. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19791. */
  19792. set: function (value) {
  19793. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19794. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19795. }
  19796. if (value && value.needInitialSkinMatrix) {
  19797. value._registerMeshWithPoseMatrix(this);
  19798. }
  19799. this._skeleton = value;
  19800. if (!this._skeleton) {
  19801. this._bonesTransformMatrices = null;
  19802. }
  19803. this._markSubMeshesAsAttributesDirty();
  19804. },
  19805. enumerable: true,
  19806. configurable: true
  19807. });
  19808. /**
  19809. * Returns the string "AbstractMesh"
  19810. * @returns "AbstractMesh"
  19811. */
  19812. AbstractMesh.prototype.getClassName = function () {
  19813. return "AbstractMesh";
  19814. };
  19815. /**
  19816. * Gets a string representation of the current mesh
  19817. * @param fullDetails defines a boolean indicating if full details must be included
  19818. * @returns a string representation of the current mesh
  19819. */
  19820. AbstractMesh.prototype.toString = function (fullDetails) {
  19821. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19822. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19823. if (this._skeleton) {
  19824. ret += ", skeleton: " + this._skeleton.name;
  19825. }
  19826. if (fullDetails) {
  19827. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19828. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19829. }
  19830. return ret;
  19831. };
  19832. /** @hidden */
  19833. AbstractMesh.prototype._rebuild = function () {
  19834. if (this._occlusionQuery) {
  19835. this._occlusionQuery = null;
  19836. }
  19837. if (this._edgesRenderer) {
  19838. this._edgesRenderer._rebuild();
  19839. }
  19840. if (!this.subMeshes) {
  19841. return;
  19842. }
  19843. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19844. var subMesh = _a[_i];
  19845. subMesh._rebuild();
  19846. }
  19847. };
  19848. /** @hidden */
  19849. AbstractMesh.prototype._resyncLightSources = function () {
  19850. this._lightSources.length = 0;
  19851. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19852. var light = _a[_i];
  19853. if (!light.isEnabled()) {
  19854. continue;
  19855. }
  19856. if (light.canAffectMesh(this)) {
  19857. this._lightSources.push(light);
  19858. }
  19859. }
  19860. this._markSubMeshesAsLightDirty();
  19861. };
  19862. /** @hidden */
  19863. AbstractMesh.prototype._resyncLighSource = function (light) {
  19864. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19865. var index = this._lightSources.indexOf(light);
  19866. if (index === -1) {
  19867. if (!isIn) {
  19868. return;
  19869. }
  19870. this._lightSources.push(light);
  19871. }
  19872. else {
  19873. if (isIn) {
  19874. return;
  19875. }
  19876. this._lightSources.splice(index, 1);
  19877. }
  19878. this._markSubMeshesAsLightDirty();
  19879. };
  19880. /** @hidden */
  19881. AbstractMesh.prototype._unBindEffect = function () {
  19882. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19883. var subMesh = _a[_i];
  19884. subMesh.setEffect(null);
  19885. }
  19886. };
  19887. /** @hidden */
  19888. AbstractMesh.prototype._removeLightSource = function (light) {
  19889. var index = this._lightSources.indexOf(light);
  19890. if (index === -1) {
  19891. return;
  19892. }
  19893. this._lightSources.splice(index, 1);
  19894. this._markSubMeshesAsLightDirty();
  19895. };
  19896. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19897. if (!this.subMeshes) {
  19898. return;
  19899. }
  19900. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19901. var subMesh = _a[_i];
  19902. if (subMesh._materialDefines) {
  19903. func(subMesh._materialDefines);
  19904. }
  19905. }
  19906. };
  19907. /** @hidden */
  19908. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19909. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19910. };
  19911. /** @hidden */
  19912. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19913. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19914. };
  19915. /** @hidden */
  19916. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19917. if (!this.subMeshes) {
  19918. return;
  19919. }
  19920. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19921. var subMesh = _a[_i];
  19922. var material = subMesh.getMaterial();
  19923. if (material) {
  19924. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19925. }
  19926. }
  19927. };
  19928. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19929. /**
  19930. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19931. */
  19932. get: function () {
  19933. return this._scaling;
  19934. },
  19935. set: function (newScaling) {
  19936. this._scaling = newScaling;
  19937. if (this.physicsImpostor) {
  19938. this.physicsImpostor.forceUpdate();
  19939. }
  19940. },
  19941. enumerable: true,
  19942. configurable: true
  19943. });
  19944. // Methods
  19945. /**
  19946. * Disables the mesh edge rendering mode
  19947. * @returns the currentAbstractMesh
  19948. */
  19949. AbstractMesh.prototype.disableEdgesRendering = function () {
  19950. if (this._edgesRenderer) {
  19951. this._edgesRenderer.dispose();
  19952. this._edgesRenderer = null;
  19953. }
  19954. return this;
  19955. };
  19956. /**
  19957. * Enables the edge rendering mode on the mesh.
  19958. * This mode makes the mesh edges visible
  19959. * @param epsilon defines the maximal distance between two angles to detect a face
  19960. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  19961. * @returns the currentAbstractMesh
  19962. * @see https://www.babylonjs-playground.com/#19O9TU#0
  19963. */
  19964. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19965. if (epsilon === void 0) { epsilon = 0.95; }
  19966. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19967. this.disableEdgesRendering();
  19968. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19969. return this;
  19970. };
  19971. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19972. /**
  19973. * Returns true if the mesh is blocked. Implemented by child classes
  19974. */
  19975. get: function () {
  19976. return false;
  19977. },
  19978. enumerable: true,
  19979. configurable: true
  19980. });
  19981. /**
  19982. * Returns the mesh itself by default. Implemented by child classes
  19983. * @param camera defines the camera to use to pick the right LOD level
  19984. * @returns the currentAbstractMesh
  19985. */
  19986. AbstractMesh.prototype.getLOD = function (camera) {
  19987. return this;
  19988. };
  19989. /**
  19990. * Returns 0 by default. Implemented by child classes
  19991. * @returns an integer
  19992. */
  19993. AbstractMesh.prototype.getTotalVertices = function () {
  19994. return 0;
  19995. };
  19996. /**
  19997. * Returns null by default. Implemented by child classes
  19998. * @returns null
  19999. */
  20000. AbstractMesh.prototype.getIndices = function () {
  20001. return null;
  20002. };
  20003. /**
  20004. * Returns the array of the requested vertex data kind. Implemented by child classes
  20005. * @param kind defines the vertex data kind to use
  20006. * @returns null
  20007. */
  20008. AbstractMesh.prototype.getVerticesData = function (kind) {
  20009. return null;
  20010. };
  20011. /**
  20012. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20013. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20014. * Note that a new underlying VertexBuffer object is created each call.
  20015. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20016. * @param kind defines vertex data kind:
  20017. * * BABYLON.VertexBuffer.PositionKind
  20018. * * BABYLON.VertexBuffer.UVKind
  20019. * * BABYLON.VertexBuffer.UV2Kind
  20020. * * BABYLON.VertexBuffer.UV3Kind
  20021. * * BABYLON.VertexBuffer.UV4Kind
  20022. * * BABYLON.VertexBuffer.UV5Kind
  20023. * * BABYLON.VertexBuffer.UV6Kind
  20024. * * BABYLON.VertexBuffer.ColorKind
  20025. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20026. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20027. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20028. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20029. * @param data defines the data source
  20030. * @param updatable defines if the data must be flagged as updatable (or static)
  20031. * @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
  20032. * @returns the current mesh
  20033. */
  20034. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20035. return this;
  20036. };
  20037. /**
  20038. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20039. * If the mesh has no geometry, it is simply returned as it is.
  20040. * @param kind defines vertex data kind:
  20041. * * BABYLON.VertexBuffer.PositionKind
  20042. * * BABYLON.VertexBuffer.UVKind
  20043. * * BABYLON.VertexBuffer.UV2Kind
  20044. * * BABYLON.VertexBuffer.UV3Kind
  20045. * * BABYLON.VertexBuffer.UV4Kind
  20046. * * BABYLON.VertexBuffer.UV5Kind
  20047. * * BABYLON.VertexBuffer.UV6Kind
  20048. * * BABYLON.VertexBuffer.ColorKind
  20049. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20050. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20051. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20052. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20053. * @param data defines the data source
  20054. * @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
  20055. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20056. * @returns the current mesh
  20057. */
  20058. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20059. return this;
  20060. };
  20061. /**
  20062. * Sets the mesh indices,
  20063. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20064. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20065. * @param totalVertices Defines the total number of vertices
  20066. * @returns the current mesh
  20067. */
  20068. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20069. return this;
  20070. };
  20071. /**
  20072. * Gets a boolean indicating if specific vertex data is present
  20073. * @param kind defines the vertex data kind to use
  20074. * @returns true is data kind is present
  20075. */
  20076. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20077. return false;
  20078. };
  20079. /**
  20080. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20081. * @returns a BoundingInfo
  20082. */
  20083. AbstractMesh.prototype.getBoundingInfo = function () {
  20084. if (this._masterMesh) {
  20085. return this._masterMesh.getBoundingInfo();
  20086. }
  20087. if (!this._boundingInfo) {
  20088. // this._boundingInfo is being created here
  20089. this._updateBoundingInfo();
  20090. }
  20091. // cannot be null.
  20092. return this._boundingInfo;
  20093. };
  20094. /**
  20095. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20096. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20097. * @returns the current mesh
  20098. */
  20099. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20100. if (includeDescendants === void 0) { includeDescendants = true; }
  20101. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20102. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20103. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20104. if (maxDimension === 0) {
  20105. return this;
  20106. }
  20107. var scale = 1 / maxDimension;
  20108. this.scaling.scaleInPlace(scale);
  20109. return this;
  20110. };
  20111. /**
  20112. * Overwrite the current bounding info
  20113. * @param boundingInfo defines the new bounding info
  20114. * @returns the current mesh
  20115. */
  20116. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20117. this._boundingInfo = boundingInfo;
  20118. return this;
  20119. };
  20120. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20121. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20122. get: function () {
  20123. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20124. },
  20125. enumerable: true,
  20126. configurable: true
  20127. });
  20128. /** @hidden */
  20129. AbstractMesh.prototype._preActivate = function () {
  20130. };
  20131. /** @hidden */
  20132. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20133. };
  20134. /** @hidden */
  20135. AbstractMesh.prototype._activate = function (renderId) {
  20136. this._renderId = renderId;
  20137. };
  20138. /**
  20139. * Gets the current world matrix
  20140. * @returns a Matrix
  20141. */
  20142. AbstractMesh.prototype.getWorldMatrix = function () {
  20143. if (this._masterMesh) {
  20144. return this._masterMesh.getWorldMatrix();
  20145. }
  20146. return _super.prototype.getWorldMatrix.call(this);
  20147. };
  20148. /** @hidden */
  20149. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20150. if (this._masterMesh) {
  20151. return this._masterMesh._getWorldMatrixDeterminant();
  20152. }
  20153. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20154. };
  20155. // ================================== Point of View Movement =================================
  20156. /**
  20157. * Perform relative position change from the point of view of behind the front of the mesh.
  20158. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20159. * Supports definition of mesh facing forward or backward
  20160. * @param amountRight defines the distance on the right axis
  20161. * @param amountUp defines the distance on the up axis
  20162. * @param amountForward defines the distance on the forward axis
  20163. * @returns the current mesh
  20164. */
  20165. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20166. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20167. return this;
  20168. };
  20169. /**
  20170. * Calculate relative position change from the point of view of behind the front of the mesh.
  20171. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20172. * Supports definition of mesh facing forward or backward
  20173. * @param amountRight defines the distance on the right axis
  20174. * @param amountUp defines the distance on the up axis
  20175. * @param amountForward defines the distance on the forward axis
  20176. * @returns the new displacement vector
  20177. */
  20178. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20179. var rotMatrix = new BABYLON.Matrix();
  20180. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20181. rotQuaternion.toRotationMatrix(rotMatrix);
  20182. var translationDelta = BABYLON.Vector3.Zero();
  20183. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20184. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20185. return translationDelta;
  20186. };
  20187. // ================================== Point of View Rotation =================================
  20188. /**
  20189. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20190. * Supports definition of mesh facing forward or backward
  20191. * @param flipBack defines the flip
  20192. * @param twirlClockwise defines the twirl
  20193. * @param tiltRight defines the tilt
  20194. * @returns the current mesh
  20195. */
  20196. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20197. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20198. return this;
  20199. };
  20200. /**
  20201. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20202. * Supports definition of mesh facing forward or backward.
  20203. * @param flipBack defines the flip
  20204. * @param twirlClockwise defines the twirl
  20205. * @param tiltRight defines the tilt
  20206. * @returns the new rotation vector
  20207. */
  20208. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20209. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20210. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20211. };
  20212. /**
  20213. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20214. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20215. * @returns the new bounding vectors
  20216. */
  20217. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  20218. if (includeDescendants === void 0) { includeDescendants = true; }
  20219. // Ensures that all world matrix will be recomputed.
  20220. this.getScene().incrementRenderId();
  20221. this.computeWorldMatrix(true);
  20222. var min;
  20223. var max;
  20224. var boundingInfo = this.getBoundingInfo();
  20225. if (!this.subMeshes) {
  20226. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20227. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20228. }
  20229. else {
  20230. min = boundingInfo.boundingBox.minimumWorld;
  20231. max = boundingInfo.boundingBox.maximumWorld;
  20232. }
  20233. if (includeDescendants) {
  20234. var descendants = this.getDescendants(false);
  20235. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20236. var descendant = descendants_1[_i];
  20237. var childMesh = descendant;
  20238. childMesh.computeWorldMatrix(true);
  20239. //make sure we have the needed params to get mix and max
  20240. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20241. continue;
  20242. }
  20243. var childBoundingInfo = childMesh.getBoundingInfo();
  20244. var boundingBox = childBoundingInfo.boundingBox;
  20245. var minBox = boundingBox.minimumWorld;
  20246. var maxBox = boundingBox.maximumWorld;
  20247. BABYLON.Tools.CheckExtends(minBox, min, max);
  20248. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20249. }
  20250. }
  20251. return {
  20252. min: min,
  20253. max: max
  20254. };
  20255. };
  20256. /** @hidden */
  20257. AbstractMesh.prototype._updateBoundingInfo = function () {
  20258. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20259. this._boundingInfo.update(this.worldMatrixFromCache);
  20260. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20261. return this;
  20262. };
  20263. /** @hidden */
  20264. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20265. if (!this.subMeshes) {
  20266. return this;
  20267. }
  20268. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20269. var subMesh = this.subMeshes[subIndex];
  20270. if (!subMesh.IsGlobal) {
  20271. subMesh.updateBoundingInfo(matrix);
  20272. }
  20273. }
  20274. return this;
  20275. };
  20276. /** @hidden */
  20277. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20278. // Bounding info
  20279. this._updateBoundingInfo();
  20280. };
  20281. /**
  20282. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20283. * A mesh is in the frustum if its bounding box intersects the frustum
  20284. * @param frustumPlanes defines the frustum to test
  20285. * @returns true if the mesh is in the frustum planes
  20286. */
  20287. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20288. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20289. };
  20290. /**
  20291. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20292. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20293. * @param frustumPlanes defines the frustum to test
  20294. * @returns true if the mesh is completely in the frustum planes
  20295. */
  20296. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20297. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20298. ;
  20299. };
  20300. /**
  20301. * True if the mesh intersects another mesh or a SolidParticle object
  20302. * @param mesh defines a target mesh or SolidParticle to test
  20303. * @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)
  20304. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20305. * @returns true if there is an intersection
  20306. */
  20307. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20308. if (precise === void 0) { precise = false; }
  20309. if (!this._boundingInfo || !mesh._boundingInfo) {
  20310. return false;
  20311. }
  20312. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20313. return true;
  20314. }
  20315. if (includeDescendants) {
  20316. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20317. var child = _a[_i];
  20318. if (child.intersectsMesh(mesh, precise, true)) {
  20319. return true;
  20320. }
  20321. }
  20322. }
  20323. return false;
  20324. };
  20325. /**
  20326. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20327. * @param point defines the point to test
  20328. * @returns true if there is an intersection
  20329. */
  20330. AbstractMesh.prototype.intersectsPoint = function (point) {
  20331. if (!this._boundingInfo) {
  20332. return false;
  20333. }
  20334. return this._boundingInfo.intersectsPoint(point);
  20335. };
  20336. /**
  20337. * Gets the current physics impostor
  20338. * @see http://doc.babylonjs.com/features/physics_engine
  20339. * @returns a physics impostor or null
  20340. */
  20341. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20342. return this.physicsImpostor;
  20343. };
  20344. /**
  20345. * Gets the position of the current mesh in camera space
  20346. * @param camera defines the camera to use
  20347. * @returns a position
  20348. */
  20349. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20350. if (camera === void 0) { camera = null; }
  20351. if (!camera) {
  20352. camera = this.getScene().activeCamera;
  20353. }
  20354. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20355. };
  20356. /**
  20357. * Returns the distance from the mesh to the active camera
  20358. * @param camera defines the camera to use
  20359. * @returns the distance
  20360. */
  20361. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20362. if (camera === void 0) { camera = null; }
  20363. if (!camera) {
  20364. camera = this.getScene().activeCamera;
  20365. }
  20366. return this.absolutePosition.subtract(camera.position).length();
  20367. };
  20368. /**
  20369. * Apply a physic impulse to the mesh
  20370. * @param force defines the force to apply
  20371. * @param contactPoint defines where to apply the force
  20372. * @returns the current mesh
  20373. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20374. */
  20375. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20376. if (!this.physicsImpostor) {
  20377. return this;
  20378. }
  20379. this.physicsImpostor.applyImpulse(force, contactPoint);
  20380. return this;
  20381. };
  20382. /**
  20383. * Creates a physic joint between two meshes
  20384. * @param otherMesh defines the other mesh to use
  20385. * @param pivot1 defines the pivot to use on this mesh
  20386. * @param pivot2 defines the pivot to use on the other mesh
  20387. * @param options defines additional options (can be plugin dependent)
  20388. * @returns the current mesh
  20389. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20390. */
  20391. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20392. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20393. return this;
  20394. }
  20395. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20396. mainPivot: pivot1,
  20397. connectedPivot: pivot2,
  20398. nativeParams: options
  20399. });
  20400. return this;
  20401. };
  20402. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20403. // Collisions
  20404. /**
  20405. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20406. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20407. */
  20408. get: function () {
  20409. return this._checkCollisions;
  20410. },
  20411. set: function (collisionEnabled) {
  20412. this._checkCollisions = collisionEnabled;
  20413. if (this.getScene().workerCollisions) {
  20414. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20415. }
  20416. },
  20417. enumerable: true,
  20418. configurable: true
  20419. });
  20420. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20421. /**
  20422. * Gets Collider object used to compute collisions (not physics)
  20423. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20424. */
  20425. get: function () {
  20426. return this._collider;
  20427. },
  20428. enumerable: true,
  20429. configurable: true
  20430. });
  20431. /**
  20432. * Move the mesh using collision engine
  20433. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20434. * @param displacement defines the requested displacement vector
  20435. * @returns the current mesh
  20436. */
  20437. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20438. var globalPosition = this.getAbsolutePosition();
  20439. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20440. if (!this._collider) {
  20441. this._collider = new BABYLON.Collider();
  20442. }
  20443. this._collider._radius = this.ellipsoid;
  20444. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20445. return this;
  20446. };
  20447. // Submeshes octree
  20448. /**
  20449. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20450. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20451. * @param maxCapacity defines the maximum size of each block (64 by default)
  20452. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20453. * @returns the new octree
  20454. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20455. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20456. */
  20457. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20458. if (maxCapacity === void 0) { maxCapacity = 64; }
  20459. if (maxDepth === void 0) { maxDepth = 2; }
  20460. if (!this._submeshesOctree) {
  20461. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20462. }
  20463. this.computeWorldMatrix(true);
  20464. var boundingInfo = this.getBoundingInfo();
  20465. // Update octree
  20466. var bbox = boundingInfo.boundingBox;
  20467. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20468. return this._submeshesOctree;
  20469. };
  20470. // Collisions
  20471. /** @hidden */
  20472. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20473. this._generatePointsArray();
  20474. if (!this._positions) {
  20475. return this;
  20476. }
  20477. // Transformation
  20478. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20479. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20480. subMesh._lastColliderWorldVertices = [];
  20481. subMesh._trianglePlanes = [];
  20482. var start = subMesh.verticesStart;
  20483. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20484. for (var i = start; i < end; i++) {
  20485. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20486. }
  20487. }
  20488. // Collide
  20489. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20490. if (collider.collisionFound) {
  20491. collider.collidedMesh = this;
  20492. }
  20493. return this;
  20494. };
  20495. /** @hidden */
  20496. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20497. var subMeshes;
  20498. var len;
  20499. // Octrees
  20500. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20501. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20502. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20503. len = intersections.length;
  20504. subMeshes = intersections.data;
  20505. }
  20506. else {
  20507. subMeshes = this.subMeshes;
  20508. len = subMeshes.length;
  20509. }
  20510. for (var index = 0; index < len; index++) {
  20511. var subMesh = subMeshes[index];
  20512. // Bounding test
  20513. if (len > 1 && !subMesh._checkCollision(collider))
  20514. continue;
  20515. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20516. }
  20517. return this;
  20518. };
  20519. /** @hidden */
  20520. AbstractMesh.prototype._checkCollision = function (collider) {
  20521. // Bounding box test
  20522. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20523. return this;
  20524. // Transformation matrix
  20525. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20526. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20527. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20528. return this;
  20529. };
  20530. // Picking
  20531. /** @hidden */
  20532. AbstractMesh.prototype._generatePointsArray = function () {
  20533. return false;
  20534. };
  20535. /**
  20536. * Checks if the passed Ray intersects with the mesh
  20537. * @param ray defines the ray to use
  20538. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20539. * @returns the picking info
  20540. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20541. */
  20542. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20543. var pickingInfo = new BABYLON.PickingInfo();
  20544. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20545. return pickingInfo;
  20546. }
  20547. if (!this._generatePointsArray()) {
  20548. return pickingInfo;
  20549. }
  20550. var intersectInfo = null;
  20551. // Octrees
  20552. var subMeshes;
  20553. var len;
  20554. if (this._submeshesOctree && this.useOctreeForPicking) {
  20555. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20556. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20557. len = intersections.length;
  20558. subMeshes = intersections.data;
  20559. }
  20560. else {
  20561. subMeshes = this.subMeshes;
  20562. len = subMeshes.length;
  20563. }
  20564. for (var index = 0; index < len; index++) {
  20565. var subMesh = subMeshes[index];
  20566. // Bounding test
  20567. if (len > 1 && !subMesh.canIntersects(ray))
  20568. continue;
  20569. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20570. if (currentIntersectInfo) {
  20571. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20572. intersectInfo = currentIntersectInfo;
  20573. intersectInfo.subMeshId = index;
  20574. if (fastCheck) {
  20575. break;
  20576. }
  20577. }
  20578. }
  20579. }
  20580. if (intersectInfo) {
  20581. // Get picked point
  20582. var world = this.getWorldMatrix();
  20583. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20584. var direction = ray.direction.clone();
  20585. direction = direction.scale(intersectInfo.distance);
  20586. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20587. var pickedPoint = worldOrigin.add(worldDirection);
  20588. // Return result
  20589. pickingInfo.hit = true;
  20590. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20591. pickingInfo.pickedPoint = pickedPoint;
  20592. pickingInfo.pickedMesh = this;
  20593. pickingInfo.bu = intersectInfo.bu || 0;
  20594. pickingInfo.bv = intersectInfo.bv || 0;
  20595. pickingInfo.faceId = intersectInfo.faceId;
  20596. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20597. return pickingInfo;
  20598. }
  20599. return pickingInfo;
  20600. };
  20601. /**
  20602. * Clones the current mesh
  20603. * @param name defines the mesh name
  20604. * @param newParent defines the new mesh parent
  20605. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20606. * @returns the new mesh
  20607. */
  20608. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20609. return null;
  20610. };
  20611. /**
  20612. * Disposes all the submeshes of the current meshnp
  20613. * @returns the current mesh
  20614. */
  20615. AbstractMesh.prototype.releaseSubMeshes = function () {
  20616. if (this.subMeshes) {
  20617. while (this.subMeshes.length) {
  20618. this.subMeshes[0].dispose();
  20619. }
  20620. }
  20621. else {
  20622. this.subMeshes = new Array();
  20623. }
  20624. return this;
  20625. };
  20626. /**
  20627. * Releases resources associated with this abstract mesh.
  20628. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20629. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20630. */
  20631. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20632. var _this = this;
  20633. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20634. var index;
  20635. // Smart Array Retainers.
  20636. this.getScene().freeActiveMeshes();
  20637. this.getScene().freeRenderingGroups();
  20638. // Action manager
  20639. if (this.actionManager !== undefined && this.actionManager !== null) {
  20640. this.actionManager.dispose();
  20641. this.actionManager = null;
  20642. }
  20643. // Skeleton
  20644. this._skeleton = null;
  20645. // Physics
  20646. if (this.physicsImpostor) {
  20647. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20648. }
  20649. // Intersections in progress
  20650. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20651. var other = this._intersectionsInProgress[index];
  20652. var pos = other._intersectionsInProgress.indexOf(this);
  20653. other._intersectionsInProgress.splice(pos, 1);
  20654. }
  20655. this._intersectionsInProgress = [];
  20656. // Lights
  20657. var lights = this.getScene().lights;
  20658. lights.forEach(function (light) {
  20659. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20660. if (meshIndex !== -1) {
  20661. light.includedOnlyMeshes.splice(meshIndex, 1);
  20662. }
  20663. meshIndex = light.excludedMeshes.indexOf(_this);
  20664. if (meshIndex !== -1) {
  20665. light.excludedMeshes.splice(meshIndex, 1);
  20666. }
  20667. // Shadow generators
  20668. var generator = light.getShadowGenerator();
  20669. if (generator) {
  20670. var shadowMap = generator.getShadowMap();
  20671. if (shadowMap && shadowMap.renderList) {
  20672. meshIndex = shadowMap.renderList.indexOf(_this);
  20673. if (meshIndex !== -1) {
  20674. shadowMap.renderList.splice(meshIndex, 1);
  20675. }
  20676. }
  20677. }
  20678. });
  20679. // Edges
  20680. if (this._edgesRenderer) {
  20681. this._edgesRenderer.dispose();
  20682. this._edgesRenderer = null;
  20683. }
  20684. // SubMeshes
  20685. if (this.getClassName() !== "InstancedMesh") {
  20686. this.releaseSubMeshes();
  20687. }
  20688. // Octree
  20689. var sceneOctree = this.getScene().selectionOctree;
  20690. if (sceneOctree !== undefined && sceneOctree !== null) {
  20691. var index = sceneOctree.dynamicContent.indexOf(this);
  20692. if (index !== -1) {
  20693. sceneOctree.dynamicContent.splice(index, 1);
  20694. }
  20695. }
  20696. // Query
  20697. var engine = this.getScene().getEngine();
  20698. if (this._occlusionQuery) {
  20699. this._isOcclusionQueryInProgress = false;
  20700. engine.deleteQuery(this._occlusionQuery);
  20701. this._occlusionQuery = null;
  20702. }
  20703. // Engine
  20704. engine.wipeCaches();
  20705. // Remove from scene
  20706. this.getScene().removeMesh(this);
  20707. if (disposeMaterialAndTextures) {
  20708. if (this.material) {
  20709. this.material.dispose(false, true);
  20710. }
  20711. }
  20712. if (!doNotRecurse) {
  20713. // Particles
  20714. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20715. if (this.getScene().particleSystems[index].emitter === this) {
  20716. this.getScene().particleSystems[index].dispose();
  20717. index--;
  20718. }
  20719. }
  20720. }
  20721. // facet data
  20722. if (this._facetDataEnabled) {
  20723. this.disableFacetData();
  20724. }
  20725. this.onAfterWorldMatrixUpdateObservable.clear();
  20726. this.onCollideObservable.clear();
  20727. this.onCollisionPositionChangeObservable.clear();
  20728. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20729. };
  20730. /**
  20731. * Adds the passed mesh as a child to the current mesh
  20732. * @param mesh defines the child mesh
  20733. * @returns the current mesh
  20734. */
  20735. AbstractMesh.prototype.addChild = function (mesh) {
  20736. mesh.setParent(this);
  20737. return this;
  20738. };
  20739. /**
  20740. * Removes the passed mesh from the current mesh children list
  20741. * @param mesh defines the child mesh
  20742. * @returns the current mesh
  20743. */
  20744. AbstractMesh.prototype.removeChild = function (mesh) {
  20745. mesh.setParent(null);
  20746. return this;
  20747. };
  20748. // Facet data
  20749. /** @hidden */
  20750. AbstractMesh.prototype._initFacetData = function () {
  20751. if (!this._facetNormals) {
  20752. this._facetNormals = new Array();
  20753. }
  20754. if (!this._facetPositions) {
  20755. this._facetPositions = new Array();
  20756. }
  20757. if (!this._facetPartitioning) {
  20758. this._facetPartitioning = new Array();
  20759. }
  20760. this._facetNb = (this.getIndices().length / 3) | 0;
  20761. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20762. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20763. for (var f = 0; f < this._facetNb; f++) {
  20764. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20765. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20766. }
  20767. this._facetDataEnabled = true;
  20768. return this;
  20769. };
  20770. /**
  20771. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20772. * This method can be called within the render loop.
  20773. * 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
  20774. * @returns the current mesh
  20775. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20776. */
  20777. AbstractMesh.prototype.updateFacetData = function () {
  20778. if (!this._facetDataEnabled) {
  20779. this._initFacetData();
  20780. }
  20781. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20782. var indices = this.getIndices();
  20783. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20784. var bInfo = this.getBoundingInfo();
  20785. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20786. // init arrays, matrix and sort function on first call
  20787. this._facetDepthSortEnabled = true;
  20788. if (indices instanceof Uint16Array) {
  20789. this._depthSortedIndices = new Uint16Array(indices);
  20790. }
  20791. else if (indices instanceof Uint32Array) {
  20792. this._depthSortedIndices = new Uint32Array(indices);
  20793. }
  20794. else {
  20795. var needs32bits = false;
  20796. for (var i = 0; i < indices.length; i++) {
  20797. if (indices[i] > 65535) {
  20798. needs32bits = true;
  20799. break;
  20800. }
  20801. }
  20802. if (needs32bits) {
  20803. this._depthSortedIndices = new Uint32Array(indices);
  20804. }
  20805. else {
  20806. this._depthSortedIndices = new Uint16Array(indices);
  20807. }
  20808. }
  20809. this._facetDepthSortFunction = function (f1, f2) {
  20810. return (f2.sqDistance - f1.sqDistance);
  20811. };
  20812. if (!this._facetDepthSortFrom) {
  20813. var camera = this.getScene().activeCamera;
  20814. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20815. }
  20816. this._depthSortedFacets = [];
  20817. for (var f = 0; f < this._facetNb; f++) {
  20818. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20819. this._depthSortedFacets.push(depthSortedFacet);
  20820. }
  20821. this._invertedMatrix = BABYLON.Matrix.Identity();
  20822. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20823. }
  20824. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20825. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20826. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20827. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20828. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20829. this._subDiv.max = this._partitioningSubdivisions;
  20830. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20831. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20832. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20833. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20834. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20835. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20836. // set the parameters for ComputeNormals()
  20837. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20838. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20839. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20840. this._facetParameters.bInfo = bInfo;
  20841. this._facetParameters.bbSize = this._bbSize;
  20842. this._facetParameters.subDiv = this._subDiv;
  20843. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20844. this._facetParameters.depthSort = this._facetDepthSort;
  20845. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20846. this.computeWorldMatrix(true);
  20847. this._worldMatrix.invertToRef(this._invertedMatrix);
  20848. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20849. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20850. }
  20851. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20852. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20853. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20854. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20855. var l = (this._depthSortedIndices.length / 3) | 0;
  20856. for (var f = 0; f < l; f++) {
  20857. var sind = this._depthSortedFacets[f].ind;
  20858. this._depthSortedIndices[f * 3] = indices[sind];
  20859. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20860. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20861. }
  20862. this.updateIndices(this._depthSortedIndices);
  20863. }
  20864. return this;
  20865. };
  20866. /**
  20867. * Returns the facetLocalNormals array.
  20868. * The normals are expressed in the mesh local spac
  20869. * @returns an array of Vector3
  20870. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20871. */
  20872. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20873. if (!this._facetNormals) {
  20874. this.updateFacetData();
  20875. }
  20876. return this._facetNormals;
  20877. };
  20878. /**
  20879. * Returns the facetLocalPositions array.
  20880. * The facet positions are expressed in the mesh local space
  20881. * @returns an array of Vector3
  20882. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20883. */
  20884. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20885. if (!this._facetPositions) {
  20886. this.updateFacetData();
  20887. }
  20888. return this._facetPositions;
  20889. };
  20890. /**
  20891. * Returns the facetLocalPartioning array
  20892. * @returns an array of array of numbers
  20893. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20894. */
  20895. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20896. if (!this._facetPartitioning) {
  20897. this.updateFacetData();
  20898. }
  20899. return this._facetPartitioning;
  20900. };
  20901. /**
  20902. * Returns the i-th facet position in the world system.
  20903. * This method allocates a new Vector3 per call
  20904. * @param i defines the facet index
  20905. * @returns a new Vector3
  20906. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20907. */
  20908. AbstractMesh.prototype.getFacetPosition = function (i) {
  20909. var pos = BABYLON.Vector3.Zero();
  20910. this.getFacetPositionToRef(i, pos);
  20911. return pos;
  20912. };
  20913. /**
  20914. * Sets the reference Vector3 with the i-th facet position in the world system
  20915. * @param i defines the facet index
  20916. * @param ref defines the target vector
  20917. * @returns the current mesh
  20918. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20919. */
  20920. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20921. var localPos = (this.getFacetLocalPositions())[i];
  20922. var world = this.getWorldMatrix();
  20923. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20924. return this;
  20925. };
  20926. /**
  20927. * Returns the i-th facet normal in the world system.
  20928. * This method allocates a new Vector3 per call
  20929. * @param i defines the facet index
  20930. * @returns a new Vector3
  20931. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20932. */
  20933. AbstractMesh.prototype.getFacetNormal = function (i) {
  20934. var norm = BABYLON.Vector3.Zero();
  20935. this.getFacetNormalToRef(i, norm);
  20936. return norm;
  20937. };
  20938. /**
  20939. * Sets the reference Vector3 with the i-th facet normal in the world system
  20940. * @param i defines the facet index
  20941. * @param ref defines the target vector
  20942. * @returns the current mesh
  20943. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20944. */
  20945. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20946. var localNorm = (this.getFacetLocalNormals())[i];
  20947. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20948. return this;
  20949. };
  20950. /**
  20951. * 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)
  20952. * @param x defines x coordinate
  20953. * @param y defines y coordinate
  20954. * @param z defines z coordinate
  20955. * @returns the array of facet indexes
  20956. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20957. */
  20958. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20959. var bInfo = this.getBoundingInfo();
  20960. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20961. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20962. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20963. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20964. return null;
  20965. }
  20966. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20967. };
  20968. /**
  20969. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  20970. * @param projected sets as the (x,y,z) world projection on the facet
  20971. * @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
  20972. * @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
  20973. * @param x defines x coordinate
  20974. * @param y defines y coordinate
  20975. * @param z defines z coordinate
  20976. * @returns the face index if found (or null instead)
  20977. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20978. */
  20979. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  20980. if (checkFace === void 0) { checkFace = false; }
  20981. if (facing === void 0) { facing = true; }
  20982. var world = this.getWorldMatrix();
  20983. var invMat = BABYLON.Tmp.Matrix[5];
  20984. world.invertToRef(invMat);
  20985. var invVect = BABYLON.Tmp.Vector3[8];
  20986. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  20987. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  20988. if (projected) {
  20989. // tranform the local computed projected vector to world coordinates
  20990. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  20991. }
  20992. return closest;
  20993. };
  20994. /**
  20995. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  20996. * @param projected sets as the (x,y,z) local projection on the facet
  20997. * @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
  20998. * @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
  20999. * @param x defines x coordinate
  21000. * @param y defines y coordinate
  21001. * @param z defines z coordinate
  21002. * @returns the face index if found (or null instead)
  21003. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21004. */
  21005. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21006. if (checkFace === void 0) { checkFace = false; }
  21007. if (facing === void 0) { facing = true; }
  21008. var closest = null;
  21009. var tmpx = 0.0;
  21010. var tmpy = 0.0;
  21011. var tmpz = 0.0;
  21012. var d = 0.0; // tmp dot facet normal * facet position
  21013. var t0 = 0.0;
  21014. var projx = 0.0;
  21015. var projy = 0.0;
  21016. var projz = 0.0;
  21017. // Get all the facets in the same partitioning block than (x, y, z)
  21018. var facetPositions = this.getFacetLocalPositions();
  21019. var facetNormals = this.getFacetLocalNormals();
  21020. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21021. if (!facetsInBlock) {
  21022. return null;
  21023. }
  21024. // Get the closest facet to (x, y, z)
  21025. var shortest = Number.MAX_VALUE; // init distance vars
  21026. var tmpDistance = shortest;
  21027. var fib; // current facet in the block
  21028. var norm; // current facet normal
  21029. var p0; // current facet barycenter position
  21030. // loop on all the facets in the current partitioning block
  21031. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21032. fib = facetsInBlock[idx];
  21033. norm = facetNormals[fib];
  21034. p0 = facetPositions[fib];
  21035. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21036. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21037. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21038. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21039. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21040. projx = x + norm.x * t0;
  21041. projy = y + norm.y * t0;
  21042. projz = z + norm.z * t0;
  21043. tmpx = projx - x;
  21044. tmpy = projy - y;
  21045. tmpz = projz - z;
  21046. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21047. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21048. shortest = tmpDistance;
  21049. closest = fib;
  21050. if (projected) {
  21051. projected.x = projx;
  21052. projected.y = projy;
  21053. projected.z = projz;
  21054. }
  21055. }
  21056. }
  21057. }
  21058. return closest;
  21059. };
  21060. /**
  21061. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21062. * @returns the parameters
  21063. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21064. */
  21065. AbstractMesh.prototype.getFacetDataParameters = function () {
  21066. return this._facetParameters;
  21067. };
  21068. /**
  21069. * Disables the feature FacetData and frees the related memory
  21070. * @returns the current mesh
  21071. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21072. */
  21073. AbstractMesh.prototype.disableFacetData = function () {
  21074. if (this._facetDataEnabled) {
  21075. this._facetDataEnabled = false;
  21076. this._facetPositions = new Array();
  21077. this._facetNormals = new Array();
  21078. this._facetPartitioning = new Array();
  21079. this._facetParameters = null;
  21080. this._depthSortedIndices = new Uint32Array(0);
  21081. }
  21082. return this;
  21083. };
  21084. /**
  21085. * Updates the AbstractMesh indices array
  21086. * @param indices defines the data source
  21087. * @returns the current mesh
  21088. */
  21089. AbstractMesh.prototype.updateIndices = function (indices) {
  21090. return this;
  21091. };
  21092. /**
  21093. * Creates new normals data for the mesh
  21094. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21095. * @returns the current mesh
  21096. */
  21097. AbstractMesh.prototype.createNormals = function (updatable) {
  21098. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21099. var indices = this.getIndices();
  21100. var normals;
  21101. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21102. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21103. }
  21104. else {
  21105. normals = [];
  21106. }
  21107. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21108. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21109. return this;
  21110. };
  21111. /**
  21112. * Align the mesh with a normal
  21113. * @param normal defines the normal to use
  21114. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21115. * @returns the current mesh
  21116. */
  21117. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21118. if (!upDirection) {
  21119. upDirection = BABYLON.Axis.Y;
  21120. }
  21121. var axisX = BABYLON.Tmp.Vector3[0];
  21122. var axisZ = BABYLON.Tmp.Vector3[1];
  21123. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21124. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21125. if (this.rotationQuaternion) {
  21126. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21127. }
  21128. else {
  21129. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21130. }
  21131. return this;
  21132. };
  21133. /** @hidden */
  21134. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21135. var engine = this.getEngine();
  21136. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21137. this._isOccluded = false;
  21138. return;
  21139. }
  21140. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21141. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21142. if (isOcclusionQueryAvailable) {
  21143. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21144. this._isOcclusionQueryInProgress = false;
  21145. this._occlusionInternalRetryCounter = 0;
  21146. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21147. }
  21148. else {
  21149. this._occlusionInternalRetryCounter++;
  21150. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21151. this._isOcclusionQueryInProgress = false;
  21152. this._occlusionInternalRetryCounter = 0;
  21153. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21154. // if strict continue the last state of the object.
  21155. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21156. }
  21157. else {
  21158. return;
  21159. }
  21160. }
  21161. }
  21162. var scene = this.getScene();
  21163. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21164. if (!this._occlusionQuery) {
  21165. this._occlusionQuery = engine.createQuery();
  21166. }
  21167. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21168. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21169. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21170. this._isOcclusionQueryInProgress = true;
  21171. };
  21172. /** No occlusion */
  21173. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21174. /** Occlusion set to optimisitic */
  21175. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21176. /** Occlusion set to strict */
  21177. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21178. /** Use an accurante occlusion algorithm */
  21179. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21180. /** Use a conservative occlusion algorithm */
  21181. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21182. return AbstractMesh;
  21183. }(BABYLON.TransformNode));
  21184. BABYLON.AbstractMesh = AbstractMesh;
  21185. })(BABYLON || (BABYLON = {}));
  21186. //# sourceMappingURL=babylon.abstractMesh.js.map
  21187. var BABYLON;
  21188. (function (BABYLON) {
  21189. /**
  21190. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21191. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21192. * 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.
  21193. */
  21194. var Light = /** @class */ (function (_super) {
  21195. __extends(Light, _super);
  21196. /**
  21197. * Creates a Light object in the scene.
  21198. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21199. * @param name The firendly name of the light
  21200. * @param scene The scene the light belongs too
  21201. */
  21202. function Light(name, scene) {
  21203. var _this = _super.call(this, name, scene) || this;
  21204. /**
  21205. * Diffuse gives the basic color to an object.
  21206. */
  21207. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21208. /**
  21209. * Specular produces a highlight color on an object.
  21210. * Note: This is note affecting PBR materials.
  21211. */
  21212. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21213. /**
  21214. * Strength of the light.
  21215. * Note: By default it is define in the framework own unit.
  21216. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21217. */
  21218. _this.intensity = 1.0;
  21219. /**
  21220. * Defines how far from the source the light is impacting in scene units.
  21221. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21222. */
  21223. _this.range = Number.MAX_VALUE;
  21224. /**
  21225. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21226. * of light.
  21227. */
  21228. _this._photometricScale = 1.0;
  21229. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21230. _this._radius = 0.00001;
  21231. /**
  21232. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21233. * exceeding the number allowed of the materials.
  21234. */
  21235. _this.renderPriority = 0;
  21236. /**
  21237. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21238. * the current shadow generator.
  21239. */
  21240. _this.shadowEnabled = true;
  21241. _this._excludeWithLayerMask = 0;
  21242. _this._includeOnlyWithLayerMask = 0;
  21243. _this._lightmapMode = 0;
  21244. /**
  21245. * @hidden Internal use only.
  21246. */
  21247. _this._excludedMeshesIds = new Array();
  21248. /**
  21249. * @hidden Internal use only.
  21250. */
  21251. _this._includedOnlyMeshesIds = new Array();
  21252. _this.getScene().addLight(_this);
  21253. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21254. _this._buildUniformLayout();
  21255. _this.includedOnlyMeshes = new Array();
  21256. _this.excludedMeshes = new Array();
  21257. _this._resyncMeshes();
  21258. return _this;
  21259. }
  21260. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21261. /**
  21262. * If every light affecting the material is in this lightmapMode,
  21263. * material.lightmapTexture adds or multiplies
  21264. * (depends on material.useLightmapAsShadowmap)
  21265. * after every other light calculations.
  21266. */
  21267. get: function () {
  21268. return Light._LIGHTMAP_DEFAULT;
  21269. },
  21270. enumerable: true,
  21271. configurable: true
  21272. });
  21273. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21274. /**
  21275. * material.lightmapTexture as only diffuse lighting from this light
  21276. * adds only specular lighting from this light
  21277. * adds dynamic shadows
  21278. */
  21279. get: function () {
  21280. return Light._LIGHTMAP_SPECULAR;
  21281. },
  21282. enumerable: true,
  21283. configurable: true
  21284. });
  21285. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21286. /**
  21287. * material.lightmapTexture as only lighting
  21288. * no light calculation from this light
  21289. * only adds dynamic shadows from this light
  21290. */
  21291. get: function () {
  21292. return Light._LIGHTMAP_SHADOWSONLY;
  21293. },
  21294. enumerable: true,
  21295. configurable: true
  21296. });
  21297. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21298. /**
  21299. * Each light type uses the default quantity according to its type:
  21300. * point/spot lights use luminous intensity
  21301. * directional lights use illuminance
  21302. */
  21303. get: function () {
  21304. return Light._INTENSITYMODE_AUTOMATIC;
  21305. },
  21306. enumerable: true,
  21307. configurable: true
  21308. });
  21309. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21310. /**
  21311. * lumen (lm)
  21312. */
  21313. get: function () {
  21314. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21315. },
  21316. enumerable: true,
  21317. configurable: true
  21318. });
  21319. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21320. /**
  21321. * candela (lm/sr)
  21322. */
  21323. get: function () {
  21324. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21325. },
  21326. enumerable: true,
  21327. configurable: true
  21328. });
  21329. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21330. /**
  21331. * lux (lm/m^2)
  21332. */
  21333. get: function () {
  21334. return Light._INTENSITYMODE_ILLUMINANCE;
  21335. },
  21336. enumerable: true,
  21337. configurable: true
  21338. });
  21339. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21340. /**
  21341. * nit (cd/m^2)
  21342. */
  21343. get: function () {
  21344. return Light._INTENSITYMODE_LUMINANCE;
  21345. },
  21346. enumerable: true,
  21347. configurable: true
  21348. });
  21349. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21350. /**
  21351. * Light type const id of the point light.
  21352. */
  21353. get: function () {
  21354. return Light._LIGHTTYPEID_POINTLIGHT;
  21355. },
  21356. enumerable: true,
  21357. configurable: true
  21358. });
  21359. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21360. /**
  21361. * Light type const id of the directional light.
  21362. */
  21363. get: function () {
  21364. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21365. },
  21366. enumerable: true,
  21367. configurable: true
  21368. });
  21369. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21370. /**
  21371. * Light type const id of the spot light.
  21372. */
  21373. get: function () {
  21374. return Light._LIGHTTYPEID_SPOTLIGHT;
  21375. },
  21376. enumerable: true,
  21377. configurable: true
  21378. });
  21379. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21380. /**
  21381. * Light type const id of the hemispheric light.
  21382. */
  21383. get: function () {
  21384. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21385. },
  21386. enumerable: true,
  21387. configurable: true
  21388. });
  21389. Object.defineProperty(Light.prototype, "intensityMode", {
  21390. /**
  21391. * Gets the photometric scale used to interpret the intensity.
  21392. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21393. */
  21394. get: function () {
  21395. return this._intensityMode;
  21396. },
  21397. /**
  21398. * Sets the photometric scale used to interpret the intensity.
  21399. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21400. */
  21401. set: function (value) {
  21402. this._intensityMode = value;
  21403. this._computePhotometricScale();
  21404. },
  21405. enumerable: true,
  21406. configurable: true
  21407. });
  21408. ;
  21409. ;
  21410. Object.defineProperty(Light.prototype, "radius", {
  21411. /**
  21412. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21413. */
  21414. get: function () {
  21415. return this._radius;
  21416. },
  21417. /**
  21418. * sets the light radius used by PBR Materials to simulate soft area lights.
  21419. */
  21420. set: function (value) {
  21421. this._radius = value;
  21422. this._computePhotometricScale();
  21423. },
  21424. enumerable: true,
  21425. configurable: true
  21426. });
  21427. ;
  21428. ;
  21429. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21430. /**
  21431. * Gets the only meshes impacted by this light.
  21432. */
  21433. get: function () {
  21434. return this._includedOnlyMeshes;
  21435. },
  21436. /**
  21437. * Sets the only meshes impacted by this light.
  21438. */
  21439. set: function (value) {
  21440. this._includedOnlyMeshes = value;
  21441. this._hookArrayForIncludedOnly(value);
  21442. },
  21443. enumerable: true,
  21444. configurable: true
  21445. });
  21446. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21447. /**
  21448. * Gets the meshes not impacted by this light.
  21449. */
  21450. get: function () {
  21451. return this._excludedMeshes;
  21452. },
  21453. /**
  21454. * Sets the meshes not impacted by this light.
  21455. */
  21456. set: function (value) {
  21457. this._excludedMeshes = value;
  21458. this._hookArrayForExcluded(value);
  21459. },
  21460. enumerable: true,
  21461. configurable: true
  21462. });
  21463. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21464. /**
  21465. * Gets the layer id use to find what meshes are not impacted by the light.
  21466. * Inactive if 0
  21467. */
  21468. get: function () {
  21469. return this._excludeWithLayerMask;
  21470. },
  21471. /**
  21472. * Sets the layer id use to find what meshes are not impacted by the light.
  21473. * Inactive if 0
  21474. */
  21475. set: function (value) {
  21476. this._excludeWithLayerMask = value;
  21477. this._resyncMeshes();
  21478. },
  21479. enumerable: true,
  21480. configurable: true
  21481. });
  21482. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21483. /**
  21484. * Gets the layer id use to find what meshes are impacted by the light.
  21485. * Inactive if 0
  21486. */
  21487. get: function () {
  21488. return this._includeOnlyWithLayerMask;
  21489. },
  21490. /**
  21491. * Sets the layer id use to find what meshes are impacted by the light.
  21492. * Inactive if 0
  21493. */
  21494. set: function (value) {
  21495. this._includeOnlyWithLayerMask = value;
  21496. this._resyncMeshes();
  21497. },
  21498. enumerable: true,
  21499. configurable: true
  21500. });
  21501. Object.defineProperty(Light.prototype, "lightmapMode", {
  21502. /**
  21503. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21504. */
  21505. get: function () {
  21506. return this._lightmapMode;
  21507. },
  21508. /**
  21509. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21510. */
  21511. set: function (value) {
  21512. if (this._lightmapMode === value) {
  21513. return;
  21514. }
  21515. this._lightmapMode = value;
  21516. this._markMeshesAsLightDirty();
  21517. },
  21518. enumerable: true,
  21519. configurable: true
  21520. });
  21521. /**
  21522. * Returns the string "Light".
  21523. * @returns the class name
  21524. */
  21525. Light.prototype.getClassName = function () {
  21526. return "Light";
  21527. };
  21528. /**
  21529. * Converts the light information to a readable string for debug purpose.
  21530. * @param fullDetails Supports for multiple levels of logging within scene loading
  21531. * @returns the human readable light info
  21532. */
  21533. Light.prototype.toString = function (fullDetails) {
  21534. var ret = "Name: " + this.name;
  21535. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21536. if (this.animations) {
  21537. for (var i = 0; i < this.animations.length; i++) {
  21538. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21539. }
  21540. }
  21541. if (fullDetails) {
  21542. }
  21543. return ret;
  21544. };
  21545. /**
  21546. * Set the enabled state of this node.
  21547. * @param value - the new enabled state
  21548. */
  21549. Light.prototype.setEnabled = function (value) {
  21550. _super.prototype.setEnabled.call(this, value);
  21551. this._resyncMeshes();
  21552. };
  21553. /**
  21554. * Returns the Light associated shadow generator if any.
  21555. * @return the associated shadow generator.
  21556. */
  21557. Light.prototype.getShadowGenerator = function () {
  21558. return this._shadowGenerator;
  21559. };
  21560. /**
  21561. * Returns a Vector3, the absolute light position in the World.
  21562. * @returns the world space position of the light
  21563. */
  21564. Light.prototype.getAbsolutePosition = function () {
  21565. return BABYLON.Vector3.Zero();
  21566. };
  21567. /**
  21568. * Specifies if the light will affect the passed mesh.
  21569. * @param mesh The mesh to test against the light
  21570. * @return true the mesh is affected otherwise, false.
  21571. */
  21572. Light.prototype.canAffectMesh = function (mesh) {
  21573. if (!mesh) {
  21574. return true;
  21575. }
  21576. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21577. return false;
  21578. }
  21579. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21580. return false;
  21581. }
  21582. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21583. return false;
  21584. }
  21585. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21586. return false;
  21587. }
  21588. return true;
  21589. };
  21590. /**
  21591. * Computes and Returns the light World matrix.
  21592. * @returns the world matrix
  21593. */
  21594. Light.prototype.getWorldMatrix = function () {
  21595. this._currentRenderId = this.getScene().getRenderId();
  21596. this._childRenderId = this._currentRenderId;
  21597. var worldMatrix = this._getWorldMatrix();
  21598. if (this.parent && this.parent.getWorldMatrix) {
  21599. if (!this._parentedWorldMatrix) {
  21600. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21601. }
  21602. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21603. this._markSyncedWithParent();
  21604. return this._parentedWorldMatrix;
  21605. }
  21606. return worldMatrix;
  21607. };
  21608. /**
  21609. * Sort function to order lights for rendering.
  21610. * @param a First Light object to compare to second.
  21611. * @param b Second Light object to compare first.
  21612. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21613. */
  21614. Light.CompareLightsPriority = function (a, b) {
  21615. //shadow-casting lights have priority over non-shadow-casting lights
  21616. //the renderPrioirty is a secondary sort criterion
  21617. if (a.shadowEnabled !== b.shadowEnabled) {
  21618. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21619. }
  21620. return b.renderPriority - a.renderPriority;
  21621. };
  21622. /**
  21623. * Releases resources associated with this node.
  21624. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21625. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21626. */
  21627. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21628. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21629. if (this._shadowGenerator) {
  21630. this._shadowGenerator.dispose();
  21631. this._shadowGenerator = null;
  21632. }
  21633. // Animations
  21634. this.getScene().stopAnimation(this);
  21635. // Remove from meshes
  21636. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21637. var mesh = _a[_i];
  21638. mesh._removeLightSource(this);
  21639. }
  21640. this._uniformBuffer.dispose();
  21641. // Remove from scene
  21642. this.getScene().removeLight(this);
  21643. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21644. };
  21645. /**
  21646. * Returns the light type ID (integer).
  21647. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21648. */
  21649. Light.prototype.getTypeID = function () {
  21650. return 0;
  21651. };
  21652. /**
  21653. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21654. * @returns the scaled intensity in intensity mode unit
  21655. */
  21656. Light.prototype.getScaledIntensity = function () {
  21657. return this._photometricScale * this.intensity;
  21658. };
  21659. /**
  21660. * Returns a new Light object, named "name", from the current one.
  21661. * @param name The name of the cloned light
  21662. * @returns the new created light
  21663. */
  21664. Light.prototype.clone = function (name) {
  21665. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21666. if (!constructor) {
  21667. return null;
  21668. }
  21669. return BABYLON.SerializationHelper.Clone(constructor, this);
  21670. };
  21671. /**
  21672. * Serializes the current light into a Serialization object.
  21673. * @returns the serialized object.
  21674. */
  21675. Light.prototype.serialize = function () {
  21676. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21677. // Type
  21678. serializationObject.type = this.getTypeID();
  21679. // Parent
  21680. if (this.parent) {
  21681. serializationObject.parentId = this.parent.id;
  21682. }
  21683. // Inclusion / exclusions
  21684. if (this.excludedMeshes.length > 0) {
  21685. serializationObject.excludedMeshesIds = [];
  21686. this.excludedMeshes.forEach(function (mesh) {
  21687. serializationObject.excludedMeshesIds.push(mesh.id);
  21688. });
  21689. }
  21690. if (this.includedOnlyMeshes.length > 0) {
  21691. serializationObject.includedOnlyMeshesIds = [];
  21692. this.includedOnlyMeshes.forEach(function (mesh) {
  21693. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21694. });
  21695. }
  21696. // Animations
  21697. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21698. serializationObject.ranges = this.serializeAnimationRanges();
  21699. return serializationObject;
  21700. };
  21701. /**
  21702. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21703. * This new light is named "name" and added to the passed scene.
  21704. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21705. * @param name The friendly name of the light
  21706. * @param scene The scene the new light will belong to
  21707. * @returns the constructor function
  21708. */
  21709. Light.GetConstructorFromName = function (type, name, scene) {
  21710. switch (type) {
  21711. case 0:
  21712. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21713. case 1:
  21714. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21715. case 2:
  21716. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21717. case 3:
  21718. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21719. }
  21720. return null;
  21721. };
  21722. /**
  21723. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21724. * @param parsedLight The JSON representation of the light
  21725. * @param scene The scene to create the parsed light in
  21726. * @returns the created light after parsing
  21727. */
  21728. Light.Parse = function (parsedLight, scene) {
  21729. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21730. if (!constructor) {
  21731. return null;
  21732. }
  21733. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21734. // Inclusion / exclusions
  21735. if (parsedLight.excludedMeshesIds) {
  21736. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21737. }
  21738. if (parsedLight.includedOnlyMeshesIds) {
  21739. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21740. }
  21741. // Parent
  21742. if (parsedLight.parentId) {
  21743. light._waitingParentId = parsedLight.parentId;
  21744. }
  21745. // Animations
  21746. if (parsedLight.animations) {
  21747. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21748. var parsedAnimation = parsedLight.animations[animationIndex];
  21749. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21750. }
  21751. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21752. }
  21753. if (parsedLight.autoAnimate) {
  21754. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21755. }
  21756. return light;
  21757. };
  21758. Light.prototype._hookArrayForExcluded = function (array) {
  21759. var _this = this;
  21760. var oldPush = array.push;
  21761. array.push = function () {
  21762. var items = [];
  21763. for (var _i = 0; _i < arguments.length; _i++) {
  21764. items[_i] = arguments[_i];
  21765. }
  21766. var result = oldPush.apply(array, items);
  21767. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21768. var item = items_1[_a];
  21769. item._resyncLighSource(_this);
  21770. }
  21771. return result;
  21772. };
  21773. var oldSplice = array.splice;
  21774. array.splice = function (index, deleteCount) {
  21775. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21776. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21777. var item = deleted_1[_i];
  21778. item._resyncLighSource(_this);
  21779. }
  21780. return deleted;
  21781. };
  21782. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21783. var item = array_1[_i];
  21784. item._resyncLighSource(this);
  21785. }
  21786. };
  21787. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21788. var _this = this;
  21789. var oldPush = array.push;
  21790. array.push = function () {
  21791. var items = [];
  21792. for (var _i = 0; _i < arguments.length; _i++) {
  21793. items[_i] = arguments[_i];
  21794. }
  21795. var result = oldPush.apply(array, items);
  21796. _this._resyncMeshes();
  21797. return result;
  21798. };
  21799. var oldSplice = array.splice;
  21800. array.splice = function (index, deleteCount) {
  21801. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21802. _this._resyncMeshes();
  21803. return deleted;
  21804. };
  21805. this._resyncMeshes();
  21806. };
  21807. Light.prototype._resyncMeshes = function () {
  21808. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21809. var mesh = _a[_i];
  21810. mesh._resyncLighSource(this);
  21811. }
  21812. };
  21813. /**
  21814. * Forces the meshes to update their light related information in their rendering used effects
  21815. * @hidden Internal Use Only
  21816. */
  21817. Light.prototype._markMeshesAsLightDirty = function () {
  21818. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21819. var mesh = _a[_i];
  21820. if (mesh._lightSources.indexOf(this) !== -1) {
  21821. mesh._markSubMeshesAsLightDirty();
  21822. }
  21823. }
  21824. };
  21825. /**
  21826. * Recomputes the cached photometric scale if needed.
  21827. */
  21828. Light.prototype._computePhotometricScale = function () {
  21829. this._photometricScale = this._getPhotometricScale();
  21830. this.getScene().resetCachedMaterial();
  21831. };
  21832. /**
  21833. * Returns the Photometric Scale according to the light type and intensity mode.
  21834. */
  21835. Light.prototype._getPhotometricScale = function () {
  21836. var photometricScale = 0.0;
  21837. var lightTypeID = this.getTypeID();
  21838. //get photometric mode
  21839. var photometricMode = this.intensityMode;
  21840. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21841. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21842. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21843. }
  21844. else {
  21845. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21846. }
  21847. }
  21848. //compute photometric scale
  21849. switch (lightTypeID) {
  21850. case Light.LIGHTTYPEID_POINTLIGHT:
  21851. case Light.LIGHTTYPEID_SPOTLIGHT:
  21852. switch (photometricMode) {
  21853. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21854. photometricScale = 1.0 / (4.0 * Math.PI);
  21855. break;
  21856. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21857. photometricScale = 1.0;
  21858. break;
  21859. case Light.INTENSITYMODE_LUMINANCE:
  21860. photometricScale = this.radius * this.radius;
  21861. break;
  21862. }
  21863. break;
  21864. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21865. switch (photometricMode) {
  21866. case Light.INTENSITYMODE_ILLUMINANCE:
  21867. photometricScale = 1.0;
  21868. break;
  21869. case Light.INTENSITYMODE_LUMINANCE:
  21870. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21871. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21872. var apexAngleRadians = this.radius;
  21873. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21874. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21875. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21876. photometricScale = solidAngle;
  21877. break;
  21878. }
  21879. break;
  21880. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21881. // No fall off in hemisperic light.
  21882. photometricScale = 1.0;
  21883. break;
  21884. }
  21885. return photometricScale;
  21886. };
  21887. /**
  21888. * Reorder the light in the scene according to their defined priority.
  21889. * @hidden Internal Use Only
  21890. */
  21891. Light.prototype._reorderLightsInScene = function () {
  21892. var scene = this.getScene();
  21893. if (this._renderPriority != 0) {
  21894. scene.requireLightSorting = true;
  21895. }
  21896. this.getScene().sortLightsByPriority();
  21897. };
  21898. //lightmapMode Consts
  21899. Light._LIGHTMAP_DEFAULT = 0;
  21900. Light._LIGHTMAP_SPECULAR = 1;
  21901. Light._LIGHTMAP_SHADOWSONLY = 2;
  21902. // Intensity Mode Consts
  21903. Light._INTENSITYMODE_AUTOMATIC = 0;
  21904. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21905. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21906. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21907. Light._INTENSITYMODE_LUMINANCE = 4;
  21908. // Light types ids const.
  21909. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21910. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21911. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21912. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21913. __decorate([
  21914. BABYLON.serializeAsColor3()
  21915. ], Light.prototype, "diffuse", void 0);
  21916. __decorate([
  21917. BABYLON.serializeAsColor3()
  21918. ], Light.prototype, "specular", void 0);
  21919. __decorate([
  21920. BABYLON.serialize()
  21921. ], Light.prototype, "intensity", void 0);
  21922. __decorate([
  21923. BABYLON.serialize()
  21924. ], Light.prototype, "range", void 0);
  21925. __decorate([
  21926. BABYLON.serialize()
  21927. ], Light.prototype, "intensityMode", null);
  21928. __decorate([
  21929. BABYLON.serialize()
  21930. ], Light.prototype, "radius", null);
  21931. __decorate([
  21932. BABYLON.serialize()
  21933. ], Light.prototype, "_renderPriority", void 0);
  21934. __decorate([
  21935. BABYLON.expandToProperty("_reorderLightsInScene")
  21936. ], Light.prototype, "renderPriority", void 0);
  21937. __decorate([
  21938. BABYLON.serialize()
  21939. ], Light.prototype, "shadowEnabled", void 0);
  21940. __decorate([
  21941. BABYLON.serialize("excludeWithLayerMask")
  21942. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21943. __decorate([
  21944. BABYLON.serialize("includeOnlyWithLayerMask")
  21945. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21946. __decorate([
  21947. BABYLON.serialize("lightmapMode")
  21948. ], Light.prototype, "_lightmapMode", void 0);
  21949. return Light;
  21950. }(BABYLON.Node));
  21951. BABYLON.Light = Light;
  21952. })(BABYLON || (BABYLON = {}));
  21953. //# sourceMappingURL=babylon.light.js.map
  21954. var BABYLON;
  21955. (function (BABYLON) {
  21956. var Camera = /** @class */ (function (_super) {
  21957. __extends(Camera, _super);
  21958. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  21959. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  21960. var _this = _super.call(this, name, scene) || this;
  21961. /**
  21962. * The vector the camera should consider as up.
  21963. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21964. */
  21965. _this.upVector = BABYLON.Vector3.Up();
  21966. _this.orthoLeft = null;
  21967. _this.orthoRight = null;
  21968. _this.orthoBottom = null;
  21969. _this.orthoTop = null;
  21970. /**
  21971. * FOV is set in Radians. (default is 0.8)
  21972. */
  21973. _this.fov = 0.8;
  21974. _this.minZ = 1;
  21975. _this.maxZ = 10000.0;
  21976. _this.inertia = 0.9;
  21977. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21978. _this.isIntermediate = false;
  21979. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  21980. /**
  21981. * Restricts the camera to viewing objects with the same layerMask.
  21982. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  21983. */
  21984. _this.layerMask = 0x0FFFFFFF;
  21985. /**
  21986. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  21987. */
  21988. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  21989. // Camera rig members
  21990. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  21991. _this._rigCameras = new Array();
  21992. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  21993. _this._skipRendering = false;
  21994. _this.customRenderTargets = new Array();
  21995. // Observables
  21996. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  21997. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  21998. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  21999. _this.onRestoreStateObservable = new BABYLON.Observable();
  22000. // Cache
  22001. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22002. _this._projectionMatrix = new BABYLON.Matrix();
  22003. _this._doNotComputeProjectionMatrix = false;
  22004. _this._worldMatrix = BABYLON.Matrix.Identity();
  22005. _this._postProcesses = new Array();
  22006. _this._transformMatrix = BABYLON.Matrix.Zero();
  22007. _this._activeMeshes = new BABYLON.SmartArray(256);
  22008. _this._globalPosition = BABYLON.Vector3.Zero();
  22009. _this._refreshFrustumPlanes = true;
  22010. _this.getScene().addCamera(_this);
  22011. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22012. _this.getScene().activeCamera = _this;
  22013. }
  22014. _this.position = position;
  22015. return _this;
  22016. }
  22017. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22018. get: function () {
  22019. return Camera._PERSPECTIVE_CAMERA;
  22020. },
  22021. enumerable: true,
  22022. configurable: true
  22023. });
  22024. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22025. get: function () {
  22026. return Camera._ORTHOGRAPHIC_CAMERA;
  22027. },
  22028. enumerable: true,
  22029. configurable: true
  22030. });
  22031. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22032. /**
  22033. * This is the default FOV mode for perspective cameras.
  22034. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22035. *
  22036. */
  22037. get: function () {
  22038. return Camera._FOVMODE_VERTICAL_FIXED;
  22039. },
  22040. enumerable: true,
  22041. configurable: true
  22042. });
  22043. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22044. /**
  22045. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22046. *
  22047. */
  22048. get: function () {
  22049. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22050. },
  22051. enumerable: true,
  22052. configurable: true
  22053. });
  22054. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22055. get: function () {
  22056. return Camera._RIG_MODE_NONE;
  22057. },
  22058. enumerable: true,
  22059. configurable: true
  22060. });
  22061. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22062. get: function () {
  22063. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22064. },
  22065. enumerable: true,
  22066. configurable: true
  22067. });
  22068. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22069. get: function () {
  22070. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22071. },
  22072. enumerable: true,
  22073. configurable: true
  22074. });
  22075. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22076. get: function () {
  22077. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22078. },
  22079. enumerable: true,
  22080. configurable: true
  22081. });
  22082. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22083. get: function () {
  22084. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22085. },
  22086. enumerable: true,
  22087. configurable: true
  22088. });
  22089. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22090. get: function () {
  22091. return Camera._RIG_MODE_VR;
  22092. },
  22093. enumerable: true,
  22094. configurable: true
  22095. });
  22096. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22097. get: function () {
  22098. return Camera._RIG_MODE_WEBVR;
  22099. },
  22100. enumerable: true,
  22101. configurable: true
  22102. });
  22103. /**
  22104. * Store current camera state (fov, position, etc..)
  22105. */
  22106. Camera.prototype.storeState = function () {
  22107. this._stateStored = true;
  22108. this._storedFov = this.fov;
  22109. return this;
  22110. };
  22111. /**
  22112. * Restores the camera state values if it has been stored. You must call storeState() first
  22113. */
  22114. Camera.prototype._restoreStateValues = function () {
  22115. if (!this._stateStored) {
  22116. return false;
  22117. }
  22118. this.fov = this._storedFov;
  22119. return true;
  22120. };
  22121. /**
  22122. * Restored camera state. You must call storeState() first
  22123. */
  22124. Camera.prototype.restoreState = function () {
  22125. if (this._restoreStateValues()) {
  22126. this.onRestoreStateObservable.notifyObservers(this);
  22127. return true;
  22128. }
  22129. return false;
  22130. };
  22131. Camera.prototype.getClassName = function () {
  22132. return "Camera";
  22133. };
  22134. /**
  22135. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22136. */
  22137. Camera.prototype.toString = function (fullDetails) {
  22138. var ret = "Name: " + this.name;
  22139. ret += ", type: " + this.getClassName();
  22140. if (this.animations) {
  22141. for (var i = 0; i < this.animations.length; i++) {
  22142. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22143. }
  22144. }
  22145. if (fullDetails) {
  22146. }
  22147. return ret;
  22148. };
  22149. Object.defineProperty(Camera.prototype, "globalPosition", {
  22150. get: function () {
  22151. return this._globalPosition;
  22152. },
  22153. enumerable: true,
  22154. configurable: true
  22155. });
  22156. Camera.prototype.getActiveMeshes = function () {
  22157. return this._activeMeshes;
  22158. };
  22159. Camera.prototype.isActiveMesh = function (mesh) {
  22160. return (this._activeMeshes.indexOf(mesh) !== -1);
  22161. };
  22162. /**
  22163. * Is this camera ready to be used/rendered
  22164. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22165. * @return true if the camera is ready
  22166. */
  22167. Camera.prototype.isReady = function (completeCheck) {
  22168. if (completeCheck === void 0) { completeCheck = false; }
  22169. if (completeCheck) {
  22170. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22171. var pp = _a[_i];
  22172. if (pp && !pp.isReady()) {
  22173. return false;
  22174. }
  22175. }
  22176. }
  22177. return _super.prototype.isReady.call(this, completeCheck);
  22178. };
  22179. //Cache
  22180. Camera.prototype._initCache = function () {
  22181. _super.prototype._initCache.call(this);
  22182. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22183. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22184. this._cache.mode = undefined;
  22185. this._cache.minZ = undefined;
  22186. this._cache.maxZ = undefined;
  22187. this._cache.fov = undefined;
  22188. this._cache.fovMode = undefined;
  22189. this._cache.aspectRatio = undefined;
  22190. this._cache.orthoLeft = undefined;
  22191. this._cache.orthoRight = undefined;
  22192. this._cache.orthoBottom = undefined;
  22193. this._cache.orthoTop = undefined;
  22194. this._cache.renderWidth = undefined;
  22195. this._cache.renderHeight = undefined;
  22196. };
  22197. Camera.prototype._updateCache = function (ignoreParentClass) {
  22198. if (!ignoreParentClass) {
  22199. _super.prototype._updateCache.call(this);
  22200. }
  22201. this._cache.position.copyFrom(this.position);
  22202. this._cache.upVector.copyFrom(this.upVector);
  22203. };
  22204. // Synchronized
  22205. Camera.prototype._isSynchronized = function () {
  22206. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22207. };
  22208. Camera.prototype._isSynchronizedViewMatrix = function () {
  22209. if (!_super.prototype._isSynchronized.call(this))
  22210. return false;
  22211. return this._cache.position.equals(this.position)
  22212. && this._cache.upVector.equals(this.upVector)
  22213. && this.isSynchronizedWithParent();
  22214. };
  22215. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22216. var check = this._cache.mode === this.mode
  22217. && this._cache.minZ === this.minZ
  22218. && this._cache.maxZ === this.maxZ;
  22219. if (!check) {
  22220. return false;
  22221. }
  22222. var engine = this.getEngine();
  22223. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22224. check = this._cache.fov === this.fov
  22225. && this._cache.fovMode === this.fovMode
  22226. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22227. }
  22228. else {
  22229. check = this._cache.orthoLeft === this.orthoLeft
  22230. && this._cache.orthoRight === this.orthoRight
  22231. && this._cache.orthoBottom === this.orthoBottom
  22232. && this._cache.orthoTop === this.orthoTop
  22233. && this._cache.renderWidth === engine.getRenderWidth()
  22234. && this._cache.renderHeight === engine.getRenderHeight();
  22235. }
  22236. return check;
  22237. };
  22238. // Controls
  22239. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22240. };
  22241. Camera.prototype.detachControl = function (element) {
  22242. };
  22243. Camera.prototype.update = function () {
  22244. this._checkInputs();
  22245. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22246. this._updateRigCameras();
  22247. }
  22248. };
  22249. Camera.prototype._checkInputs = function () {
  22250. this.onAfterCheckInputsObservable.notifyObservers(this);
  22251. };
  22252. Object.defineProperty(Camera.prototype, "rigCameras", {
  22253. get: function () {
  22254. return this._rigCameras;
  22255. },
  22256. enumerable: true,
  22257. configurable: true
  22258. });
  22259. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22260. get: function () {
  22261. return this._rigPostProcess;
  22262. },
  22263. enumerable: true,
  22264. configurable: true
  22265. });
  22266. /**
  22267. * Internal, gets the first post proces.
  22268. * @returns the first post process to be run on this camera.
  22269. */
  22270. Camera.prototype._getFirstPostProcess = function () {
  22271. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22272. if (this._postProcesses[ppIndex] !== null) {
  22273. return this._postProcesses[ppIndex];
  22274. }
  22275. }
  22276. return null;
  22277. };
  22278. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22279. // invalidate framebuffer
  22280. var firstPostProcess = this._getFirstPostProcess();
  22281. if (firstPostProcess) {
  22282. firstPostProcess.markTextureDirty();
  22283. }
  22284. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22285. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22286. var cam = this._rigCameras[i];
  22287. var rigPostProcess = cam._rigPostProcess;
  22288. // for VR rig, there does not have to be a post process
  22289. if (rigPostProcess) {
  22290. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22291. if (isPass) {
  22292. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22293. cam.isIntermediate = this._postProcesses.length === 0;
  22294. }
  22295. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22296. rigPostProcess.markTextureDirty();
  22297. }
  22298. else {
  22299. cam._postProcesses = this._postProcesses.slice(0);
  22300. }
  22301. }
  22302. };
  22303. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22304. if (insertAt === void 0) { insertAt = null; }
  22305. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22306. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22307. return 0;
  22308. }
  22309. if (insertAt == null || insertAt < 0) {
  22310. this._postProcesses.push(postProcess);
  22311. }
  22312. else if (this._postProcesses[insertAt] === null) {
  22313. this._postProcesses[insertAt] = postProcess;
  22314. }
  22315. else {
  22316. this._postProcesses.splice(insertAt, 0, postProcess);
  22317. }
  22318. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22319. return this._postProcesses.indexOf(postProcess);
  22320. };
  22321. Camera.prototype.detachPostProcess = function (postProcess) {
  22322. var idx = this._postProcesses.indexOf(postProcess);
  22323. if (idx !== -1) {
  22324. this._postProcesses[idx] = null;
  22325. }
  22326. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22327. };
  22328. Camera.prototype.getWorldMatrix = function () {
  22329. if (this._isSynchronizedViewMatrix()) {
  22330. return this._worldMatrix;
  22331. }
  22332. // Getting the the view matrix will also compute the world matrix.
  22333. this.getViewMatrix();
  22334. return this._worldMatrix;
  22335. };
  22336. Camera.prototype._getViewMatrix = function () {
  22337. return BABYLON.Matrix.Identity();
  22338. };
  22339. Camera.prototype.getViewMatrix = function (force) {
  22340. if (!force && this._isSynchronizedViewMatrix()) {
  22341. return this._computedViewMatrix;
  22342. }
  22343. this.updateCache();
  22344. this._computedViewMatrix = this._getViewMatrix();
  22345. this._currentRenderId = this.getScene().getRenderId();
  22346. this._childRenderId = this._currentRenderId;
  22347. this._refreshFrustumPlanes = true;
  22348. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22349. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22350. }
  22351. this.onViewMatrixChangedObservable.notifyObservers(this);
  22352. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22353. return this._computedViewMatrix;
  22354. };
  22355. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22356. this._doNotComputeProjectionMatrix = true;
  22357. if (projection !== undefined) {
  22358. this._projectionMatrix = projection;
  22359. }
  22360. };
  22361. ;
  22362. Camera.prototype.unfreezeProjectionMatrix = function () {
  22363. this._doNotComputeProjectionMatrix = false;
  22364. };
  22365. ;
  22366. Camera.prototype.getProjectionMatrix = function (force) {
  22367. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22368. return this._projectionMatrix;
  22369. }
  22370. // Cache
  22371. this._cache.mode = this.mode;
  22372. this._cache.minZ = this.minZ;
  22373. this._cache.maxZ = this.maxZ;
  22374. // Matrix
  22375. this._refreshFrustumPlanes = true;
  22376. var engine = this.getEngine();
  22377. var scene = this.getScene();
  22378. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22379. this._cache.fov = this.fov;
  22380. this._cache.fovMode = this.fovMode;
  22381. this._cache.aspectRatio = engine.getAspectRatio(this);
  22382. if (this.minZ <= 0) {
  22383. this.minZ = 0.1;
  22384. }
  22385. if (scene.useRightHandedSystem) {
  22386. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22387. }
  22388. else {
  22389. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22390. }
  22391. }
  22392. else {
  22393. var halfWidth = engine.getRenderWidth() / 2.0;
  22394. var halfHeight = engine.getRenderHeight() / 2.0;
  22395. if (scene.useRightHandedSystem) {
  22396. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22397. }
  22398. else {
  22399. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22400. }
  22401. this._cache.orthoLeft = this.orthoLeft;
  22402. this._cache.orthoRight = this.orthoRight;
  22403. this._cache.orthoBottom = this.orthoBottom;
  22404. this._cache.orthoTop = this.orthoTop;
  22405. this._cache.renderWidth = engine.getRenderWidth();
  22406. this._cache.renderHeight = engine.getRenderHeight();
  22407. }
  22408. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22409. return this._projectionMatrix;
  22410. };
  22411. Camera.prototype.getTranformationMatrix = function () {
  22412. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22413. return this._transformMatrix;
  22414. };
  22415. Camera.prototype.updateFrustumPlanes = function () {
  22416. if (!this._refreshFrustumPlanes) {
  22417. return;
  22418. }
  22419. this.getTranformationMatrix();
  22420. if (!this._frustumPlanes) {
  22421. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22422. }
  22423. else {
  22424. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22425. }
  22426. this._refreshFrustumPlanes = false;
  22427. };
  22428. Camera.prototype.isInFrustum = function (target) {
  22429. this.updateFrustumPlanes();
  22430. return target.isInFrustum(this._frustumPlanes);
  22431. };
  22432. Camera.prototype.isCompletelyInFrustum = function (target) {
  22433. this.updateFrustumPlanes();
  22434. return target.isCompletelyInFrustum(this._frustumPlanes);
  22435. };
  22436. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22437. if (length === void 0) { length = 100; }
  22438. if (!transform) {
  22439. transform = this.getWorldMatrix();
  22440. }
  22441. if (!origin) {
  22442. origin = this.position;
  22443. }
  22444. var forward = new BABYLON.Vector3(0, 0, 1);
  22445. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22446. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22447. return new BABYLON.Ray(origin, direction, length);
  22448. };
  22449. /**
  22450. * Releases resources associated with this node.
  22451. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22452. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22453. */
  22454. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22455. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22456. // Observables
  22457. this.onViewMatrixChangedObservable.clear();
  22458. this.onProjectionMatrixChangedObservable.clear();
  22459. this.onAfterCheckInputsObservable.clear();
  22460. this.onRestoreStateObservable.clear();
  22461. // Inputs
  22462. if (this.inputs) {
  22463. this.inputs.clear();
  22464. }
  22465. // Animations
  22466. this.getScene().stopAnimation(this);
  22467. // Remove from scene
  22468. this.getScene().removeCamera(this);
  22469. while (this._rigCameras.length > 0) {
  22470. var camera = this._rigCameras.pop();
  22471. if (camera) {
  22472. camera.dispose();
  22473. }
  22474. }
  22475. // Postprocesses
  22476. if (this._rigPostProcess) {
  22477. this._rigPostProcess.dispose(this);
  22478. this._rigPostProcess = null;
  22479. this._postProcesses = [];
  22480. }
  22481. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22482. this._rigPostProcess = null;
  22483. this._postProcesses = [];
  22484. }
  22485. else {
  22486. var i = this._postProcesses.length;
  22487. while (--i >= 0) {
  22488. var postProcess = this._postProcesses[i];
  22489. if (postProcess) {
  22490. postProcess.dispose(this);
  22491. }
  22492. }
  22493. }
  22494. // Render targets
  22495. var i = this.customRenderTargets.length;
  22496. while (--i >= 0) {
  22497. this.customRenderTargets[i].dispose();
  22498. }
  22499. this.customRenderTargets = [];
  22500. // Active Meshes
  22501. this._activeMeshes.dispose();
  22502. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22503. };
  22504. Object.defineProperty(Camera.prototype, "leftCamera", {
  22505. // ---- Camera rigs section ----
  22506. get: function () {
  22507. if (this._rigCameras.length < 1) {
  22508. return null;
  22509. }
  22510. return this._rigCameras[0];
  22511. },
  22512. enumerable: true,
  22513. configurable: true
  22514. });
  22515. Object.defineProperty(Camera.prototype, "rightCamera", {
  22516. get: function () {
  22517. if (this._rigCameras.length < 2) {
  22518. return null;
  22519. }
  22520. return this._rigCameras[1];
  22521. },
  22522. enumerable: true,
  22523. configurable: true
  22524. });
  22525. Camera.prototype.getLeftTarget = function () {
  22526. if (this._rigCameras.length < 1) {
  22527. return null;
  22528. }
  22529. return this._rigCameras[0].getTarget();
  22530. };
  22531. Camera.prototype.getRightTarget = function () {
  22532. if (this._rigCameras.length < 2) {
  22533. return null;
  22534. }
  22535. return this._rigCameras[1].getTarget();
  22536. };
  22537. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22538. if (this.cameraRigMode === mode) {
  22539. return;
  22540. }
  22541. while (this._rigCameras.length > 0) {
  22542. var camera = this._rigCameras.pop();
  22543. if (camera) {
  22544. camera.dispose();
  22545. }
  22546. }
  22547. this.cameraRigMode = mode;
  22548. this._cameraRigParams = {};
  22549. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22550. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22551. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22552. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22553. // create the rig cameras, unless none
  22554. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22555. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22556. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22557. if (leftCamera && rightCamera) {
  22558. this._rigCameras.push(leftCamera);
  22559. this._rigCameras.push(rightCamera);
  22560. }
  22561. }
  22562. switch (this.cameraRigMode) {
  22563. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22564. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22565. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22566. break;
  22567. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22568. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22569. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22570. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22571. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22572. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22573. break;
  22574. case Camera.RIG_MODE_VR:
  22575. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22576. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22577. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22578. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22579. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22580. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22581. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22582. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22583. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22584. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22585. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22586. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22587. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22588. if (metrics.compensateDistortion) {
  22589. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22590. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22591. }
  22592. break;
  22593. case Camera.RIG_MODE_WEBVR:
  22594. if (rigParams.vrDisplay) {
  22595. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22596. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22597. //Left eye
  22598. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22599. this._rigCameras[0].setCameraRigParameter("left", true);
  22600. //leaving this for future reference
  22601. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22602. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22603. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22604. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22605. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22606. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22607. this._rigCameras[0].parent = this;
  22608. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22609. //Right eye
  22610. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22611. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22612. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22613. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22614. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22615. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22616. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22617. this._rigCameras[1].parent = this;
  22618. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22619. if (Camera.UseAlternateWebVRRendering) {
  22620. this._rigCameras[1]._skipRendering = true;
  22621. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22622. }
  22623. }
  22624. break;
  22625. }
  22626. this._cascadePostProcessesToRigCams();
  22627. this.update();
  22628. };
  22629. Camera.prototype._getVRProjectionMatrix = function () {
  22630. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22631. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22632. return this._projectionMatrix;
  22633. };
  22634. Camera.prototype._updateCameraRotationMatrix = function () {
  22635. //Here for WebVR
  22636. };
  22637. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22638. //Here for WebVR
  22639. };
  22640. /**
  22641. * This function MUST be overwritten by the different WebVR cameras available.
  22642. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22643. */
  22644. Camera.prototype._getWebVRProjectionMatrix = function () {
  22645. return BABYLON.Matrix.Identity();
  22646. };
  22647. /**
  22648. * This function MUST be overwritten by the different WebVR cameras available.
  22649. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22650. */
  22651. Camera.prototype._getWebVRViewMatrix = function () {
  22652. return BABYLON.Matrix.Identity();
  22653. };
  22654. Camera.prototype.setCameraRigParameter = function (name, value) {
  22655. if (!this._cameraRigParams) {
  22656. this._cameraRigParams = {};
  22657. }
  22658. this._cameraRigParams[name] = value;
  22659. //provisionnally:
  22660. if (name === "interaxialDistance") {
  22661. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22662. }
  22663. };
  22664. /**
  22665. * needs to be overridden by children so sub has required properties to be copied
  22666. */
  22667. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22668. return null;
  22669. };
  22670. /**
  22671. * May need to be overridden by children
  22672. */
  22673. Camera.prototype._updateRigCameras = function () {
  22674. for (var i = 0; i < this._rigCameras.length; i++) {
  22675. this._rigCameras[i].minZ = this.minZ;
  22676. this._rigCameras[i].maxZ = this.maxZ;
  22677. this._rigCameras[i].fov = this.fov;
  22678. }
  22679. // only update viewport when ANAGLYPH
  22680. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22681. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22682. }
  22683. };
  22684. Camera.prototype._setupInputs = function () {
  22685. };
  22686. Camera.prototype.serialize = function () {
  22687. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22688. // Type
  22689. serializationObject.type = this.getClassName();
  22690. // Parent
  22691. if (this.parent) {
  22692. serializationObject.parentId = this.parent.id;
  22693. }
  22694. if (this.inputs) {
  22695. this.inputs.serialize(serializationObject);
  22696. }
  22697. // Animations
  22698. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22699. serializationObject.ranges = this.serializeAnimationRanges();
  22700. return serializationObject;
  22701. };
  22702. Camera.prototype.clone = function (name) {
  22703. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22704. };
  22705. Camera.prototype.getDirection = function (localAxis) {
  22706. var result = BABYLON.Vector3.Zero();
  22707. this.getDirectionToRef(localAxis, result);
  22708. return result;
  22709. };
  22710. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22711. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22712. };
  22713. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22714. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22715. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22716. switch (type) {
  22717. case "ArcRotateCamera":
  22718. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22719. case "DeviceOrientationCamera":
  22720. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22721. case "FollowCamera":
  22722. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22723. case "ArcFollowCamera":
  22724. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22725. case "GamepadCamera":
  22726. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22727. case "TouchCamera":
  22728. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22729. case "VirtualJoysticksCamera":
  22730. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22731. case "WebVRFreeCamera":
  22732. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22733. case "WebVRGamepadCamera":
  22734. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22735. case "VRDeviceOrientationFreeCamera":
  22736. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22737. case "VRDeviceOrientationGamepadCamera":
  22738. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22739. case "AnaglyphArcRotateCamera":
  22740. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22741. case "AnaglyphFreeCamera":
  22742. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22743. case "AnaglyphGamepadCamera":
  22744. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22745. case "AnaglyphUniversalCamera":
  22746. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22747. case "StereoscopicArcRotateCamera":
  22748. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22749. case "StereoscopicFreeCamera":
  22750. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22751. case "StereoscopicGamepadCamera":
  22752. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22753. case "StereoscopicUniversalCamera":
  22754. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22755. case "FreeCamera": // Forcing Universal here
  22756. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22757. default: // Universal Camera is the default value
  22758. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22759. }
  22760. };
  22761. Camera.prototype.computeWorldMatrix = function () {
  22762. return this.getWorldMatrix();
  22763. };
  22764. Camera.Parse = function (parsedCamera, scene) {
  22765. var type = parsedCamera.type;
  22766. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22767. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22768. // Parent
  22769. if (parsedCamera.parentId) {
  22770. camera._waitingParentId = parsedCamera.parentId;
  22771. }
  22772. //If camera has an input manager, let it parse inputs settings
  22773. if (camera.inputs) {
  22774. camera.inputs.parse(parsedCamera);
  22775. camera._setupInputs();
  22776. }
  22777. if (camera.setPosition) { // need to force position
  22778. camera.position.copyFromFloats(0, 0, 0);
  22779. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22780. }
  22781. // Target
  22782. if (parsedCamera.target) {
  22783. if (camera.setTarget) {
  22784. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22785. }
  22786. }
  22787. // Apply 3d rig, when found
  22788. if (parsedCamera.cameraRigMode) {
  22789. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22790. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22791. }
  22792. // Animations
  22793. if (parsedCamera.animations) {
  22794. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22795. var parsedAnimation = parsedCamera.animations[animationIndex];
  22796. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22797. }
  22798. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22799. }
  22800. if (parsedCamera.autoAnimate) {
  22801. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22802. }
  22803. return camera;
  22804. };
  22805. // Statics
  22806. Camera._PERSPECTIVE_CAMERA = 0;
  22807. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22808. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22809. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22810. Camera._RIG_MODE_NONE = 0;
  22811. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22812. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22813. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22814. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22815. Camera._RIG_MODE_VR = 20;
  22816. Camera._RIG_MODE_WEBVR = 21;
  22817. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22818. Camera.UseAlternateWebVRRendering = false;
  22819. __decorate([
  22820. BABYLON.serializeAsVector3()
  22821. ], Camera.prototype, "position", void 0);
  22822. __decorate([
  22823. BABYLON.serializeAsVector3()
  22824. ], Camera.prototype, "upVector", void 0);
  22825. __decorate([
  22826. BABYLON.serialize()
  22827. ], Camera.prototype, "orthoLeft", void 0);
  22828. __decorate([
  22829. BABYLON.serialize()
  22830. ], Camera.prototype, "orthoRight", void 0);
  22831. __decorate([
  22832. BABYLON.serialize()
  22833. ], Camera.prototype, "orthoBottom", void 0);
  22834. __decorate([
  22835. BABYLON.serialize()
  22836. ], Camera.prototype, "orthoTop", void 0);
  22837. __decorate([
  22838. BABYLON.serialize()
  22839. ], Camera.prototype, "fov", void 0);
  22840. __decorate([
  22841. BABYLON.serialize()
  22842. ], Camera.prototype, "minZ", void 0);
  22843. __decorate([
  22844. BABYLON.serialize()
  22845. ], Camera.prototype, "maxZ", void 0);
  22846. __decorate([
  22847. BABYLON.serialize()
  22848. ], Camera.prototype, "inertia", void 0);
  22849. __decorate([
  22850. BABYLON.serialize()
  22851. ], Camera.prototype, "mode", void 0);
  22852. __decorate([
  22853. BABYLON.serialize()
  22854. ], Camera.prototype, "layerMask", void 0);
  22855. __decorate([
  22856. BABYLON.serialize()
  22857. ], Camera.prototype, "fovMode", void 0);
  22858. __decorate([
  22859. BABYLON.serialize()
  22860. ], Camera.prototype, "cameraRigMode", void 0);
  22861. __decorate([
  22862. BABYLON.serialize()
  22863. ], Camera.prototype, "interaxialDistance", void 0);
  22864. __decorate([
  22865. BABYLON.serialize()
  22866. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22867. return Camera;
  22868. }(BABYLON.Node));
  22869. BABYLON.Camera = Camera;
  22870. })(BABYLON || (BABYLON = {}));
  22871. //# sourceMappingURL=babylon.camera.js.map
  22872. var BABYLON;
  22873. (function (BABYLON) {
  22874. var RenderingManager = /** @class */ (function () {
  22875. function RenderingManager(scene) {
  22876. this._renderingGroups = new Array();
  22877. this._autoClearDepthStencil = {};
  22878. this._customOpaqueSortCompareFn = {};
  22879. this._customAlphaTestSortCompareFn = {};
  22880. this._customTransparentSortCompareFn = {};
  22881. this._renderinGroupInfo = null;
  22882. this._scene = scene;
  22883. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22884. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22885. }
  22886. }
  22887. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22888. if (depth === void 0) { depth = true; }
  22889. if (stencil === void 0) { stencil = true; }
  22890. if (this._depthStencilBufferAlreadyCleaned) {
  22891. return;
  22892. }
  22893. this._scene.getEngine().clear(null, false, depth, stencil);
  22894. this._depthStencilBufferAlreadyCleaned = true;
  22895. };
  22896. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22897. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22898. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22899. var info = null;
  22900. if (observable) {
  22901. if (!this._renderinGroupInfo) {
  22902. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22903. }
  22904. info = this._renderinGroupInfo;
  22905. info.scene = this._scene;
  22906. info.camera = this._scene.activeCamera;
  22907. }
  22908. // Dispatch sprites
  22909. if (renderSprites) {
  22910. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22911. var manager = this._scene.spriteManagers[index];
  22912. this.dispatchSprites(manager);
  22913. }
  22914. }
  22915. // Render
  22916. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22917. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22918. var renderingGroup = this._renderingGroups[index];
  22919. if (!renderingGroup && !observable)
  22920. continue;
  22921. var renderingGroupMask = 0;
  22922. // Fire PRECLEAR stage
  22923. if (observable && info) {
  22924. renderingGroupMask = Math.pow(2, index);
  22925. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22926. info.renderingGroupId = index;
  22927. observable.notifyObservers(info, renderingGroupMask);
  22928. }
  22929. // Clear depth/stencil if needed
  22930. if (RenderingManager.AUTOCLEAR) {
  22931. var autoClear = this._autoClearDepthStencil[index];
  22932. if (autoClear && autoClear.autoClear) {
  22933. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22934. }
  22935. }
  22936. if (observable && info) {
  22937. // Fire PREOPAQUE stage
  22938. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22939. observable.notifyObservers(info, renderingGroupMask);
  22940. // Fire PRETRANSPARENT stage
  22941. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22942. observable.notifyObservers(info, renderingGroupMask);
  22943. }
  22944. if (renderingGroup)
  22945. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22946. // Fire POSTTRANSPARENT stage
  22947. if (observable && info) {
  22948. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22949. observable.notifyObservers(info, renderingGroupMask);
  22950. }
  22951. }
  22952. };
  22953. RenderingManager.prototype.reset = function () {
  22954. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22955. var renderingGroup = this._renderingGroups[index];
  22956. if (renderingGroup) {
  22957. renderingGroup.prepare();
  22958. }
  22959. }
  22960. };
  22961. RenderingManager.prototype.dispose = function () {
  22962. this.freeRenderingGroups();
  22963. this._renderingGroups.length = 0;
  22964. };
  22965. /**
  22966. * Clear the info related to rendering groups preventing retention points during dispose.
  22967. */
  22968. RenderingManager.prototype.freeRenderingGroups = function () {
  22969. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22970. var renderingGroup = this._renderingGroups[index];
  22971. if (renderingGroup) {
  22972. renderingGroup.dispose();
  22973. }
  22974. }
  22975. };
  22976. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22977. if (this._renderingGroups[renderingGroupId] === undefined) {
  22978. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  22979. }
  22980. };
  22981. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  22982. var renderingGroupId = spriteManager.renderingGroupId || 0;
  22983. this._prepareRenderingGroup(renderingGroupId);
  22984. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  22985. };
  22986. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  22987. var renderingGroupId = particleSystem.renderingGroupId || 0;
  22988. this._prepareRenderingGroup(renderingGroupId);
  22989. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  22990. };
  22991. /**
  22992. * @param subMesh The submesh to dispatch
  22993. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  22994. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  22995. */
  22996. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  22997. if (mesh === undefined) {
  22998. mesh = subMesh.getMesh();
  22999. }
  23000. var renderingGroupId = mesh.renderingGroupId || 0;
  23001. this._prepareRenderingGroup(renderingGroupId);
  23002. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23003. };
  23004. /**
  23005. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23006. * This allowed control for front to back rendering or reversly depending of the special needs.
  23007. *
  23008. * @param renderingGroupId The rendering group id corresponding to its index
  23009. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23010. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23011. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23012. */
  23013. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23014. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23015. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23016. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23017. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23018. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23019. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23020. if (this._renderingGroups[renderingGroupId]) {
  23021. var group = this._renderingGroups[renderingGroupId];
  23022. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23023. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23024. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23025. }
  23026. };
  23027. /**
  23028. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23029. *
  23030. * @param renderingGroupId The rendering group id corresponding to its index
  23031. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23032. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23033. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23034. */
  23035. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23036. if (depth === void 0) { depth = true; }
  23037. if (stencil === void 0) { stencil = true; }
  23038. this._autoClearDepthStencil[renderingGroupId] = {
  23039. autoClear: autoClearDepthStencil,
  23040. depth: depth,
  23041. stencil: stencil
  23042. };
  23043. };
  23044. /**
  23045. * The max id used for rendering groups (not included)
  23046. */
  23047. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23048. /**
  23049. * The min id used for rendering groups (included)
  23050. */
  23051. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23052. /**
  23053. * Used to globally prevent autoclearing scenes.
  23054. */
  23055. RenderingManager.AUTOCLEAR = true;
  23056. return RenderingManager;
  23057. }());
  23058. BABYLON.RenderingManager = RenderingManager;
  23059. })(BABYLON || (BABYLON = {}));
  23060. //# sourceMappingURL=babylon.renderingManager.js.map
  23061. var BABYLON;
  23062. (function (BABYLON) {
  23063. var RenderingGroup = /** @class */ (function () {
  23064. /**
  23065. * Creates a new rendering group.
  23066. * @param index The rendering group index
  23067. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23068. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23069. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23070. */
  23071. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23072. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23073. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23074. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23075. this.index = index;
  23076. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23077. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23078. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23079. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23080. this._particleSystems = new BABYLON.SmartArray(256);
  23081. this._spriteManagers = new BABYLON.SmartArray(256);
  23082. this._edgesRenderers = new BABYLON.SmartArray(16);
  23083. this._scene = scene;
  23084. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23085. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23086. this.transparentSortCompareFn = transparentSortCompareFn;
  23087. }
  23088. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23089. /**
  23090. * Set the opaque sort comparison function.
  23091. * If null the sub meshes will be render in the order they were created
  23092. */
  23093. set: function (value) {
  23094. this._opaqueSortCompareFn = value;
  23095. if (value) {
  23096. this._renderOpaque = this.renderOpaqueSorted;
  23097. }
  23098. else {
  23099. this._renderOpaque = RenderingGroup.renderUnsorted;
  23100. }
  23101. },
  23102. enumerable: true,
  23103. configurable: true
  23104. });
  23105. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23106. /**
  23107. * Set the alpha test sort comparison function.
  23108. * If null the sub meshes will be render in the order they were created
  23109. */
  23110. set: function (value) {
  23111. this._alphaTestSortCompareFn = value;
  23112. if (value) {
  23113. this._renderAlphaTest = this.renderAlphaTestSorted;
  23114. }
  23115. else {
  23116. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23117. }
  23118. },
  23119. enumerable: true,
  23120. configurable: true
  23121. });
  23122. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23123. /**
  23124. * Set the transparent sort comparison function.
  23125. * If null the sub meshes will be render in the order they were created
  23126. */
  23127. set: function (value) {
  23128. if (value) {
  23129. this._transparentSortCompareFn = value;
  23130. }
  23131. else {
  23132. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23133. }
  23134. this._renderTransparent = this.renderTransparentSorted;
  23135. },
  23136. enumerable: true,
  23137. configurable: true
  23138. });
  23139. /**
  23140. * Render all the sub meshes contained in the group.
  23141. * @param customRenderFunction Used to override the default render behaviour of the group.
  23142. * @returns true if rendered some submeshes.
  23143. */
  23144. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23145. if (customRenderFunction) {
  23146. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23147. return;
  23148. }
  23149. var engine = this._scene.getEngine();
  23150. // Depth only
  23151. if (this._depthOnlySubMeshes.length !== 0) {
  23152. engine.setColorWrite(false);
  23153. this._renderAlphaTest(this._depthOnlySubMeshes);
  23154. engine.setColorWrite(true);
  23155. }
  23156. // Opaque
  23157. if (this._opaqueSubMeshes.length !== 0) {
  23158. this._renderOpaque(this._opaqueSubMeshes);
  23159. }
  23160. // Alpha test
  23161. if (this._alphaTestSubMeshes.length !== 0) {
  23162. this._renderAlphaTest(this._alphaTestSubMeshes);
  23163. }
  23164. var stencilState = engine.getStencilBuffer();
  23165. engine.setStencilBuffer(false);
  23166. // Sprites
  23167. if (renderSprites) {
  23168. this._renderSprites();
  23169. }
  23170. // Particles
  23171. if (renderParticles) {
  23172. this._renderParticles(activeMeshes);
  23173. }
  23174. if (this.onBeforeTransparentRendering) {
  23175. this.onBeforeTransparentRendering();
  23176. }
  23177. // Transparent
  23178. if (this._transparentSubMeshes.length !== 0) {
  23179. this._renderTransparent(this._transparentSubMeshes);
  23180. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23181. }
  23182. // Set back stencil to false in case it changes before the edge renderer.
  23183. engine.setStencilBuffer(false);
  23184. // Edges
  23185. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23186. this._edgesRenderers.data[edgesRendererIndex].render();
  23187. }
  23188. // Restore Stencil state.
  23189. engine.setStencilBuffer(stencilState);
  23190. };
  23191. /**
  23192. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23193. * @param subMeshes The submeshes to render
  23194. */
  23195. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23196. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23197. };
  23198. /**
  23199. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23200. * @param subMeshes The submeshes to render
  23201. */
  23202. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23203. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23204. };
  23205. /**
  23206. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23207. * @param subMeshes The submeshes to render
  23208. */
  23209. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23210. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23211. };
  23212. /**
  23213. * Renders the submeshes in a specified order.
  23214. * @param subMeshes The submeshes to sort before render
  23215. * @param sortCompareFn The comparison function use to sort
  23216. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23217. * @param transparent Specifies to activate blending if true
  23218. */
  23219. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23220. var subIndex = 0;
  23221. var subMesh;
  23222. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23223. for (; subIndex < subMeshes.length; subIndex++) {
  23224. subMesh = subMeshes.data[subIndex];
  23225. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23226. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23227. }
  23228. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23229. if (sortCompareFn) {
  23230. sortedArray.sort(sortCompareFn);
  23231. }
  23232. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23233. subMesh = sortedArray[subIndex];
  23234. if (transparent) {
  23235. var material = subMesh.getMaterial();
  23236. if (material && material.needDepthPrePass) {
  23237. var engine = material.getScene().getEngine();
  23238. engine.setColorWrite(false);
  23239. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23240. subMesh.render(false);
  23241. engine.setColorWrite(true);
  23242. }
  23243. }
  23244. subMesh.render(transparent);
  23245. }
  23246. };
  23247. /**
  23248. * Renders the submeshes in the order they were dispatched (no sort applied).
  23249. * @param subMeshes The submeshes to render
  23250. */
  23251. RenderingGroup.renderUnsorted = function (subMeshes) {
  23252. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23253. var submesh = subMeshes.data[subIndex];
  23254. submesh.render(false);
  23255. }
  23256. };
  23257. /**
  23258. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23259. * are rendered back to front if in the same alpha index.
  23260. *
  23261. * @param a The first submesh
  23262. * @param b The second submesh
  23263. * @returns The result of the comparison
  23264. */
  23265. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23266. // Alpha index first
  23267. if (a._alphaIndex > b._alphaIndex) {
  23268. return 1;
  23269. }
  23270. if (a._alphaIndex < b._alphaIndex) {
  23271. return -1;
  23272. }
  23273. // Then distance to camera
  23274. return RenderingGroup.backToFrontSortCompare(a, b);
  23275. };
  23276. /**
  23277. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23278. * are rendered back to front.
  23279. *
  23280. * @param a The first submesh
  23281. * @param b The second submesh
  23282. * @returns The result of the comparison
  23283. */
  23284. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23285. // Then distance to camera
  23286. if (a._distanceToCamera < b._distanceToCamera) {
  23287. return 1;
  23288. }
  23289. if (a._distanceToCamera > b._distanceToCamera) {
  23290. return -1;
  23291. }
  23292. return 0;
  23293. };
  23294. /**
  23295. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23296. * are rendered front to back (prevent overdraw).
  23297. *
  23298. * @param a The first submesh
  23299. * @param b The second submesh
  23300. * @returns The result of the comparison
  23301. */
  23302. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23303. // Then distance to camera
  23304. if (a._distanceToCamera < b._distanceToCamera) {
  23305. return -1;
  23306. }
  23307. if (a._distanceToCamera > b._distanceToCamera) {
  23308. return 1;
  23309. }
  23310. return 0;
  23311. };
  23312. /**
  23313. * Resets the different lists of submeshes to prepare a new frame.
  23314. */
  23315. RenderingGroup.prototype.prepare = function () {
  23316. this._opaqueSubMeshes.reset();
  23317. this._transparentSubMeshes.reset();
  23318. this._alphaTestSubMeshes.reset();
  23319. this._depthOnlySubMeshes.reset();
  23320. this._particleSystems.reset();
  23321. this._spriteManagers.reset();
  23322. this._edgesRenderers.reset();
  23323. };
  23324. RenderingGroup.prototype.dispose = function () {
  23325. this._opaqueSubMeshes.dispose();
  23326. this._transparentSubMeshes.dispose();
  23327. this._alphaTestSubMeshes.dispose();
  23328. this._depthOnlySubMeshes.dispose();
  23329. this._particleSystems.dispose();
  23330. this._spriteManagers.dispose();
  23331. this._edgesRenderers.dispose();
  23332. };
  23333. /**
  23334. * Inserts the submesh in its correct queue depending on its material.
  23335. * @param subMesh The submesh to dispatch
  23336. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23337. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23338. */
  23339. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23340. // Get mesh and materials if not provided
  23341. if (mesh === undefined) {
  23342. mesh = subMesh.getMesh();
  23343. }
  23344. if (material === undefined) {
  23345. material = subMesh.getMaterial();
  23346. }
  23347. if (material === null || material === undefined) {
  23348. return;
  23349. }
  23350. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23351. this._transparentSubMeshes.push(subMesh);
  23352. }
  23353. else if (material.needAlphaTesting()) { // Alpha test
  23354. if (material.needDepthPrePass) {
  23355. this._depthOnlySubMeshes.push(subMesh);
  23356. }
  23357. this._alphaTestSubMeshes.push(subMesh);
  23358. }
  23359. else {
  23360. if (material.needDepthPrePass) {
  23361. this._depthOnlySubMeshes.push(subMesh);
  23362. }
  23363. this._opaqueSubMeshes.push(subMesh); // Opaque
  23364. }
  23365. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23366. this._edgesRenderers.push(mesh._edgesRenderer);
  23367. }
  23368. };
  23369. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23370. this._spriteManagers.push(spriteManager);
  23371. };
  23372. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23373. this._particleSystems.push(particleSystem);
  23374. };
  23375. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23376. if (this._particleSystems.length === 0) {
  23377. return;
  23378. }
  23379. // Particles
  23380. var activeCamera = this._scene.activeCamera;
  23381. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23382. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23383. var particleSystem = this._particleSystems.data[particleIndex];
  23384. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23385. continue;
  23386. }
  23387. var emitter = particleSystem.emitter;
  23388. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23389. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23390. }
  23391. }
  23392. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23393. };
  23394. RenderingGroup.prototype._renderSprites = function () {
  23395. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23396. return;
  23397. }
  23398. // Sprites
  23399. var activeCamera = this._scene.activeCamera;
  23400. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23401. for (var id = 0; id < this._spriteManagers.length; id++) {
  23402. var spriteManager = this._spriteManagers.data[id];
  23403. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23404. spriteManager.render();
  23405. }
  23406. }
  23407. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23408. };
  23409. return RenderingGroup;
  23410. }());
  23411. BABYLON.RenderingGroup = RenderingGroup;
  23412. })(BABYLON || (BABYLON = {}));
  23413. //# sourceMappingURL=babylon.renderingGroup.js.map
  23414. var BABYLON;
  23415. (function (BABYLON) {
  23416. /** @hidden */
  23417. var ClickInfo = /** @class */ (function () {
  23418. function ClickInfo() {
  23419. this._singleClick = false;
  23420. this._doubleClick = false;
  23421. this._hasSwiped = false;
  23422. this._ignore = false;
  23423. }
  23424. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23425. get: function () {
  23426. return this._singleClick;
  23427. },
  23428. set: function (b) {
  23429. this._singleClick = b;
  23430. },
  23431. enumerable: true,
  23432. configurable: true
  23433. });
  23434. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23435. get: function () {
  23436. return this._doubleClick;
  23437. },
  23438. set: function (b) {
  23439. this._doubleClick = b;
  23440. },
  23441. enumerable: true,
  23442. configurable: true
  23443. });
  23444. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23445. get: function () {
  23446. return this._hasSwiped;
  23447. },
  23448. set: function (b) {
  23449. this._hasSwiped = b;
  23450. },
  23451. enumerable: true,
  23452. configurable: true
  23453. });
  23454. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23455. get: function () {
  23456. return this._ignore;
  23457. },
  23458. set: function (b) {
  23459. this._ignore = b;
  23460. },
  23461. enumerable: true,
  23462. configurable: true
  23463. });
  23464. return ClickInfo;
  23465. }());
  23466. /**
  23467. * This class is used by the onRenderingGroupObservable
  23468. */
  23469. var RenderingGroupInfo = /** @class */ (function () {
  23470. function RenderingGroupInfo() {
  23471. }
  23472. /**
  23473. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23474. * This stage will be fired no matter what
  23475. */
  23476. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23477. /**
  23478. * Called before opaque object are rendered.
  23479. * This stage will be fired only if there's 3D Opaque content to render
  23480. */
  23481. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23482. /**
  23483. * Called after the opaque objects are rendered and before the transparent ones
  23484. * This stage will be fired only if there's 3D transparent content to render
  23485. */
  23486. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23487. /**
  23488. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23489. * This stage will be fired no matter what
  23490. */
  23491. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23492. return RenderingGroupInfo;
  23493. }());
  23494. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23495. /**
  23496. * Represents a scene to be rendered by the engine.
  23497. * @see http://doc.babylonjs.com/features/scene
  23498. */
  23499. var Scene = /** @class */ (function () {
  23500. /**
  23501. * Creates a new Scene
  23502. * @param engine defines the engine to use to render this scene
  23503. */
  23504. function Scene(engine) {
  23505. // Members
  23506. /**
  23507. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23508. */
  23509. this.autoClear = true;
  23510. /**
  23511. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23512. */
  23513. this.autoClearDepthAndStencil = true;
  23514. /**
  23515. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23516. */
  23517. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23518. /**
  23519. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23520. */
  23521. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23522. this._forceWireframe = false;
  23523. this._forcePointsCloud = false;
  23524. /**
  23525. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23526. */
  23527. this.forceShowBoundingBoxes = false;
  23528. /**
  23529. * Gets or sets a boolean indicating if animations are enabled
  23530. */
  23531. this.animationsEnabled = true;
  23532. this._animationPropertiesOverride = null;
  23533. /**
  23534. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23535. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23536. */
  23537. this.useConstantAnimationDeltaTime = false;
  23538. /**
  23539. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23540. * Please note that it requires to run a ray cast through the scene on every frame
  23541. */
  23542. this.constantlyUpdateMeshUnderPointer = false;
  23543. /**
  23544. * Defines the HTML cursor to use when hovering over interactive elements
  23545. */
  23546. this.hoverCursor = "pointer";
  23547. /**
  23548. * Defines the HTML default cursor to use (empty by default)
  23549. */
  23550. this.defaultCursor = "";
  23551. /**
  23552. * This is used to call preventDefault() on pointer down
  23553. * in order to block unwanted artifacts like system double clicks
  23554. */
  23555. this.preventDefaultOnPointerDown = true;
  23556. // Metadata
  23557. /**
  23558. * Gets or sets user defined metadata
  23559. */
  23560. this.metadata = null;
  23561. /**
  23562. * Use this array to add regular expressions used to disable offline support for specific urls
  23563. */
  23564. this.disableOfflineSupportExceptionRules = new Array();
  23565. /**
  23566. * An event triggered when the scene is disposed.
  23567. */
  23568. this.onDisposeObservable = new BABYLON.Observable();
  23569. this._onDisposeObserver = null;
  23570. /**
  23571. * An event triggered before rendering the scene (right after animations and physics)
  23572. */
  23573. this.onBeforeRenderObservable = new BABYLON.Observable();
  23574. this._onBeforeRenderObserver = null;
  23575. /**
  23576. * An event triggered after rendering the scene
  23577. */
  23578. this.onAfterRenderObservable = new BABYLON.Observable();
  23579. this._onAfterRenderObserver = null;
  23580. /**
  23581. * An event triggered before animating the scene
  23582. */
  23583. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23584. /**
  23585. * An event triggered after animations processing
  23586. */
  23587. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23588. /**
  23589. * An event triggered before draw calls are ready to be sent
  23590. */
  23591. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23592. /**
  23593. * An event triggered after draw calls have been sent
  23594. */
  23595. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23596. /**
  23597. * An event triggered when physic simulation is about to be run
  23598. */
  23599. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23600. /**
  23601. * An event triggered when physic simulation has been done
  23602. */
  23603. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23604. /**
  23605. * An event triggered when the scene is ready
  23606. */
  23607. this.onReadyObservable = new BABYLON.Observable();
  23608. /**
  23609. * An event triggered before rendering a camera
  23610. */
  23611. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23612. this._onBeforeCameraRenderObserver = null;
  23613. /**
  23614. * An event triggered after rendering a camera
  23615. */
  23616. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23617. this._onAfterCameraRenderObserver = null;
  23618. /**
  23619. * An event triggered when active meshes evaluation is about to start
  23620. */
  23621. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23622. /**
  23623. * An event triggered when active meshes evaluation is done
  23624. */
  23625. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23626. /**
  23627. * An event triggered when particles rendering is about to start
  23628. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23629. */
  23630. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23631. /**
  23632. * An event triggered when particles rendering is done
  23633. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23634. */
  23635. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23636. /**
  23637. * An event triggered when sprites rendering is about to start
  23638. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23639. */
  23640. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23641. /**
  23642. * An event triggered when sprites rendering is done
  23643. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23644. */
  23645. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23646. /**
  23647. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23648. */
  23649. this.onDataLoadedObservable = new BABYLON.Observable();
  23650. /**
  23651. * An event triggered when a camera is created
  23652. */
  23653. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23654. /**
  23655. * An event triggered when a camera is removed
  23656. */
  23657. this.onCameraRemovedObservable = new BABYLON.Observable();
  23658. /**
  23659. * An event triggered when a light is created
  23660. */
  23661. this.onNewLightAddedObservable = new BABYLON.Observable();
  23662. /**
  23663. * An event triggered when a light is removed
  23664. */
  23665. this.onLightRemovedObservable = new BABYLON.Observable();
  23666. /**
  23667. * An event triggered when a geometry is created
  23668. */
  23669. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23670. /**
  23671. * An event triggered when a geometry is removed
  23672. */
  23673. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23674. /**
  23675. * An event triggered when a transform node is created
  23676. */
  23677. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23678. /**
  23679. * An event triggered when a transform node is removed
  23680. */
  23681. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23682. /**
  23683. * An event triggered when a mesh is created
  23684. */
  23685. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23686. /**
  23687. * An event triggered when a mesh is removed
  23688. */
  23689. this.onMeshRemovedObservable = new BABYLON.Observable();
  23690. /**
  23691. * An event triggered when render targets are about to be rendered
  23692. * Can happen multiple times per frame.
  23693. */
  23694. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23695. /**
  23696. * An event triggered when render targets were rendered.
  23697. * Can happen multiple times per frame.
  23698. */
  23699. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23700. /**
  23701. * An event triggered before calculating deterministic simulation step
  23702. */
  23703. this.onBeforeStepObservable = new BABYLON.Observable();
  23704. /**
  23705. * An event triggered after calculating deterministic simulation step
  23706. */
  23707. this.onAfterStepObservable = new BABYLON.Observable();
  23708. /**
  23709. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23710. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23711. * 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)
  23712. */
  23713. this.onRenderingGroupObservable = new BABYLON.Observable();
  23714. // Animations
  23715. /**
  23716. * Gets a list of Animations associated with the scene
  23717. */
  23718. this.animations = [];
  23719. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23720. /**
  23721. * 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).
  23722. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23723. */
  23724. this.onPrePointerObservable = new BABYLON.Observable();
  23725. /**
  23726. * Observable event triggered each time an input event is received from the rendering canvas
  23727. */
  23728. this.onPointerObservable = new BABYLON.Observable();
  23729. this._meshPickProceed = false;
  23730. this._currentPickResult = null;
  23731. this._previousPickResult = null;
  23732. this._totalPointersPressed = 0;
  23733. this._doubleClickOccured = false;
  23734. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23735. this.cameraToUseForPointers = null;
  23736. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23737. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23738. this._startingPointerTime = 0;
  23739. this._previousStartingPointerTime = 0;
  23740. // Deterministic lockstep
  23741. this._timeAccumulator = 0;
  23742. this._currentStepId = 0;
  23743. this._currentInternalStep = 0;
  23744. // Keyboard
  23745. /**
  23746. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23747. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23748. */
  23749. this.onPreKeyboardObservable = new BABYLON.Observable();
  23750. /**
  23751. * Observable event triggered each time an keyboard event is received from the hosting window
  23752. */
  23753. this.onKeyboardObservable = new BABYLON.Observable();
  23754. // Coordinates system
  23755. this._useRightHandedSystem = false;
  23756. // Fog
  23757. this._fogEnabled = true;
  23758. this._fogMode = Scene.FOGMODE_NONE;
  23759. /**
  23760. * Gets or sets the fog color to use
  23761. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23762. */
  23763. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23764. /**
  23765. * Gets or sets the fog density to use
  23766. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23767. */
  23768. this.fogDensity = 0.1;
  23769. /**
  23770. * Gets or sets the fog start distance to use
  23771. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23772. */
  23773. this.fogStart = 0;
  23774. /**
  23775. * Gets or sets the fog end distance to use
  23776. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23777. */
  23778. this.fogEnd = 1000.0;
  23779. // Lights
  23780. this._shadowsEnabled = true;
  23781. this._lightsEnabled = true;
  23782. /**
  23783. * All of the lights added to this scene
  23784. * @see http://doc.babylonjs.com/babylon101/lights
  23785. */
  23786. this.lights = new Array();
  23787. // Cameras
  23788. /** All of the cameras added to this scene.
  23789. * @see http://doc.babylonjs.com/babylon101/cameras
  23790. */
  23791. this.cameras = new Array();
  23792. /** All of the active cameras added to this scene. */
  23793. this.activeCameras = new Array();
  23794. // Meshes
  23795. /**
  23796. * All of the tranform nodes added to this scene
  23797. * @see http://doc.babylonjs.com/how_to/transformnode
  23798. */
  23799. this.transformNodes = new Array();
  23800. /**
  23801. * All of the (abstract) meshes added to this scene
  23802. */
  23803. this.meshes = new Array();
  23804. /**
  23805. * All of the animation groups added to this scene
  23806. * @see http://doc.babylonjs.com/how_to/group
  23807. */
  23808. this.animationGroups = new Array();
  23809. // Geometries
  23810. this._geometries = new Array();
  23811. /**
  23812. * All of the materials added to this scene
  23813. * @see http://doc.babylonjs.com/babylon101/materials
  23814. */
  23815. this.materials = new Array();
  23816. /**
  23817. * All of the multi-materials added to this scene
  23818. * @see http://doc.babylonjs.com/how_to/multi_materials
  23819. */
  23820. this.multiMaterials = new Array();
  23821. // Textures
  23822. this._texturesEnabled = true;
  23823. /**
  23824. * All of the textures added to this scene
  23825. */
  23826. this.textures = new Array();
  23827. // Particles
  23828. /**
  23829. * Gets or sets a boolean indicating if particles are enabled on this scene
  23830. */
  23831. this.particlesEnabled = true;
  23832. /**
  23833. * All of the particle systems added to this scene
  23834. * @see http://doc.babylonjs.com/babylon101/particles
  23835. */
  23836. this.particleSystems = new Array();
  23837. // Sprites
  23838. /**
  23839. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23840. */
  23841. this.spritesEnabled = true;
  23842. /**
  23843. * All of the sprite managers added to this scene
  23844. * @see http://doc.babylonjs.com/babylon101/sprites
  23845. */
  23846. this.spriteManagers = new Array();
  23847. /**
  23848. * The list of layers (background and foreground) of the scene
  23849. */
  23850. this.layers = new Array();
  23851. /**
  23852. * The list of effect layers (highlights/glow) added to the scene
  23853. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23854. * @see http://doc.babylonjs.com/how_to/glow_layer
  23855. */
  23856. this.effectLayers = new Array();
  23857. // Skeletons
  23858. this._skeletonsEnabled = true;
  23859. /**
  23860. * The list of skeletons added to the scene
  23861. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23862. */
  23863. this.skeletons = new Array();
  23864. // Morph targets
  23865. /**
  23866. * The list of morph target managers added to the scene
  23867. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23868. */
  23869. this.morphTargetManagers = new Array();
  23870. // Lens flares
  23871. /**
  23872. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23873. */
  23874. this.lensFlaresEnabled = true;
  23875. /**
  23876. * The list of lens flare system added to the scene
  23877. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23878. */
  23879. this.lensFlareSystems = new Array();
  23880. // Collisions
  23881. /**
  23882. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23883. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23884. */
  23885. this.collisionsEnabled = true;
  23886. /**
  23887. * Defines the gravity applied to this scene (used only for collisions)
  23888. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23889. */
  23890. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23891. // Postprocesses
  23892. /**
  23893. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23894. */
  23895. this.postProcessesEnabled = true;
  23896. /**
  23897. * The list of postprocesses added to the scene
  23898. */
  23899. this.postProcesses = new Array();
  23900. // Customs render targets
  23901. /**
  23902. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23903. */
  23904. this.renderTargetsEnabled = true;
  23905. /**
  23906. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23907. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23908. */
  23909. this.dumpNextRenderTargets = false;
  23910. /**
  23911. * The list of user defined render targets added to the scene
  23912. */
  23913. this.customRenderTargets = new Array();
  23914. /**
  23915. * Gets the list of meshes imported to the scene through SceneLoader
  23916. */
  23917. this.importedMeshesFiles = new Array();
  23918. // Probes
  23919. /**
  23920. * Gets or sets a boolean indicating if probes are enabled on this scene
  23921. */
  23922. this.probesEnabled = true;
  23923. /**
  23924. * The list of reflection probes added to the scene
  23925. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23926. */
  23927. this.reflectionProbes = new Array();
  23928. /** @hidden */
  23929. this._actionManagers = new Array();
  23930. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23931. // Procedural textures
  23932. /**
  23933. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23934. */
  23935. this.proceduralTexturesEnabled = true;
  23936. /**
  23937. * The list of procedural textures added to the scene
  23938. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23939. */
  23940. this.proceduralTextures = new Array();
  23941. /**
  23942. * The list of sound tracks added to the scene
  23943. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23944. */
  23945. this.soundTracks = new Array();
  23946. this._audioEnabled = true;
  23947. this._headphone = false;
  23948. // Performance counters
  23949. this._totalVertices = new BABYLON.PerfCounter();
  23950. /** @hidden */
  23951. this._activeIndices = new BABYLON.PerfCounter();
  23952. /** @hidden */
  23953. this._activeParticles = new BABYLON.PerfCounter();
  23954. /** @hidden */
  23955. this._activeBones = new BABYLON.PerfCounter();
  23956. this._animationTime = 0;
  23957. /**
  23958. * Gets or sets a general scale for animation speed
  23959. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23960. */
  23961. this.animationTimeScale = 1;
  23962. this._renderId = 0;
  23963. this._executeWhenReadyTimeoutId = -1;
  23964. this._intermediateRendering = false;
  23965. this._viewUpdateFlag = -1;
  23966. this._projectionUpdateFlag = -1;
  23967. this._alternateViewUpdateFlag = -1;
  23968. this._alternateProjectionUpdateFlag = -1;
  23969. /** @hidden */
  23970. this._toBeDisposed = new BABYLON.SmartArray(256);
  23971. this._activeRequests = new Array();
  23972. this._pendingData = new Array();
  23973. this._isDisposed = false;
  23974. /**
  23975. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  23976. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  23977. */
  23978. this.dispatchAllSubMeshesOfActiveMeshes = false;
  23979. this._activeMeshes = new BABYLON.SmartArray(256);
  23980. this._processedMaterials = new BABYLON.SmartArray(256);
  23981. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  23982. /** @hidden */
  23983. this._activeParticleSystems = new BABYLON.SmartArray(256);
  23984. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  23985. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  23986. /** @hidden */
  23987. this._activeAnimatables = new Array();
  23988. this._transformMatrix = BABYLON.Matrix.Zero();
  23989. this._useAlternateCameraConfiguration = false;
  23990. this._alternateRendering = false;
  23991. /**
  23992. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  23993. * This is useful if there are more lights that the maximum simulteanous authorized
  23994. */
  23995. this.requireLightSorting = false;
  23996. this._depthRenderer = {};
  23997. this._activeMeshesFrozen = false;
  23998. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  23999. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24000. this._engine.scenes.push(this);
  24001. this._uid = null;
  24002. this._renderingManager = new BABYLON.RenderingManager(this);
  24003. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24004. if (BABYLON.OutlineRenderer) {
  24005. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24006. }
  24007. if (BABYLON.Tools.IsWindowObjectExist()) {
  24008. this.attachControl();
  24009. }
  24010. //simplification queue
  24011. if (BABYLON.SimplificationQueue) {
  24012. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24013. }
  24014. //collision coordinator initialization. For now legacy per default.
  24015. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24016. // Uniform Buffer
  24017. this._createUbo();
  24018. // Default Image processing definition.
  24019. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24020. }
  24021. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24022. /** The fog is deactivated */
  24023. get: function () {
  24024. return Scene._FOGMODE_NONE;
  24025. },
  24026. enumerable: true,
  24027. configurable: true
  24028. });
  24029. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24030. /** The fog density is following an exponential function */
  24031. get: function () {
  24032. return Scene._FOGMODE_EXP;
  24033. },
  24034. enumerable: true,
  24035. configurable: true
  24036. });
  24037. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24038. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24039. get: function () {
  24040. return Scene._FOGMODE_EXP2;
  24041. },
  24042. enumerable: true,
  24043. configurable: true
  24044. });
  24045. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24046. /** The fog density is following a linear function. */
  24047. get: function () {
  24048. return Scene._FOGMODE_LINEAR;
  24049. },
  24050. enumerable: true,
  24051. configurable: true
  24052. });
  24053. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24054. /**
  24055. * Texture used in all pbr material as the reflection texture.
  24056. * As in the majority of the scene they are the same (exception for multi room and so on),
  24057. * this is easier to reference from here than from all the materials.
  24058. */
  24059. get: function () {
  24060. return this._environmentTexture;
  24061. },
  24062. /**
  24063. * Texture used in all pbr material as the reflection texture.
  24064. * As in the majority of the scene they are the same (exception for multi room and so on),
  24065. * this is easier to set here than in all the materials.
  24066. */
  24067. set: function (value) {
  24068. if (this._environmentTexture === value) {
  24069. return;
  24070. }
  24071. this._environmentTexture = value;
  24072. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24073. },
  24074. enumerable: true,
  24075. configurable: true
  24076. });
  24077. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24078. /**
  24079. * Default image processing configuration used either in the rendering
  24080. * Forward main pass or through the imageProcessingPostProcess if present.
  24081. * As in the majority of the scene they are the same (exception for multi camera),
  24082. * this is easier to reference from here than from all the materials and post process.
  24083. *
  24084. * No setter as we it is a shared configuration, you can set the values instead.
  24085. */
  24086. get: function () {
  24087. return this._imageProcessingConfiguration;
  24088. },
  24089. enumerable: true,
  24090. configurable: true
  24091. });
  24092. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24093. get: function () {
  24094. return this._forceWireframe;
  24095. },
  24096. /**
  24097. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24098. */
  24099. set: function (value) {
  24100. if (this._forceWireframe === value) {
  24101. return;
  24102. }
  24103. this._forceWireframe = value;
  24104. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24105. },
  24106. enumerable: true,
  24107. configurable: true
  24108. });
  24109. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24110. get: function () {
  24111. return this._forcePointsCloud;
  24112. },
  24113. /**
  24114. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24115. */
  24116. set: function (value) {
  24117. if (this._forcePointsCloud === value) {
  24118. return;
  24119. }
  24120. this._forcePointsCloud = value;
  24121. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24122. },
  24123. enumerable: true,
  24124. configurable: true
  24125. });
  24126. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24127. /**
  24128. * Gets or sets the animation properties override
  24129. */
  24130. get: function () {
  24131. return this._animationPropertiesOverride;
  24132. },
  24133. set: function (value) {
  24134. this._animationPropertiesOverride = value;
  24135. },
  24136. enumerable: true,
  24137. configurable: true
  24138. });
  24139. Object.defineProperty(Scene.prototype, "onDispose", {
  24140. /** Sets a function to be executed when this scene is disposed. */
  24141. set: function (callback) {
  24142. if (this._onDisposeObserver) {
  24143. this.onDisposeObservable.remove(this._onDisposeObserver);
  24144. }
  24145. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24146. },
  24147. enumerable: true,
  24148. configurable: true
  24149. });
  24150. Object.defineProperty(Scene.prototype, "beforeRender", {
  24151. /** Sets a function to be executed before rendering this scene */
  24152. set: function (callback) {
  24153. if (this._onBeforeRenderObserver) {
  24154. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24155. }
  24156. if (callback) {
  24157. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24158. }
  24159. },
  24160. enumerable: true,
  24161. configurable: true
  24162. });
  24163. Object.defineProperty(Scene.prototype, "afterRender", {
  24164. /** Sets a function to be executed after rendering this scene */
  24165. set: function (callback) {
  24166. if (this._onAfterRenderObserver) {
  24167. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24168. }
  24169. if (callback) {
  24170. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24171. }
  24172. },
  24173. enumerable: true,
  24174. configurable: true
  24175. });
  24176. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24177. /** Sets a function to be executed before rendering a camera*/
  24178. set: function (callback) {
  24179. if (this._onBeforeCameraRenderObserver) {
  24180. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24181. }
  24182. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24183. },
  24184. enumerable: true,
  24185. configurable: true
  24186. });
  24187. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24188. /** Sets a function to be executed after rendering a camera*/
  24189. set: function (callback) {
  24190. if (this._onAfterCameraRenderObserver) {
  24191. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24192. }
  24193. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24194. },
  24195. enumerable: true,
  24196. configurable: true
  24197. });
  24198. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24199. /**
  24200. * Gets the gamepad manager associated with the scene
  24201. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24202. */
  24203. get: function () {
  24204. if (!this._gamepadManager) {
  24205. this._gamepadManager = new BABYLON.GamepadManager(this);
  24206. }
  24207. return this._gamepadManager;
  24208. },
  24209. enumerable: true,
  24210. configurable: true
  24211. });
  24212. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24213. /**
  24214. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24215. */
  24216. get: function () {
  24217. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24218. },
  24219. enumerable: true,
  24220. configurable: true
  24221. });
  24222. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24223. get: function () {
  24224. return this._useRightHandedSystem;
  24225. },
  24226. /**
  24227. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24228. */
  24229. set: function (value) {
  24230. if (this._useRightHandedSystem === value) {
  24231. return;
  24232. }
  24233. this._useRightHandedSystem = value;
  24234. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24235. },
  24236. enumerable: true,
  24237. configurable: true
  24238. });
  24239. /**
  24240. * Sets the step Id used by deterministic lock step
  24241. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24242. * @param newStepId defines the step Id
  24243. */
  24244. Scene.prototype.setStepId = function (newStepId) {
  24245. this._currentStepId = newStepId;
  24246. };
  24247. ;
  24248. /**
  24249. * Gets the step Id used by deterministic lock step
  24250. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24251. * @returns the step Id
  24252. */
  24253. Scene.prototype.getStepId = function () {
  24254. return this._currentStepId;
  24255. };
  24256. ;
  24257. /**
  24258. * Gets the internal step used by deterministic lock step
  24259. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24260. * @returns the internal step
  24261. */
  24262. Scene.prototype.getInternalStep = function () {
  24263. return this._currentInternalStep;
  24264. };
  24265. ;
  24266. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24267. get: function () {
  24268. return this._fogEnabled;
  24269. },
  24270. /**
  24271. * Gets or sets a boolean indicating if fog is enabled on this scene
  24272. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24273. */
  24274. set: function (value) {
  24275. if (this._fogEnabled === value) {
  24276. return;
  24277. }
  24278. this._fogEnabled = value;
  24279. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24280. },
  24281. enumerable: true,
  24282. configurable: true
  24283. });
  24284. Object.defineProperty(Scene.prototype, "fogMode", {
  24285. get: function () {
  24286. return this._fogMode;
  24287. },
  24288. /**
  24289. * Gets or sets the fog mode to use
  24290. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24291. */
  24292. set: function (value) {
  24293. if (this._fogMode === value) {
  24294. return;
  24295. }
  24296. this._fogMode = value;
  24297. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24298. },
  24299. enumerable: true,
  24300. configurable: true
  24301. });
  24302. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24303. get: function () {
  24304. return this._shadowsEnabled;
  24305. },
  24306. /**
  24307. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24308. */
  24309. set: function (value) {
  24310. if (this._shadowsEnabled === value) {
  24311. return;
  24312. }
  24313. this._shadowsEnabled = value;
  24314. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24315. },
  24316. enumerable: true,
  24317. configurable: true
  24318. });
  24319. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24320. get: function () {
  24321. return this._lightsEnabled;
  24322. },
  24323. /**
  24324. * Gets or sets a boolean indicating if lights are enabled on this scene
  24325. */
  24326. set: function (value) {
  24327. if (this._lightsEnabled === value) {
  24328. return;
  24329. }
  24330. this._lightsEnabled = value;
  24331. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24332. },
  24333. enumerable: true,
  24334. configurable: true
  24335. });
  24336. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24337. /** The default material used on meshes when no material is affected */
  24338. get: function () {
  24339. if (!this._defaultMaterial) {
  24340. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24341. }
  24342. return this._defaultMaterial;
  24343. },
  24344. /** The default material used on meshes when no material is affected */
  24345. set: function (value) {
  24346. this._defaultMaterial = value;
  24347. },
  24348. enumerable: true,
  24349. configurable: true
  24350. });
  24351. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24352. get: function () {
  24353. return this._texturesEnabled;
  24354. },
  24355. /**
  24356. * Gets or sets a boolean indicating if textures are enabled on this scene
  24357. */
  24358. set: function (value) {
  24359. if (this._texturesEnabled === value) {
  24360. return;
  24361. }
  24362. this._texturesEnabled = value;
  24363. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24364. },
  24365. enumerable: true,
  24366. configurable: true
  24367. });
  24368. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24369. get: function () {
  24370. return this._skeletonsEnabled;
  24371. },
  24372. /**
  24373. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24374. */
  24375. set: function (value) {
  24376. if (this._skeletonsEnabled === value) {
  24377. return;
  24378. }
  24379. this._skeletonsEnabled = value;
  24380. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24381. },
  24382. enumerable: true,
  24383. configurable: true
  24384. });
  24385. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24386. /**
  24387. * Gets the postprocess render pipeline manager
  24388. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24389. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24390. */
  24391. get: function () {
  24392. if (!this._postProcessRenderPipelineManager) {
  24393. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24394. }
  24395. return this._postProcessRenderPipelineManager;
  24396. },
  24397. enumerable: true,
  24398. configurable: true
  24399. });
  24400. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24401. /**
  24402. * Gets the main soundtrack associated with the scene
  24403. */
  24404. get: function () {
  24405. if (!this._mainSoundTrack) {
  24406. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24407. }
  24408. return this._mainSoundTrack;
  24409. },
  24410. enumerable: true,
  24411. configurable: true
  24412. });
  24413. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24414. /** @hidden */
  24415. get: function () {
  24416. return this._alternateRendering;
  24417. },
  24418. enumerable: true,
  24419. configurable: true
  24420. });
  24421. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24422. /**
  24423. * Gets the list of frustum planes (built from the active camera)
  24424. */
  24425. get: function () {
  24426. return this._frustumPlanes;
  24427. },
  24428. enumerable: true,
  24429. configurable: true
  24430. });
  24431. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24432. /**
  24433. * Gets the current geometry buffer associated to the scene.
  24434. */
  24435. get: function () {
  24436. return this._geometryBufferRenderer;
  24437. },
  24438. /**
  24439. * Sets the current geometry buffer for the scene.
  24440. */
  24441. set: function (geometryBufferRenderer) {
  24442. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24443. this._geometryBufferRenderer = geometryBufferRenderer;
  24444. }
  24445. },
  24446. enumerable: true,
  24447. configurable: true
  24448. });
  24449. Object.defineProperty(Scene.prototype, "debugLayer", {
  24450. /**
  24451. * Gets the debug layer associated with the scene
  24452. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24453. */
  24454. get: function () {
  24455. if (!this._debugLayer) {
  24456. this._debugLayer = new BABYLON.DebugLayer(this);
  24457. }
  24458. return this._debugLayer;
  24459. },
  24460. enumerable: true,
  24461. configurable: true
  24462. });
  24463. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24464. /**
  24465. * Gets a boolean indicating if collisions are processed on a web worker
  24466. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24467. */
  24468. get: function () {
  24469. return this._workerCollisions;
  24470. },
  24471. set: function (enabled) {
  24472. if (!BABYLON.CollisionCoordinatorLegacy) {
  24473. return;
  24474. }
  24475. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24476. this._workerCollisions = enabled;
  24477. if (this.collisionCoordinator) {
  24478. this.collisionCoordinator.destroy();
  24479. }
  24480. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24481. this.collisionCoordinator.init(this);
  24482. },
  24483. enumerable: true,
  24484. configurable: true
  24485. });
  24486. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24487. /**
  24488. * Gets the octree used to boost mesh selection (picking)
  24489. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24490. */
  24491. get: function () {
  24492. return this._selectionOctree;
  24493. },
  24494. enumerable: true,
  24495. configurable: true
  24496. });
  24497. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24498. /**
  24499. * Gets the mesh that is currently under the pointer
  24500. */
  24501. get: function () {
  24502. return this._pointerOverMesh;
  24503. },
  24504. enumerable: true,
  24505. configurable: true
  24506. });
  24507. Object.defineProperty(Scene.prototype, "pointerX", {
  24508. /**
  24509. * Gets the current on-screen X position of the pointer
  24510. */
  24511. get: function () {
  24512. return this._pointerX;
  24513. },
  24514. enumerable: true,
  24515. configurable: true
  24516. });
  24517. Object.defineProperty(Scene.prototype, "pointerY", {
  24518. /**
  24519. * Gets the current on-screen Y position of the pointer
  24520. */
  24521. get: function () {
  24522. return this._pointerY;
  24523. },
  24524. enumerable: true,
  24525. configurable: true
  24526. });
  24527. /**
  24528. * Gets the cached material (ie. the latest rendered one)
  24529. * @returns the cached material
  24530. */
  24531. Scene.prototype.getCachedMaterial = function () {
  24532. return this._cachedMaterial;
  24533. };
  24534. /**
  24535. * Gets the cached effect (ie. the latest rendered one)
  24536. * @returns the cached effect
  24537. */
  24538. Scene.prototype.getCachedEffect = function () {
  24539. return this._cachedEffect;
  24540. };
  24541. /**
  24542. * Gets the cached visibility state (ie. the latest rendered one)
  24543. * @returns the cached visibility state
  24544. */
  24545. Scene.prototype.getCachedVisibility = function () {
  24546. return this._cachedVisibility;
  24547. };
  24548. /**
  24549. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24550. * @param material defines the current material
  24551. * @param effect defines the current effect
  24552. * @param visibility defines the current visibility state
  24553. * @returns true if one parameter is not cached
  24554. */
  24555. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24556. if (visibility === void 0) { visibility = 1; }
  24557. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24558. };
  24559. /**
  24560. * Gets the bounding box renderer associated with the scene
  24561. * @returns a BoundingBoxRenderer
  24562. */
  24563. Scene.prototype.getBoundingBoxRenderer = function () {
  24564. if (!this._boundingBoxRenderer) {
  24565. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24566. }
  24567. return this._boundingBoxRenderer;
  24568. };
  24569. /**
  24570. * Gets the outline renderer associated with the scene
  24571. * @returns a OutlineRenderer
  24572. */
  24573. Scene.prototype.getOutlineRenderer = function () {
  24574. return this._outlineRenderer;
  24575. };
  24576. /**
  24577. * Gets the engine associated with the scene
  24578. * @returns an Engine
  24579. */
  24580. Scene.prototype.getEngine = function () {
  24581. return this._engine;
  24582. };
  24583. /**
  24584. * Gets the total number of vertices rendered per frame
  24585. * @returns the total number of vertices rendered per frame
  24586. */
  24587. Scene.prototype.getTotalVertices = function () {
  24588. return this._totalVertices.current;
  24589. };
  24590. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24591. /**
  24592. * Gets the performance counter for total vertices
  24593. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24594. */
  24595. get: function () {
  24596. return this._totalVertices;
  24597. },
  24598. enumerable: true,
  24599. configurable: true
  24600. });
  24601. /**
  24602. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24603. * @returns the total number of active indices rendered per frame
  24604. */
  24605. Scene.prototype.getActiveIndices = function () {
  24606. return this._activeIndices.current;
  24607. };
  24608. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24609. /**
  24610. * Gets the performance counter for active indices
  24611. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24612. */
  24613. get: function () {
  24614. return this._activeIndices;
  24615. },
  24616. enumerable: true,
  24617. configurable: true
  24618. });
  24619. /**
  24620. * Gets the total number of active particles rendered per frame
  24621. * @returns the total number of active particles rendered per frame
  24622. */
  24623. Scene.prototype.getActiveParticles = function () {
  24624. return this._activeParticles.current;
  24625. };
  24626. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24627. /**
  24628. * Gets the performance counter for active particles
  24629. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24630. */
  24631. get: function () {
  24632. return this._activeParticles;
  24633. },
  24634. enumerable: true,
  24635. configurable: true
  24636. });
  24637. /**
  24638. * Gets the total number of active bones rendered per frame
  24639. * @returns the total number of active bones rendered per frame
  24640. */
  24641. Scene.prototype.getActiveBones = function () {
  24642. return this._activeBones.current;
  24643. };
  24644. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24645. /**
  24646. * Gets the performance counter for active bones
  24647. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24648. */
  24649. get: function () {
  24650. return this._activeBones;
  24651. },
  24652. enumerable: true,
  24653. configurable: true
  24654. });
  24655. /** @hidden */
  24656. Scene.prototype.getInterFramePerfCounter = function () {
  24657. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24658. return 0;
  24659. };
  24660. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24661. /** @hidden */
  24662. get: function () {
  24663. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24664. return null;
  24665. },
  24666. enumerable: true,
  24667. configurable: true
  24668. });
  24669. /** @hidden */
  24670. Scene.prototype.getLastFrameDuration = function () {
  24671. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24672. return 0;
  24673. };
  24674. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24675. /** @hidden */
  24676. get: function () {
  24677. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24678. return null;
  24679. },
  24680. enumerable: true,
  24681. configurable: true
  24682. });
  24683. /** @hidden */
  24684. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24685. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24686. return 0;
  24687. };
  24688. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24689. /** @hidden */
  24690. get: function () {
  24691. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24692. return null;
  24693. },
  24694. enumerable: true,
  24695. configurable: true
  24696. });
  24697. /**
  24698. * Gets the array of active meshes
  24699. * @returns an array of AbstractMesh
  24700. */
  24701. Scene.prototype.getActiveMeshes = function () {
  24702. return this._activeMeshes;
  24703. };
  24704. /** @hidden */
  24705. Scene.prototype.getRenderTargetsDuration = function () {
  24706. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24707. return 0;
  24708. };
  24709. /** @hidden */
  24710. Scene.prototype.getRenderDuration = function () {
  24711. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24712. return 0;
  24713. };
  24714. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24715. /** @hidden */
  24716. get: function () {
  24717. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24718. return null;
  24719. },
  24720. enumerable: true,
  24721. configurable: true
  24722. });
  24723. /** @hidden */
  24724. Scene.prototype.getParticlesDuration = function () {
  24725. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24726. return 0;
  24727. };
  24728. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24729. /** @hidden */
  24730. get: function () {
  24731. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24732. return null;
  24733. },
  24734. enumerable: true,
  24735. configurable: true
  24736. });
  24737. /** @hidden */
  24738. Scene.prototype.getSpritesDuration = function () {
  24739. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24740. return 0;
  24741. };
  24742. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24743. /** @hidden */
  24744. get: function () {
  24745. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24746. return null;
  24747. },
  24748. enumerable: true,
  24749. configurable: true
  24750. });
  24751. /**
  24752. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24753. * @returns a number
  24754. */
  24755. Scene.prototype.getAnimationRatio = function () {
  24756. return this._animationRatio;
  24757. };
  24758. /**
  24759. * Gets an unique Id for the current frame
  24760. * @returns a number
  24761. */
  24762. Scene.prototype.getRenderId = function () {
  24763. return this._renderId;
  24764. };
  24765. /** Call this function if you want to manually increment the render Id*/
  24766. Scene.prototype.incrementRenderId = function () {
  24767. this._renderId++;
  24768. };
  24769. Scene.prototype._updatePointerPosition = function (evt) {
  24770. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24771. if (!canvasRect) {
  24772. return;
  24773. }
  24774. this._pointerX = evt.clientX - canvasRect.left;
  24775. this._pointerY = evt.clientY - canvasRect.top;
  24776. this._unTranslatedPointerX = this._pointerX;
  24777. this._unTranslatedPointerY = this._pointerY;
  24778. };
  24779. Scene.prototype._createUbo = function () {
  24780. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24781. this._sceneUbo.addUniform("viewProjection", 16);
  24782. this._sceneUbo.addUniform("view", 16);
  24783. };
  24784. Scene.prototype._createAlternateUbo = function () {
  24785. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24786. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24787. this._alternateSceneUbo.addUniform("view", 16);
  24788. };
  24789. // Pointers handling
  24790. /**
  24791. * Use this method to simulate a pointer move on a mesh
  24792. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24793. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24794. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24795. * @returns the current scene
  24796. */
  24797. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24798. var evt = new PointerEvent("pointermove", pointerEventInit);
  24799. return this._processPointerMove(pickResult, evt);
  24800. };
  24801. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24802. var canvas = this._engine.getRenderingCanvas();
  24803. if (!canvas) {
  24804. return this;
  24805. }
  24806. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24807. this.setPointerOverSprite(null);
  24808. this.setPointerOverMesh(pickResult.pickedMesh);
  24809. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24810. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24811. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24812. }
  24813. else {
  24814. canvas.style.cursor = this.hoverCursor;
  24815. }
  24816. }
  24817. else {
  24818. canvas.style.cursor = this.defaultCursor;
  24819. }
  24820. }
  24821. else {
  24822. this.setPointerOverMesh(null);
  24823. // Sprites
  24824. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24825. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24826. this.setPointerOverSprite(pickResult.pickedSprite);
  24827. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24828. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24829. }
  24830. else {
  24831. canvas.style.cursor = this.hoverCursor;
  24832. }
  24833. }
  24834. else {
  24835. this.setPointerOverSprite(null);
  24836. // Restore pointer
  24837. canvas.style.cursor = this.defaultCursor;
  24838. }
  24839. }
  24840. if (pickResult) {
  24841. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24842. if (this.onPointerMove) {
  24843. this.onPointerMove(evt, pickResult, type);
  24844. }
  24845. if (this.onPointerObservable.hasObservers()) {
  24846. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24847. this.onPointerObservable.notifyObservers(pi, type);
  24848. }
  24849. }
  24850. return this;
  24851. };
  24852. /**
  24853. * Use this method to simulate a pointer down on a mesh
  24854. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24855. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24856. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24857. * @returns the current scene
  24858. */
  24859. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24860. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24861. return this._processPointerDown(pickResult, evt);
  24862. };
  24863. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24864. var _this = this;
  24865. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24866. this._pickedDownMesh = pickResult.pickedMesh;
  24867. var actionManager = pickResult.pickedMesh.actionManager;
  24868. if (actionManager) {
  24869. if (actionManager.hasPickTriggers) {
  24870. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24871. switch (evt.button) {
  24872. case 0:
  24873. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24874. break;
  24875. case 1:
  24876. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24877. break;
  24878. case 2:
  24879. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24880. break;
  24881. }
  24882. }
  24883. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24884. window.setTimeout(function () {
  24885. 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);
  24886. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24887. if (_this._totalPointersPressed !== 0 &&
  24888. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24889. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24890. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24891. _this._startingPointerTime = 0;
  24892. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24893. }
  24894. }
  24895. }, Scene.LongPressDelay);
  24896. }
  24897. }
  24898. }
  24899. if (pickResult) {
  24900. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24901. if (this.onPointerDown) {
  24902. this.onPointerDown(evt, pickResult, type);
  24903. }
  24904. if (this.onPointerObservable.hasObservers()) {
  24905. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24906. this.onPointerObservable.notifyObservers(pi, type);
  24907. }
  24908. }
  24909. return this;
  24910. };
  24911. /**
  24912. * Use this method to simulate a pointer up on a mesh
  24913. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24914. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24915. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24916. * @returns the current scene
  24917. */
  24918. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24919. var evt = new PointerEvent("pointerup", pointerEventInit);
  24920. var clickInfo = new ClickInfo();
  24921. clickInfo.singleClick = true;
  24922. clickInfo.ignore = true;
  24923. return this._processPointerUp(pickResult, evt, clickInfo);
  24924. };
  24925. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24926. if (pickResult && pickResult && pickResult.pickedMesh) {
  24927. this._pickedUpMesh = pickResult.pickedMesh;
  24928. if (this._pickedDownMesh === this._pickedUpMesh) {
  24929. if (this.onPointerPick) {
  24930. this.onPointerPick(evt, pickResult);
  24931. }
  24932. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24933. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24934. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24935. this.onPointerObservable.notifyObservers(pi, type_1);
  24936. }
  24937. }
  24938. if (pickResult.pickedMesh.actionManager) {
  24939. if (clickInfo.ignore) {
  24940. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24941. }
  24942. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24943. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24944. }
  24945. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24946. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24947. }
  24948. }
  24949. }
  24950. if (this._pickedDownMesh &&
  24951. this._pickedDownMesh.actionManager &&
  24952. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  24953. this._pickedDownMesh !== this._pickedUpMesh) {
  24954. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  24955. }
  24956. var type = BABYLON.PointerEventTypes.POINTERUP;
  24957. if (this.onPointerObservable.hasObservers()) {
  24958. if (!clickInfo.ignore) {
  24959. if (!clickInfo.hasSwiped) {
  24960. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24961. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  24962. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  24963. this.onPointerObservable.notifyObservers(pi, type_2);
  24964. }
  24965. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24966. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24967. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  24968. this.onPointerObservable.notifyObservers(pi, type_3);
  24969. }
  24970. }
  24971. }
  24972. else {
  24973. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24974. this.onPointerObservable.notifyObservers(pi, type);
  24975. }
  24976. }
  24977. if (this.onPointerUp) {
  24978. this.onPointerUp(evt, pickResult, type);
  24979. }
  24980. return this;
  24981. };
  24982. /**
  24983. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  24984. * @param attachUp defines if you want to attach events to pointerup
  24985. * @param attachDown defines if you want to attach events to pointerdown
  24986. * @param attachMove defines if you want to attach events to pointermove
  24987. */
  24988. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  24989. var _this = this;
  24990. if (attachUp === void 0) { attachUp = true; }
  24991. if (attachDown === void 0) { attachDown = true; }
  24992. if (attachMove === void 0) { attachMove = true; }
  24993. this._initActionManager = function (act, clickInfo) {
  24994. if (!_this._meshPickProceed) {
  24995. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  24996. _this._currentPickResult = pickResult;
  24997. if (pickResult) {
  24998. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  24999. }
  25000. _this._meshPickProceed = true;
  25001. }
  25002. return act;
  25003. };
  25004. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25005. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25006. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25007. btn !== _this._previousButtonPressed) {
  25008. _this._doubleClickOccured = false;
  25009. clickInfo.singleClick = true;
  25010. clickInfo.ignore = false;
  25011. cb(clickInfo, _this._currentPickResult);
  25012. }
  25013. };
  25014. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25015. var clickInfo = new ClickInfo();
  25016. _this._currentPickResult = null;
  25017. var act = null;
  25018. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25019. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25020. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25021. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25022. act = _this._initActionManager(act, clickInfo);
  25023. if (act)
  25024. checkPicking = act.hasPickTriggers;
  25025. }
  25026. if (checkPicking) {
  25027. var btn = evt.button;
  25028. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25029. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25030. if (!clickInfo.hasSwiped) {
  25031. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25032. if (!checkSingleClickImmediately) {
  25033. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25034. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25035. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25036. act = _this._initActionManager(act, clickInfo);
  25037. if (act)
  25038. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25039. }
  25040. }
  25041. if (checkSingleClickImmediately) {
  25042. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25043. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25044. btn !== _this._previousButtonPressed) {
  25045. clickInfo.singleClick = true;
  25046. cb(clickInfo, _this._currentPickResult);
  25047. }
  25048. }
  25049. // at least one double click is required to be check and exclusive double click is enabled
  25050. else {
  25051. // wait that no double click has been raised during the double click delay
  25052. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25053. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25054. }
  25055. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25056. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25057. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25058. act = _this._initActionManager(act, clickInfo);
  25059. if (act)
  25060. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25061. }
  25062. if (checkDoubleClick) {
  25063. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25064. if (btn === _this._previousButtonPressed &&
  25065. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25066. !_this._doubleClickOccured) {
  25067. // pointer has not moved for 2 clicks, it's a double click
  25068. if (!clickInfo.hasSwiped &&
  25069. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25070. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25071. _this._previousStartingPointerTime = 0;
  25072. _this._doubleClickOccured = true;
  25073. clickInfo.doubleClick = true;
  25074. clickInfo.ignore = false;
  25075. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25076. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25077. }
  25078. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25079. cb(clickInfo, _this._currentPickResult);
  25080. }
  25081. // if the two successive clicks are too far, it's just two simple clicks
  25082. else {
  25083. _this._doubleClickOccured = false;
  25084. _this._previousStartingPointerTime = _this._startingPointerTime;
  25085. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25086. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25087. _this._previousButtonPressed = btn;
  25088. if (Scene.ExclusiveDoubleClickMode) {
  25089. if (_this._previousDelayedSimpleClickTimeout) {
  25090. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25091. }
  25092. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25093. cb(clickInfo, _this._previousPickResult);
  25094. }
  25095. else {
  25096. cb(clickInfo, _this._currentPickResult);
  25097. }
  25098. }
  25099. }
  25100. // just the first click of the double has been raised
  25101. else {
  25102. _this._doubleClickOccured = false;
  25103. _this._previousStartingPointerTime = _this._startingPointerTime;
  25104. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25105. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25106. _this._previousButtonPressed = btn;
  25107. }
  25108. }
  25109. }
  25110. }
  25111. clickInfo.ignore = true;
  25112. cb(clickInfo, _this._currentPickResult);
  25113. };
  25114. this._spritePredicate = function (sprite) {
  25115. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25116. };
  25117. this._onPointerMove = function (evt) {
  25118. _this._updatePointerPosition(evt);
  25119. // PreObservable support
  25120. if (_this.onPrePointerObservable.hasObservers()) {
  25121. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25122. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25123. _this.onPrePointerObservable.notifyObservers(pi, type);
  25124. if (pi.skipOnPointerObservable) {
  25125. return;
  25126. }
  25127. }
  25128. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25129. return;
  25130. }
  25131. if (!_this.pointerMovePredicate) {
  25132. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25133. }
  25134. // Meshes
  25135. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25136. _this._processPointerMove(pickResult, evt);
  25137. };
  25138. this._onPointerDown = function (evt) {
  25139. _this._totalPointersPressed++;
  25140. _this._pickedDownMesh = null;
  25141. _this._meshPickProceed = false;
  25142. _this._updatePointerPosition(evt);
  25143. if (_this.preventDefaultOnPointerDown && canvas) {
  25144. evt.preventDefault();
  25145. canvas.focus();
  25146. }
  25147. // PreObservable support
  25148. if (_this.onPrePointerObservable.hasObservers()) {
  25149. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25150. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25151. _this.onPrePointerObservable.notifyObservers(pi, type);
  25152. if (pi.skipOnPointerObservable) {
  25153. return;
  25154. }
  25155. }
  25156. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25157. return;
  25158. }
  25159. _this._startingPointerPosition.x = _this._pointerX;
  25160. _this._startingPointerPosition.y = _this._pointerY;
  25161. _this._startingPointerTime = Date.now();
  25162. if (!_this.pointerDownPredicate) {
  25163. _this.pointerDownPredicate = function (mesh) {
  25164. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25165. };
  25166. }
  25167. // Meshes
  25168. _this._pickedDownMesh = null;
  25169. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25170. _this._processPointerDown(pickResult, evt);
  25171. // Sprites
  25172. _this._pickedDownSprite = null;
  25173. if (_this.spriteManagers.length > 0) {
  25174. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25175. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25176. if (pickResult.pickedSprite.actionManager) {
  25177. _this._pickedDownSprite = pickResult.pickedSprite;
  25178. switch (evt.button) {
  25179. case 0:
  25180. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25181. break;
  25182. case 1:
  25183. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25184. break;
  25185. case 2:
  25186. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25187. break;
  25188. }
  25189. if (pickResult.pickedSprite.actionManager) {
  25190. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25191. }
  25192. }
  25193. }
  25194. }
  25195. };
  25196. this._onPointerUp = function (evt) {
  25197. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25198. return; // So we need to test it the pointer down was pressed before.
  25199. }
  25200. _this._totalPointersPressed--;
  25201. _this._pickedUpMesh = null;
  25202. _this._meshPickProceed = false;
  25203. _this._updatePointerPosition(evt);
  25204. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25205. // PreObservable support
  25206. if (_this.onPrePointerObservable.hasObservers()) {
  25207. if (!clickInfo.ignore) {
  25208. if (!clickInfo.hasSwiped) {
  25209. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25210. var type = BABYLON.PointerEventTypes.POINTERTAP;
  25211. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25212. _this.onPrePointerObservable.notifyObservers(pi, type);
  25213. if (pi.skipOnPointerObservable) {
  25214. return;
  25215. }
  25216. }
  25217. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25218. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25219. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25220. _this.onPrePointerObservable.notifyObservers(pi, type);
  25221. if (pi.skipOnPointerObservable) {
  25222. return;
  25223. }
  25224. }
  25225. }
  25226. }
  25227. else {
  25228. var type = BABYLON.PointerEventTypes.POINTERUP;
  25229. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25230. _this.onPrePointerObservable.notifyObservers(pi, type);
  25231. if (pi.skipOnPointerObservable) {
  25232. return;
  25233. }
  25234. }
  25235. }
  25236. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25237. return;
  25238. }
  25239. if (!_this.pointerUpPredicate) {
  25240. _this.pointerUpPredicate = function (mesh) {
  25241. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25242. };
  25243. }
  25244. // Meshes
  25245. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25246. _this._initActionManager(null, clickInfo);
  25247. }
  25248. if (!pickResult) {
  25249. pickResult = _this._currentPickResult;
  25250. }
  25251. _this._processPointerUp(pickResult, evt, clickInfo);
  25252. // Sprites
  25253. if (!clickInfo.ignore) {
  25254. if (_this.spriteManagers.length > 0) {
  25255. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25256. if (spritePickResult) {
  25257. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25258. if (spritePickResult.pickedSprite.actionManager) {
  25259. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25260. if (spritePickResult.pickedSprite.actionManager) {
  25261. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25262. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25263. }
  25264. }
  25265. }
  25266. }
  25267. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25268. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25269. }
  25270. }
  25271. }
  25272. }
  25273. _this._previousPickResult = _this._currentPickResult;
  25274. });
  25275. };
  25276. this._onKeyDown = function (evt) {
  25277. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25278. if (_this.onPreKeyboardObservable.hasObservers()) {
  25279. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25280. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25281. if (pi.skipOnPointerObservable) {
  25282. return;
  25283. }
  25284. }
  25285. if (_this.onKeyboardObservable.hasObservers()) {
  25286. var pi = new BABYLON.KeyboardInfo(type, evt);
  25287. _this.onKeyboardObservable.notifyObservers(pi, type);
  25288. }
  25289. if (_this.actionManager) {
  25290. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25291. }
  25292. };
  25293. this._onKeyUp = function (evt) {
  25294. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25295. if (_this.onPreKeyboardObservable.hasObservers()) {
  25296. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25297. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25298. if (pi.skipOnPointerObservable) {
  25299. return;
  25300. }
  25301. }
  25302. if (_this.onKeyboardObservable.hasObservers()) {
  25303. var pi = new BABYLON.KeyboardInfo(type, evt);
  25304. _this.onKeyboardObservable.notifyObservers(pi, type);
  25305. }
  25306. if (_this.actionManager) {
  25307. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25308. }
  25309. };
  25310. var engine = this.getEngine();
  25311. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25312. if (!canvas) {
  25313. return;
  25314. }
  25315. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25316. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25317. });
  25318. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25319. if (!canvas) {
  25320. return;
  25321. }
  25322. canvas.removeEventListener("keydown", _this._onKeyDown);
  25323. canvas.removeEventListener("keyup", _this._onKeyUp);
  25324. });
  25325. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25326. var canvas = this._engine.getRenderingCanvas();
  25327. if (!canvas) {
  25328. return;
  25329. }
  25330. if (attachMove) {
  25331. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25332. // Wheel
  25333. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25334. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25335. }
  25336. if (attachDown) {
  25337. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25338. }
  25339. if (attachUp) {
  25340. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25341. }
  25342. canvas.tabIndex = 1;
  25343. };
  25344. /** Detaches all event handlers*/
  25345. Scene.prototype.detachControl = function () {
  25346. var engine = this.getEngine();
  25347. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25348. var canvas = engine.getRenderingCanvas();
  25349. if (!canvas) {
  25350. return;
  25351. }
  25352. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25353. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25354. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25355. if (this._onCanvasBlurObserver) {
  25356. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25357. }
  25358. if (this._onCanvasFocusObserver) {
  25359. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25360. }
  25361. // Wheel
  25362. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25363. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25364. // Keyboard
  25365. canvas.removeEventListener("keydown", this._onKeyDown);
  25366. canvas.removeEventListener("keyup", this._onKeyUp);
  25367. // Observables
  25368. this.onKeyboardObservable.clear();
  25369. this.onPreKeyboardObservable.clear();
  25370. this.onPointerObservable.clear();
  25371. this.onPrePointerObservable.clear();
  25372. };
  25373. /**
  25374. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25375. * Delay loaded resources are not taking in account
  25376. * @return true if all required resources are ready
  25377. */
  25378. Scene.prototype.isReady = function () {
  25379. if (this._isDisposed) {
  25380. return false;
  25381. }
  25382. if (this._pendingData.length > 0) {
  25383. return false;
  25384. }
  25385. var index;
  25386. var engine = this.getEngine();
  25387. // Geometries
  25388. for (index = 0; index < this._geometries.length; index++) {
  25389. var geometry = this._geometries[index];
  25390. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25391. return false;
  25392. }
  25393. }
  25394. // Meshes
  25395. for (index = 0; index < this.meshes.length; index++) {
  25396. var mesh = this.meshes[index];
  25397. if (!mesh.isEnabled()) {
  25398. continue;
  25399. }
  25400. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25401. continue;
  25402. }
  25403. if (!mesh.isReady(true)) {
  25404. return false;
  25405. }
  25406. // Effect layers
  25407. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25408. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25409. var layer = _a[_i];
  25410. if (!layer.hasMesh(mesh)) {
  25411. continue;
  25412. }
  25413. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25414. var subMesh = _c[_b];
  25415. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25416. return false;
  25417. }
  25418. }
  25419. }
  25420. }
  25421. // Post-processes
  25422. if (this.activeCameras && this.activeCameras.length > 0) {
  25423. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25424. var camera = _e[_d];
  25425. if (!camera.isReady(true)) {
  25426. return false;
  25427. }
  25428. }
  25429. }
  25430. else if (this.activeCamera) {
  25431. if (!this.activeCamera.isReady(true)) {
  25432. return false;
  25433. }
  25434. }
  25435. // Particles
  25436. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25437. var particleSystem = _g[_f];
  25438. if (!particleSystem.isReady()) {
  25439. return false;
  25440. }
  25441. }
  25442. return true;
  25443. };
  25444. /** Resets all cached information relative to material (including effect and visibility) */
  25445. Scene.prototype.resetCachedMaterial = function () {
  25446. this._cachedMaterial = null;
  25447. this._cachedEffect = null;
  25448. this._cachedVisibility = null;
  25449. };
  25450. /**
  25451. * Registers a function to be called before every frame render
  25452. * @param func defines the function to register
  25453. */
  25454. Scene.prototype.registerBeforeRender = function (func) {
  25455. this.onBeforeRenderObservable.add(func);
  25456. };
  25457. /**
  25458. * Unregisters a function called before every frame render
  25459. * @param func defines the function to unregister
  25460. */
  25461. Scene.prototype.unregisterBeforeRender = function (func) {
  25462. this.onBeforeRenderObservable.removeCallback(func);
  25463. };
  25464. /**
  25465. * Registers a function to be called after every frame render
  25466. * @param func defines the function to register
  25467. */
  25468. Scene.prototype.registerAfterRender = function (func) {
  25469. this.onAfterRenderObservable.add(func);
  25470. };
  25471. /**
  25472. * Unregisters a function called after every frame render
  25473. * @param func defines the function to unregister
  25474. */
  25475. Scene.prototype.unregisterAfterRender = function (func) {
  25476. this.onAfterRenderObservable.removeCallback(func);
  25477. };
  25478. Scene.prototype._executeOnceBeforeRender = function (func) {
  25479. var _this = this;
  25480. var execFunc = function () {
  25481. func();
  25482. setTimeout(function () {
  25483. _this.unregisterBeforeRender(execFunc);
  25484. });
  25485. };
  25486. this.registerBeforeRender(execFunc);
  25487. };
  25488. /**
  25489. * The provided function will run before render once and will be disposed afterwards.
  25490. * A timeout delay can be provided so that the function will be executed in N ms.
  25491. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25492. * @param func The function to be executed.
  25493. * @param timeout optional delay in ms
  25494. */
  25495. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25496. var _this = this;
  25497. if (timeout !== undefined) {
  25498. setTimeout(function () {
  25499. _this._executeOnceBeforeRender(func);
  25500. }, timeout);
  25501. }
  25502. else {
  25503. this._executeOnceBeforeRender(func);
  25504. }
  25505. };
  25506. /** @hidden */
  25507. Scene.prototype._addPendingData = function (data) {
  25508. this._pendingData.push(data);
  25509. };
  25510. /** @hidden */
  25511. Scene.prototype._removePendingData = function (data) {
  25512. var wasLoading = this.isLoading;
  25513. var index = this._pendingData.indexOf(data);
  25514. if (index !== -1) {
  25515. this._pendingData.splice(index, 1);
  25516. }
  25517. if (wasLoading && !this.isLoading) {
  25518. this.onDataLoadedObservable.notifyObservers(this);
  25519. }
  25520. };
  25521. /**
  25522. * Returns the number of items waiting to be loaded
  25523. * @returns the number of items waiting to be loaded
  25524. */
  25525. Scene.prototype.getWaitingItemsCount = function () {
  25526. return this._pendingData.length;
  25527. };
  25528. Object.defineProperty(Scene.prototype, "isLoading", {
  25529. /**
  25530. * Returns a boolean indicating if the scene is still loading data
  25531. */
  25532. get: function () {
  25533. return this._pendingData.length > 0;
  25534. },
  25535. enumerable: true,
  25536. configurable: true
  25537. });
  25538. /**
  25539. * Registers a function to be executed when the scene is ready
  25540. * @param {Function} func - the function to be executed
  25541. */
  25542. Scene.prototype.executeWhenReady = function (func) {
  25543. var _this = this;
  25544. this.onReadyObservable.add(func);
  25545. if (this._executeWhenReadyTimeoutId !== -1) {
  25546. return;
  25547. }
  25548. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25549. _this._checkIsReady();
  25550. }, 150);
  25551. };
  25552. /**
  25553. * Returns a promise that resolves when the scene is ready
  25554. * @returns A promise that resolves when the scene is ready
  25555. */
  25556. Scene.prototype.whenReadyAsync = function () {
  25557. var _this = this;
  25558. return new Promise(function (resolve) {
  25559. _this.executeWhenReady(function () {
  25560. resolve();
  25561. });
  25562. });
  25563. };
  25564. /** @hidden */
  25565. Scene.prototype._checkIsReady = function () {
  25566. var _this = this;
  25567. if (this.isReady()) {
  25568. this.onReadyObservable.notifyObservers(this);
  25569. this.onReadyObservable.clear();
  25570. this._executeWhenReadyTimeoutId = -1;
  25571. return;
  25572. }
  25573. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25574. _this._checkIsReady();
  25575. }, 150);
  25576. };
  25577. // Animations
  25578. /**
  25579. * Will start the animation sequence of a given target
  25580. * @param target defines the target
  25581. * @param from defines from which frame should animation start
  25582. * @param to defines until which frame should animation run.
  25583. * @param weight defines the weight to apply to the animation (1.0 by default)
  25584. * @param loop defines if the animation loops
  25585. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25586. * @param onAnimationEnd defines the function to be executed when the animation ends
  25587. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25588. * @returns the animatable object created for this animation
  25589. */
  25590. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25591. if (weight === void 0) { weight = 1.0; }
  25592. if (speedRatio === void 0) { speedRatio = 1.0; }
  25593. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25594. returnedAnimatable.weight = weight;
  25595. return returnedAnimatable;
  25596. };
  25597. /**
  25598. * Will start the animation sequence of a given target
  25599. * @param target defines the target
  25600. * @param from defines from which frame should animation start
  25601. * @param to defines until which frame should animation run.
  25602. * @param loop defines if the animation loops
  25603. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25604. * @param onAnimationEnd defines the function to be executed when the animation ends
  25605. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25606. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25607. * @returns the animatable object created for this animation
  25608. */
  25609. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25610. if (speedRatio === void 0) { speedRatio = 1.0; }
  25611. if (stopCurrent === void 0) { stopCurrent = true; }
  25612. if (from > to && speedRatio > 0) {
  25613. speedRatio *= -1;
  25614. }
  25615. if (stopCurrent) {
  25616. this.stopAnimation(target);
  25617. }
  25618. if (!animatable) {
  25619. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25620. }
  25621. // Local animations
  25622. if (target.animations) {
  25623. animatable.appendAnimations(target, target.animations);
  25624. }
  25625. // Children animations
  25626. if (target.getAnimatables) {
  25627. var animatables = target.getAnimatables();
  25628. for (var index = 0; index < animatables.length; index++) {
  25629. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25630. }
  25631. }
  25632. animatable.reset();
  25633. return animatable;
  25634. };
  25635. /**
  25636. * Begin a new animation on a given node
  25637. * @param target defines the target where the animation will take place
  25638. * @param animations defines the list of animations to start
  25639. * @param from defines the initial value
  25640. * @param to defines the final value
  25641. * @param loop defines if you want animation to loop (off by default)
  25642. * @param speedRatio defines the speed ratio to apply to all animations
  25643. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25644. * @returns the list of created animatables
  25645. */
  25646. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25647. if (speedRatio === undefined) {
  25648. speedRatio = 1.0;
  25649. }
  25650. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25651. return animatable;
  25652. };
  25653. /**
  25654. * Begin a new animation on a given node and its hierarchy
  25655. * @param target defines the root node where the animation will take place
  25656. * @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.
  25657. * @param animations defines the list of animations to start
  25658. * @param from defines the initial value
  25659. * @param to defines the final value
  25660. * @param loop defines if you want animation to loop (off by default)
  25661. * @param speedRatio defines the speed ratio to apply to all animations
  25662. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25663. * @returns the list of animatables created for all nodes
  25664. */
  25665. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25666. var children = target.getDescendants(directDescendantsOnly);
  25667. var result = [];
  25668. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25669. var child = children_1[_i];
  25670. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25671. }
  25672. return result;
  25673. };
  25674. /**
  25675. * Gets the animatable associated with a specific target
  25676. * @param target defines the target of the animatable
  25677. * @returns the required animatable if found
  25678. */
  25679. Scene.prototype.getAnimatableByTarget = function (target) {
  25680. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25681. if (this._activeAnimatables[index].target === target) {
  25682. return this._activeAnimatables[index];
  25683. }
  25684. }
  25685. return null;
  25686. };
  25687. /**
  25688. * Gets all animatables associated with a given target
  25689. * @param target defines the target to look animatables for
  25690. * @returns an array of Animatables
  25691. */
  25692. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25693. var result = [];
  25694. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25695. if (this._activeAnimatables[index].target === target) {
  25696. result.push(this._activeAnimatables[index]);
  25697. }
  25698. }
  25699. return result;
  25700. };
  25701. Object.defineProperty(Scene.prototype, "animatables", {
  25702. /**
  25703. * Gets all animatable attached to the scene
  25704. */
  25705. get: function () {
  25706. return this._activeAnimatables;
  25707. },
  25708. enumerable: true,
  25709. configurable: true
  25710. });
  25711. /**
  25712. * Will stop the animation of the given target
  25713. * @param target - the target
  25714. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25715. */
  25716. Scene.prototype.stopAnimation = function (target, animationName) {
  25717. var animatables = this.getAllAnimatablesByTarget(target);
  25718. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25719. var animatable = animatables_1[_i];
  25720. animatable.stop(animationName);
  25721. }
  25722. };
  25723. /**
  25724. * Stops and removes all animations that have been applied to the scene
  25725. */
  25726. Scene.prototype.stopAllAnimations = function () {
  25727. if (this._activeAnimatables) {
  25728. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25729. this._activeAnimatables[i].stop();
  25730. }
  25731. this._activeAnimatables = [];
  25732. }
  25733. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25734. var group = _a[_i];
  25735. group.stop();
  25736. }
  25737. };
  25738. Scene.prototype._animate = function () {
  25739. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25740. return;
  25741. }
  25742. // Getting time
  25743. var now = BABYLON.Tools.Now;
  25744. if (!this._animationTimeLast) {
  25745. if (this._pendingData.length > 0) {
  25746. return;
  25747. }
  25748. this._animationTimeLast = now;
  25749. }
  25750. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25751. this._animationTime += deltaTime;
  25752. this._animationTimeLast = now;
  25753. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25754. this._activeAnimatables[index]._animate(this._animationTime);
  25755. }
  25756. // Late animation bindings
  25757. this._processLateAnimationBindings();
  25758. };
  25759. /** @hidden */
  25760. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  25761. var target = runtimeAnimation.target;
  25762. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25763. if (!target._lateAnimationHolders) {
  25764. target._lateAnimationHolders = {};
  25765. }
  25766. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25767. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25768. totalWeight: 0,
  25769. animations: []
  25770. };
  25771. }
  25772. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25773. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25774. };
  25775. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder, originalValue) {
  25776. var normalizer = 1.0;
  25777. var finalPosition = BABYLON.Tmp.Vector3[0];
  25778. var finalScaling = BABYLON.Tmp.Vector3[1];
  25779. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25780. var startIndex = 0;
  25781. var originalAnimation = holder.animations[0];
  25782. var scale = 1;
  25783. if (holder.totalWeight < 1.0) {
  25784. // We need to mix the original value in
  25785. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25786. scale = 1.0 - holder.totalWeight;
  25787. }
  25788. else {
  25789. startIndex = 1;
  25790. // We need to normalize the weights
  25791. normalizer = holder.totalWeight;
  25792. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25793. scale = originalAnimation.weight / normalizer;
  25794. if (scale == 1) {
  25795. return originalAnimation.currentValue;
  25796. }
  25797. }
  25798. finalScaling.scaleInPlace(scale);
  25799. finalPosition.scaleInPlace(scale);
  25800. finalQuaternion.scaleInPlace(scale);
  25801. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25802. var runtimeAnimation = holder.animations[animIndex];
  25803. var scale = runtimeAnimation.weight / normalizer;
  25804. var currentPosition = BABYLON.Tmp.Vector3[2];
  25805. var currentScaling = BABYLON.Tmp.Vector3[3];
  25806. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25807. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25808. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25809. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25810. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25811. }
  25812. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25813. return originalAnimation._workValue;
  25814. };
  25815. Scene.prototype._processLateAnimationBindings = function () {
  25816. if (!this._registeredForLateAnimationBindings.length) {
  25817. return;
  25818. }
  25819. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25820. var target = this._registeredForLateAnimationBindings.data[index];
  25821. for (var path in target._lateAnimationHolders) {
  25822. var holder = target._lateAnimationHolders[path];
  25823. var originalAnimation = holder.animations[0];
  25824. var originalValue = originalAnimation.originalValue;
  25825. var finalTarget = originalAnimation.target;
  25826. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25827. var finalValue = void 0;
  25828. if (matrixDecomposeMode) {
  25829. finalValue = this._processLateAnimationBindingsForMatrices(holder, originalValue);
  25830. }
  25831. else {
  25832. var startIndex = 0;
  25833. var normalizer = 1.0;
  25834. if (holder.totalWeight < 1.0) {
  25835. // We need to mix the original value in
  25836. if (originalValue.scale) {
  25837. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25838. }
  25839. else {
  25840. finalValue = originalValue * (1.0 - holder.totalWeight);
  25841. }
  25842. }
  25843. else {
  25844. // We need to normalize the weights
  25845. normalizer = holder.totalWeight;
  25846. var scale_1 = originalAnimation.weight / normalizer;
  25847. if (scale_1 !== 1) {
  25848. if (originalAnimation.currentValue.scale) {
  25849. finalValue = originalAnimation.currentValue.scale(scale_1);
  25850. }
  25851. else {
  25852. finalValue = originalAnimation.currentValue * scale_1;
  25853. }
  25854. }
  25855. else {
  25856. finalValue = originalAnimation.currentValue;
  25857. }
  25858. startIndex = 1;
  25859. }
  25860. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25861. var runtimeAnimation = holder.animations[animIndex];
  25862. var scale = runtimeAnimation.weight / normalizer;
  25863. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25864. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25865. }
  25866. else {
  25867. finalValue += runtimeAnimation.currentValue * scale;
  25868. }
  25869. }
  25870. }
  25871. finalTarget[path] = finalValue;
  25872. }
  25873. target._lateAnimationHolders = {};
  25874. }
  25875. this._registeredForLateAnimationBindings.reset();
  25876. };
  25877. // Matrix
  25878. /** @hidden */
  25879. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25880. this._useAlternateCameraConfiguration = active;
  25881. };
  25882. /**
  25883. * Gets the current view matrix
  25884. * @returns a Matrix
  25885. */
  25886. Scene.prototype.getViewMatrix = function () {
  25887. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25888. };
  25889. /**
  25890. * Gets the current projection matrix
  25891. * @returns a Matrix
  25892. */
  25893. Scene.prototype.getProjectionMatrix = function () {
  25894. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25895. };
  25896. /**
  25897. * Gets the current transform matrix
  25898. * @returns a Matrix made of View * Projection
  25899. */
  25900. Scene.prototype.getTransformMatrix = function () {
  25901. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  25902. };
  25903. /**
  25904. * Sets the current transform matrix
  25905. * @param view defines the View matrix to use
  25906. * @param projection defines the Projection matrix to use
  25907. */
  25908. Scene.prototype.setTransformMatrix = function (view, projection) {
  25909. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  25910. return;
  25911. }
  25912. this._viewUpdateFlag = view.updateFlag;
  25913. this._projectionUpdateFlag = projection.updateFlag;
  25914. this._viewMatrix = view;
  25915. this._projectionMatrix = projection;
  25916. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  25917. // Update frustum
  25918. if (!this._frustumPlanes) {
  25919. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  25920. }
  25921. else {
  25922. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  25923. }
  25924. if (this.activeCamera && this.activeCamera._alternateCamera) {
  25925. var otherCamera = this.activeCamera._alternateCamera;
  25926. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  25927. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  25928. }
  25929. if (this._sceneUbo.useUbo) {
  25930. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  25931. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  25932. this._sceneUbo.update();
  25933. }
  25934. };
  25935. /** @hidden */
  25936. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  25937. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  25938. return;
  25939. }
  25940. this._alternateViewUpdateFlag = view.updateFlag;
  25941. this._alternateProjectionUpdateFlag = projection.updateFlag;
  25942. this._alternateViewMatrix = view;
  25943. this._alternateProjectionMatrix = projection;
  25944. if (!this._alternateTransformMatrix) {
  25945. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  25946. }
  25947. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  25948. if (!this._alternateSceneUbo) {
  25949. this._createAlternateUbo();
  25950. }
  25951. if (this._alternateSceneUbo.useUbo) {
  25952. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  25953. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  25954. this._alternateSceneUbo.update();
  25955. }
  25956. };
  25957. /**
  25958. * Gets the uniform buffer used to store scene data
  25959. * @returns a UniformBuffer
  25960. */
  25961. Scene.prototype.getSceneUniformBuffer = function () {
  25962. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  25963. };
  25964. /**
  25965. * Gets an unique (relatively to the current scene) Id
  25966. * @returns an unique number for the scene
  25967. */
  25968. Scene.prototype.getUniqueId = function () {
  25969. var result = Scene._uniqueIdCounter;
  25970. Scene._uniqueIdCounter++;
  25971. return result;
  25972. };
  25973. /**
  25974. * Add a mesh to the list of scene's meshes
  25975. * @param newMesh defines the mesh to add
  25976. */
  25977. Scene.prototype.addMesh = function (newMesh) {
  25978. this.meshes.push(newMesh);
  25979. //notify the collision coordinator
  25980. if (this.collisionCoordinator) {
  25981. this.collisionCoordinator.onMeshAdded(newMesh);
  25982. }
  25983. newMesh._resyncLightSources();
  25984. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  25985. };
  25986. /**
  25987. * Remove a mesh for the list of scene's meshes
  25988. * @param toRemove defines the mesh to remove
  25989. * @param recursive if all child meshes should also be removed from the scene
  25990. * @returns the index where the mesh was in the mesh list
  25991. */
  25992. Scene.prototype.removeMesh = function (toRemove, recursive) {
  25993. var _this = this;
  25994. if (recursive === void 0) { recursive = false; }
  25995. var index = this.meshes.indexOf(toRemove);
  25996. if (index !== -1) {
  25997. // Remove from the scene if mesh found
  25998. this.meshes.splice(index, 1);
  25999. }
  26000. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26001. if (recursive) {
  26002. toRemove.getChildMeshes().forEach(function (m) {
  26003. _this.removeMesh(m);
  26004. });
  26005. }
  26006. return index;
  26007. };
  26008. /**
  26009. * Add a transform node to the list of scene's transform nodes
  26010. * @param newTransformNode defines the transform node to add
  26011. */
  26012. Scene.prototype.addTransformNode = function (newTransformNode) {
  26013. this.transformNodes.push(newTransformNode);
  26014. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26015. };
  26016. /**
  26017. * Remove a transform node for the list of scene's transform nodes
  26018. * @param toRemove defines the transform node to remove
  26019. * @returns the index where the transform node was in the transform node list
  26020. */
  26021. Scene.prototype.removeTransformNode = function (toRemove) {
  26022. var index = this.transformNodes.indexOf(toRemove);
  26023. if (index !== -1) {
  26024. // Remove from the scene if found
  26025. this.transformNodes.splice(index, 1);
  26026. }
  26027. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26028. return index;
  26029. };
  26030. /**
  26031. * Remove a skeleton for the list of scene's skeletons
  26032. * @param toRemove defines the skeleton to remove
  26033. * @returns the index where the skeleton was in the skeleton list
  26034. */
  26035. Scene.prototype.removeSkeleton = function (toRemove) {
  26036. var index = this.skeletons.indexOf(toRemove);
  26037. if (index !== -1) {
  26038. // Remove from the scene if found
  26039. this.skeletons.splice(index, 1);
  26040. }
  26041. return index;
  26042. };
  26043. /**
  26044. * Remove a morph target for the list of scene's morph targets
  26045. * @param toRemove defines the morph target to remove
  26046. * @returns the index where the morph target was in the morph target list
  26047. */
  26048. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26049. var index = this.morphTargetManagers.indexOf(toRemove);
  26050. if (index !== -1) {
  26051. // Remove from the scene if found
  26052. this.morphTargetManagers.splice(index, 1);
  26053. }
  26054. return index;
  26055. };
  26056. /**
  26057. * Remove a light for the list of scene's lights
  26058. * @param toRemove defines the light to remove
  26059. * @returns the index where the light was in the light list
  26060. */
  26061. Scene.prototype.removeLight = function (toRemove) {
  26062. var index = this.lights.indexOf(toRemove);
  26063. if (index !== -1) {
  26064. // Remove from meshes
  26065. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26066. var mesh = _a[_i];
  26067. mesh._removeLightSource(toRemove);
  26068. }
  26069. // Remove from the scene if mesh found
  26070. this.lights.splice(index, 1);
  26071. this.sortLightsByPriority();
  26072. }
  26073. this.onLightRemovedObservable.notifyObservers(toRemove);
  26074. return index;
  26075. };
  26076. /**
  26077. * Remove a camera for the list of scene's cameras
  26078. * @param toRemove defines the camera to remove
  26079. * @returns the index where the camera was in the camera list
  26080. */
  26081. Scene.prototype.removeCamera = function (toRemove) {
  26082. var index = this.cameras.indexOf(toRemove);
  26083. if (index !== -1) {
  26084. // Remove from the scene if mesh found
  26085. this.cameras.splice(index, 1);
  26086. }
  26087. // Remove from activeCameras
  26088. var index2 = this.activeCameras.indexOf(toRemove);
  26089. if (index2 !== -1) {
  26090. // Remove from the scene if mesh found
  26091. this.activeCameras.splice(index2, 1);
  26092. }
  26093. // Reset the activeCamera
  26094. if (this.activeCamera === toRemove) {
  26095. if (this.cameras.length > 0) {
  26096. this.activeCamera = this.cameras[0];
  26097. }
  26098. else {
  26099. this.activeCamera = null;
  26100. }
  26101. }
  26102. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26103. return index;
  26104. };
  26105. /**
  26106. * Remove a particle system for the list of scene's particle systems
  26107. * @param toRemove defines the particle system to remove
  26108. * @returns the index where the particle system was in the particle system list
  26109. */
  26110. Scene.prototype.removeParticleSystem = function (toRemove) {
  26111. var index = this.particleSystems.indexOf(toRemove);
  26112. if (index !== -1) {
  26113. this.particleSystems.splice(index, 1);
  26114. }
  26115. return index;
  26116. };
  26117. /**
  26118. * Remove a animation for the list of scene's animations
  26119. * @param toRemove defines the animation to remove
  26120. * @returns the index where the animation was in the animation list
  26121. */
  26122. Scene.prototype.removeAnimation = function (toRemove) {
  26123. var index = this.animations.indexOf(toRemove);
  26124. if (index !== -1) {
  26125. this.animations.splice(index, 1);
  26126. }
  26127. return index;
  26128. };
  26129. /**
  26130. * Removes the given animation group from this scene.
  26131. * @param toRemove The animation group to remove
  26132. * @returns The index of the removed animation group
  26133. */
  26134. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26135. var index = this.animationGroups.indexOf(toRemove);
  26136. if (index !== -1) {
  26137. this.animationGroups.splice(index, 1);
  26138. }
  26139. return index;
  26140. };
  26141. /**
  26142. * Removes the given multi-material from this scene.
  26143. * @param toRemove The multi-material to remove
  26144. * @returns The index of the removed multi-material
  26145. */
  26146. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26147. var index = this.multiMaterials.indexOf(toRemove);
  26148. if (index !== -1) {
  26149. this.multiMaterials.splice(index, 1);
  26150. }
  26151. return index;
  26152. };
  26153. /**
  26154. * Removes the given material from this scene.
  26155. * @param toRemove The material to remove
  26156. * @returns The index of the removed material
  26157. */
  26158. Scene.prototype.removeMaterial = function (toRemove) {
  26159. var index = this.materials.indexOf(toRemove);
  26160. if (index !== -1) {
  26161. this.materials.splice(index, 1);
  26162. }
  26163. return index;
  26164. };
  26165. /**
  26166. * Removes the given lens flare system from this scene.
  26167. * @param toRemove The lens flare system to remove
  26168. * @returns The index of the removed lens flare system
  26169. */
  26170. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26171. var index = this.lensFlareSystems.indexOf(toRemove);
  26172. if (index !== -1) {
  26173. this.lensFlareSystems.splice(index, 1);
  26174. }
  26175. return index;
  26176. };
  26177. /**
  26178. * Removes the given action manager from this scene.
  26179. * @param toRemove The action manager to remove
  26180. * @returns The index of the removed action manager
  26181. */
  26182. Scene.prototype.removeActionManager = function (toRemove) {
  26183. var index = this._actionManagers.indexOf(toRemove);
  26184. if (index !== -1) {
  26185. this._actionManagers.splice(index, 1);
  26186. }
  26187. return index;
  26188. };
  26189. /**
  26190. * Removes the given effect layer from this scene.
  26191. * @param toRemove defines the effect layer to remove
  26192. * @returns the index of the removed effect layer
  26193. */
  26194. Scene.prototype.removeEffectLayer = function (toRemove) {
  26195. var index = this.effectLayers.indexOf(toRemove);
  26196. if (index !== -1) {
  26197. this.effectLayers.splice(index, 1);
  26198. }
  26199. return index;
  26200. };
  26201. /**
  26202. * Removes the given texture from this scene.
  26203. * @param toRemove The texture to remove
  26204. * @returns The index of the removed texture
  26205. */
  26206. Scene.prototype.removeTexture = function (toRemove) {
  26207. var index = this.textures.indexOf(toRemove);
  26208. if (index !== -1) {
  26209. this.textures.splice(index, 1);
  26210. }
  26211. return index;
  26212. };
  26213. /**
  26214. * Adds the given light to this scene
  26215. * @param newLight The light to add
  26216. */
  26217. Scene.prototype.addLight = function (newLight) {
  26218. this.lights.push(newLight);
  26219. this.sortLightsByPriority();
  26220. // Add light to all meshes (To support if the light is removed and then readded)
  26221. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26222. var mesh = _a[_i];
  26223. if (mesh._lightSources.indexOf(newLight) === -1) {
  26224. mesh._lightSources.push(newLight);
  26225. mesh._resyncLightSources();
  26226. }
  26227. }
  26228. this.onNewLightAddedObservable.notifyObservers(newLight);
  26229. };
  26230. /**
  26231. * Sorts the list list based on light priorities
  26232. */
  26233. Scene.prototype.sortLightsByPriority = function () {
  26234. if (this.requireLightSorting) {
  26235. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26236. }
  26237. };
  26238. /**
  26239. * Adds the given camera to this scene
  26240. * @param newCamera The camera to add
  26241. */
  26242. Scene.prototype.addCamera = function (newCamera) {
  26243. this.cameras.push(newCamera);
  26244. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26245. };
  26246. /**
  26247. * Adds the given skeleton to this scene
  26248. * @param newSkeleton The skeleton to add
  26249. */
  26250. Scene.prototype.addSkeleton = function (newSkeleton) {
  26251. this.skeletons.push(newSkeleton);
  26252. };
  26253. /**
  26254. * Adds the given particle system to this scene
  26255. * @param newParticleSystem The particle system to add
  26256. */
  26257. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26258. this.particleSystems.push(newParticleSystem);
  26259. };
  26260. /**
  26261. * Adds the given animation to this scene
  26262. * @param newAnimation The animation to add
  26263. */
  26264. Scene.prototype.addAnimation = function (newAnimation) {
  26265. this.animations.push(newAnimation);
  26266. };
  26267. /**
  26268. * Adds the given animation group to this scene.
  26269. * @param newAnimationGroup The animation group to add
  26270. */
  26271. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26272. this.animationGroups.push(newAnimationGroup);
  26273. };
  26274. /**
  26275. * Adds the given multi-material to this scene
  26276. * @param newMultiMaterial The multi-material to add
  26277. */
  26278. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26279. this.multiMaterials.push(newMultiMaterial);
  26280. };
  26281. /**
  26282. * Adds the given material to this scene
  26283. * @param newMaterial The material to add
  26284. */
  26285. Scene.prototype.addMaterial = function (newMaterial) {
  26286. this.materials.push(newMaterial);
  26287. };
  26288. /**
  26289. * Adds the given morph target to this scene
  26290. * @param newMorphTargetManager The morph target to add
  26291. */
  26292. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26293. this.morphTargetManagers.push(newMorphTargetManager);
  26294. };
  26295. /**
  26296. * Adds the given geometry to this scene
  26297. * @param newGeometry The geometry to add
  26298. */
  26299. Scene.prototype.addGeometry = function (newGeometry) {
  26300. this._geometries.push(newGeometry);
  26301. };
  26302. /**
  26303. * Adds the given lens flare system to this scene
  26304. * @param newLensFlareSystem The lens flare system to add
  26305. */
  26306. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26307. this.lensFlareSystems.push(newLensFlareSystem);
  26308. };
  26309. /**
  26310. * Adds the given effect layer to this scene
  26311. * @param newEffectLayer defines the effect layer to add
  26312. */
  26313. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26314. this.effectLayers.push(newEffectLayer);
  26315. };
  26316. /**
  26317. * Adds the given action manager to this scene
  26318. * @param newActionManager The action manager to add
  26319. */
  26320. Scene.prototype.addActionManager = function (newActionManager) {
  26321. this._actionManagers.push(newActionManager);
  26322. };
  26323. /**
  26324. * Adds the given texture to this scene.
  26325. * @param newTexture The texture to add
  26326. */
  26327. Scene.prototype.addTexture = function (newTexture) {
  26328. this.textures.push(newTexture);
  26329. };
  26330. /**
  26331. * Switch active camera
  26332. * @param newCamera defines the new active camera
  26333. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26334. */
  26335. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26336. if (attachControl === void 0) { attachControl = true; }
  26337. var canvas = this._engine.getRenderingCanvas();
  26338. if (!canvas) {
  26339. return;
  26340. }
  26341. if (this.activeCamera) {
  26342. this.activeCamera.detachControl(canvas);
  26343. }
  26344. this.activeCamera = newCamera;
  26345. if (attachControl) {
  26346. newCamera.attachControl(canvas);
  26347. }
  26348. };
  26349. /**
  26350. * sets the active camera of the scene using its ID
  26351. * @param id defines the camera's ID
  26352. * @return the new active camera or null if none found.
  26353. */
  26354. Scene.prototype.setActiveCameraByID = function (id) {
  26355. var camera = this.getCameraByID(id);
  26356. if (camera) {
  26357. this.activeCamera = camera;
  26358. return camera;
  26359. }
  26360. return null;
  26361. };
  26362. /**
  26363. * sets the active camera of the scene using its name
  26364. * @param name defines the camera's name
  26365. * @returns the new active camera or null if none found.
  26366. */
  26367. Scene.prototype.setActiveCameraByName = function (name) {
  26368. var camera = this.getCameraByName(name);
  26369. if (camera) {
  26370. this.activeCamera = camera;
  26371. return camera;
  26372. }
  26373. return null;
  26374. };
  26375. /**
  26376. * get an animation group using its name
  26377. * @param name defines the material's name
  26378. * @return the animation group or null if none found.
  26379. */
  26380. Scene.prototype.getAnimationGroupByName = function (name) {
  26381. for (var index = 0; index < this.animationGroups.length; index++) {
  26382. if (this.animationGroups[index].name === name) {
  26383. return this.animationGroups[index];
  26384. }
  26385. }
  26386. return null;
  26387. };
  26388. /**
  26389. * get a material using its id
  26390. * @param id defines the material's ID
  26391. * @return the material or null if none found.
  26392. */
  26393. Scene.prototype.getMaterialByID = function (id) {
  26394. for (var index = 0; index < this.materials.length; index++) {
  26395. if (this.materials[index].id === id) {
  26396. return this.materials[index];
  26397. }
  26398. }
  26399. return null;
  26400. };
  26401. /**
  26402. * Gets a material using its name
  26403. * @param name defines the material's name
  26404. * @return the material or null if none found.
  26405. */
  26406. Scene.prototype.getMaterialByName = function (name) {
  26407. for (var index = 0; index < this.materials.length; index++) {
  26408. if (this.materials[index].name === name) {
  26409. return this.materials[index];
  26410. }
  26411. }
  26412. return null;
  26413. };
  26414. /**
  26415. * Gets a lens flare system using its name
  26416. * @param name defines the name to look for
  26417. * @returns the lens flare system or null if not found
  26418. */
  26419. Scene.prototype.getLensFlareSystemByName = function (name) {
  26420. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26421. if (this.lensFlareSystems[index].name === name) {
  26422. return this.lensFlareSystems[index];
  26423. }
  26424. }
  26425. return null;
  26426. };
  26427. /**
  26428. * Gets a lens flare system using its id
  26429. * @param id defines the id to look for
  26430. * @returns the lens flare system or null if not found
  26431. */
  26432. Scene.prototype.getLensFlareSystemByID = function (id) {
  26433. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26434. if (this.lensFlareSystems[index].id === id) {
  26435. return this.lensFlareSystems[index];
  26436. }
  26437. }
  26438. return null;
  26439. };
  26440. /**
  26441. * Gets a camera using its id
  26442. * @param id defines the id to look for
  26443. * @returns the camera or null if not found
  26444. */
  26445. Scene.prototype.getCameraByID = function (id) {
  26446. for (var index = 0; index < this.cameras.length; index++) {
  26447. if (this.cameras[index].id === id) {
  26448. return this.cameras[index];
  26449. }
  26450. }
  26451. return null;
  26452. };
  26453. /**
  26454. * Gets a camera using its unique id
  26455. * @param uniqueId defines the unique id to look for
  26456. * @returns the camera or null if not found
  26457. */
  26458. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26459. for (var index = 0; index < this.cameras.length; index++) {
  26460. if (this.cameras[index].uniqueId === uniqueId) {
  26461. return this.cameras[index];
  26462. }
  26463. }
  26464. return null;
  26465. };
  26466. /**
  26467. * Gets a camera using its name
  26468. * @param name defines the camera's name
  26469. * @return the camera or null if none found.
  26470. */
  26471. Scene.prototype.getCameraByName = function (name) {
  26472. for (var index = 0; index < this.cameras.length; index++) {
  26473. if (this.cameras[index].name === name) {
  26474. return this.cameras[index];
  26475. }
  26476. }
  26477. return null;
  26478. };
  26479. /**
  26480. * Gets a bone using its id
  26481. * @param id defines the bone's id
  26482. * @return the bone or null if not found
  26483. */
  26484. Scene.prototype.getBoneByID = function (id) {
  26485. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26486. var skeleton = this.skeletons[skeletonIndex];
  26487. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26488. if (skeleton.bones[boneIndex].id === id) {
  26489. return skeleton.bones[boneIndex];
  26490. }
  26491. }
  26492. }
  26493. return null;
  26494. };
  26495. /**
  26496. * Gets a bone using its id
  26497. * @param name defines the bone's name
  26498. * @return the bone or null if not found
  26499. */
  26500. Scene.prototype.getBoneByName = function (name) {
  26501. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26502. var skeleton = this.skeletons[skeletonIndex];
  26503. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26504. if (skeleton.bones[boneIndex].name === name) {
  26505. return skeleton.bones[boneIndex];
  26506. }
  26507. }
  26508. }
  26509. return null;
  26510. };
  26511. /**
  26512. * Gets a light node using its name
  26513. * @param name defines the the light's name
  26514. * @return the light or null if none found.
  26515. */
  26516. Scene.prototype.getLightByName = function (name) {
  26517. for (var index = 0; index < this.lights.length; index++) {
  26518. if (this.lights[index].name === name) {
  26519. return this.lights[index];
  26520. }
  26521. }
  26522. return null;
  26523. };
  26524. /**
  26525. * Gets a light node using its id
  26526. * @param id defines the light's id
  26527. * @return the light or null if none found.
  26528. */
  26529. Scene.prototype.getLightByID = function (id) {
  26530. for (var index = 0; index < this.lights.length; index++) {
  26531. if (this.lights[index].id === id) {
  26532. return this.lights[index];
  26533. }
  26534. }
  26535. return null;
  26536. };
  26537. /**
  26538. * Gets a light node using its scene-generated unique ID
  26539. * @param uniqueId defines the light's unique id
  26540. * @return the light or null if none found.
  26541. */
  26542. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26543. for (var index = 0; index < this.lights.length; index++) {
  26544. if (this.lights[index].uniqueId === uniqueId) {
  26545. return this.lights[index];
  26546. }
  26547. }
  26548. return null;
  26549. };
  26550. /**
  26551. * Gets a particle system by id
  26552. * @param id defines the particle system id
  26553. * @return the corresponding system or null if none found
  26554. */
  26555. Scene.prototype.getParticleSystemByID = function (id) {
  26556. for (var index = 0; index < this.particleSystems.length; index++) {
  26557. if (this.particleSystems[index].id === id) {
  26558. return this.particleSystems[index];
  26559. }
  26560. }
  26561. return null;
  26562. };
  26563. /**
  26564. * Gets a geometry using its ID
  26565. * @param id defines the geometry's id
  26566. * @return the geometry or null if none found.
  26567. */
  26568. Scene.prototype.getGeometryByID = function (id) {
  26569. for (var index = 0; index < this._geometries.length; index++) {
  26570. if (this._geometries[index].id === id) {
  26571. return this._geometries[index];
  26572. }
  26573. }
  26574. return null;
  26575. };
  26576. /**
  26577. * Add a new geometry to this scene
  26578. * @param geometry defines the geometry to be added to the scene.
  26579. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26580. * @return a boolean defining if the geometry was added or not
  26581. */
  26582. Scene.prototype.pushGeometry = function (geometry, force) {
  26583. if (!force && this.getGeometryByID(geometry.id)) {
  26584. return false;
  26585. }
  26586. this._geometries.push(geometry);
  26587. //notify the collision coordinator
  26588. if (this.collisionCoordinator) {
  26589. this.collisionCoordinator.onGeometryAdded(geometry);
  26590. }
  26591. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26592. return true;
  26593. };
  26594. /**
  26595. * Removes an existing geometry
  26596. * @param geometry defines the geometry to be removed from the scene
  26597. * @return a boolean defining if the geometry was removed or not
  26598. */
  26599. Scene.prototype.removeGeometry = function (geometry) {
  26600. var index = this._geometries.indexOf(geometry);
  26601. if (index > -1) {
  26602. this._geometries.splice(index, 1);
  26603. //notify the collision coordinator
  26604. if (this.collisionCoordinator) {
  26605. this.collisionCoordinator.onGeometryDeleted(geometry);
  26606. }
  26607. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26608. return true;
  26609. }
  26610. return false;
  26611. };
  26612. /**
  26613. * Gets the list of geometries attached to the scene
  26614. * @returns an array of Geometry
  26615. */
  26616. Scene.prototype.getGeometries = function () {
  26617. return this._geometries;
  26618. };
  26619. /**
  26620. * Gets the first added mesh found of a given ID
  26621. * @param id defines the id to search for
  26622. * @return the mesh found or null if not found at all
  26623. */
  26624. Scene.prototype.getMeshByID = function (id) {
  26625. for (var index = 0; index < this.meshes.length; index++) {
  26626. if (this.meshes[index].id === id) {
  26627. return this.meshes[index];
  26628. }
  26629. }
  26630. return null;
  26631. };
  26632. /**
  26633. * Gets a list of meshes using their id
  26634. * @param id defines the id to search for
  26635. * @returns a list of meshes
  26636. */
  26637. Scene.prototype.getMeshesByID = function (id) {
  26638. return this.meshes.filter(function (m) {
  26639. return m.id === id;
  26640. });
  26641. };
  26642. /**
  26643. * Gets the first added transform node found of a given ID
  26644. * @param id defines the id to search for
  26645. * @return the found transform node or null if not found at all.
  26646. */
  26647. Scene.prototype.getTransformNodeByID = function (id) {
  26648. for (var index = 0; index < this.transformNodes.length; index++) {
  26649. if (this.transformNodes[index].id === id) {
  26650. return this.transformNodes[index];
  26651. }
  26652. }
  26653. return null;
  26654. };
  26655. /**
  26656. * Gets a list of transform nodes using their id
  26657. * @param id defines the id to search for
  26658. * @returns a list of transform nodes
  26659. */
  26660. Scene.prototype.getTransformNodesByID = function (id) {
  26661. return this.transformNodes.filter(function (m) {
  26662. return m.id === id;
  26663. });
  26664. };
  26665. /**
  26666. * Gets a mesh with its auto-generated unique id
  26667. * @param uniqueId defines the unique id to search for
  26668. * @return the found mesh or null if not found at all.
  26669. */
  26670. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26671. for (var index = 0; index < this.meshes.length; index++) {
  26672. if (this.meshes[index].uniqueId === uniqueId) {
  26673. return this.meshes[index];
  26674. }
  26675. }
  26676. return null;
  26677. };
  26678. /**
  26679. * Gets a the last added mesh using a given id
  26680. * @param id defines the id to search for
  26681. * @return the found mesh or null if not found at all.
  26682. */
  26683. Scene.prototype.getLastMeshByID = function (id) {
  26684. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26685. if (this.meshes[index].id === id) {
  26686. return this.meshes[index];
  26687. }
  26688. }
  26689. return null;
  26690. };
  26691. /**
  26692. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26693. * @param id defines the id to search for
  26694. * @return the found node or null if not found at all
  26695. */
  26696. Scene.prototype.getLastEntryByID = function (id) {
  26697. var index;
  26698. for (index = this.meshes.length - 1; index >= 0; index--) {
  26699. if (this.meshes[index].id === id) {
  26700. return this.meshes[index];
  26701. }
  26702. }
  26703. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26704. if (this.transformNodes[index].id === id) {
  26705. return this.transformNodes[index];
  26706. }
  26707. }
  26708. for (index = this.cameras.length - 1; index >= 0; index--) {
  26709. if (this.cameras[index].id === id) {
  26710. return this.cameras[index];
  26711. }
  26712. }
  26713. for (index = this.lights.length - 1; index >= 0; index--) {
  26714. if (this.lights[index].id === id) {
  26715. return this.lights[index];
  26716. }
  26717. }
  26718. return null;
  26719. };
  26720. /**
  26721. * Gets a node (Mesh, Camera, Light) using a given id
  26722. * @param id defines the id to search for
  26723. * @return the found node or null if not found at all
  26724. */
  26725. Scene.prototype.getNodeByID = function (id) {
  26726. var mesh = this.getMeshByID(id);
  26727. if (mesh) {
  26728. return mesh;
  26729. }
  26730. var light = this.getLightByID(id);
  26731. if (light) {
  26732. return light;
  26733. }
  26734. var camera = this.getCameraByID(id);
  26735. if (camera) {
  26736. return camera;
  26737. }
  26738. var bone = this.getBoneByID(id);
  26739. return bone;
  26740. };
  26741. /**
  26742. * Gets a node (Mesh, Camera, Light) using a given name
  26743. * @param name defines the name to search for
  26744. * @return the found node or null if not found at all.
  26745. */
  26746. Scene.prototype.getNodeByName = function (name) {
  26747. var mesh = this.getMeshByName(name);
  26748. if (mesh) {
  26749. return mesh;
  26750. }
  26751. var light = this.getLightByName(name);
  26752. if (light) {
  26753. return light;
  26754. }
  26755. var camera = this.getCameraByName(name);
  26756. if (camera) {
  26757. return camera;
  26758. }
  26759. var bone = this.getBoneByName(name);
  26760. return bone;
  26761. };
  26762. /**
  26763. * Gets a mesh using a given name
  26764. * @param name defines the name to search for
  26765. * @return the found mesh or null if not found at all.
  26766. */
  26767. Scene.prototype.getMeshByName = function (name) {
  26768. for (var index = 0; index < this.meshes.length; index++) {
  26769. if (this.meshes[index].name === name) {
  26770. return this.meshes[index];
  26771. }
  26772. }
  26773. return null;
  26774. };
  26775. /**
  26776. * Gets a transform node using a given name
  26777. * @param name defines the name to search for
  26778. * @return the found transform node or null if not found at all.
  26779. */
  26780. Scene.prototype.getTransformNodeByName = function (name) {
  26781. for (var index = 0; index < this.transformNodes.length; index++) {
  26782. if (this.transformNodes[index].name === name) {
  26783. return this.transformNodes[index];
  26784. }
  26785. }
  26786. return null;
  26787. };
  26788. /**
  26789. * Gets a sound using a given name
  26790. * @param name defines the name to search for
  26791. * @return the found sound or null if not found at all.
  26792. */
  26793. Scene.prototype.getSoundByName = function (name) {
  26794. var index;
  26795. if (BABYLON.AudioEngine) {
  26796. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26797. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26798. return this.mainSoundTrack.soundCollection[index];
  26799. }
  26800. }
  26801. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26802. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26803. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26804. return this.soundTracks[sdIndex].soundCollection[index];
  26805. }
  26806. }
  26807. }
  26808. }
  26809. return null;
  26810. };
  26811. /**
  26812. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26813. * @param id defines the id to search for
  26814. * @return the found skeleton or null if not found at all.
  26815. */
  26816. Scene.prototype.getLastSkeletonByID = function (id) {
  26817. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26818. if (this.skeletons[index].id === id) {
  26819. return this.skeletons[index];
  26820. }
  26821. }
  26822. return null;
  26823. };
  26824. /**
  26825. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26826. * @param id defines the id to search for
  26827. * @return the found skeleton or null if not found at all.
  26828. */
  26829. Scene.prototype.getSkeletonById = function (id) {
  26830. for (var index = 0; index < this.skeletons.length; index++) {
  26831. if (this.skeletons[index].id === id) {
  26832. return this.skeletons[index];
  26833. }
  26834. }
  26835. return null;
  26836. };
  26837. /**
  26838. * Gets a skeleton using a given name
  26839. * @param name defines the name to search for
  26840. * @return the found skeleton or null if not found at all.
  26841. */
  26842. Scene.prototype.getSkeletonByName = function (name) {
  26843. for (var index = 0; index < this.skeletons.length; index++) {
  26844. if (this.skeletons[index].name === name) {
  26845. return this.skeletons[index];
  26846. }
  26847. }
  26848. return null;
  26849. };
  26850. /**
  26851. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26852. * @param id defines the id to search for
  26853. * @return the found morph target manager or null if not found at all.
  26854. */
  26855. Scene.prototype.getMorphTargetManagerById = function (id) {
  26856. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26857. if (this.morphTargetManagers[index].uniqueId === id) {
  26858. return this.morphTargetManagers[index];
  26859. }
  26860. }
  26861. return null;
  26862. };
  26863. /**
  26864. * Gets a boolean indicating if the given mesh is active
  26865. * @param mesh defines the mesh to look for
  26866. * @returns true if the mesh is in the active list
  26867. */
  26868. Scene.prototype.isActiveMesh = function (mesh) {
  26869. return (this._activeMeshes.indexOf(mesh) !== -1);
  26870. };
  26871. /**
  26872. * Return a the first highlight layer of the scene with a given name.
  26873. * @param name The name of the highlight layer to look for.
  26874. * @return The highlight layer if found otherwise null.
  26875. */
  26876. Scene.prototype.getHighlightLayerByName = function (name) {
  26877. for (var index = 0; index < this.effectLayers.length; index++) {
  26878. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26879. return this.effectLayers[index];
  26880. }
  26881. }
  26882. return null;
  26883. };
  26884. /**
  26885. * Return a the first highlight layer of the scene with a given name.
  26886. * @param name The name of the highlight layer to look for.
  26887. * @return The highlight layer if found otherwise null.
  26888. */
  26889. Scene.prototype.getGlowLayerByName = function (name) {
  26890. for (var index = 0; index < this.effectLayers.length; index++) {
  26891. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  26892. return this.effectLayers[index];
  26893. }
  26894. }
  26895. return null;
  26896. };
  26897. Object.defineProperty(Scene.prototype, "uid", {
  26898. /**
  26899. * Return a unique id as a string which can serve as an identifier for the scene
  26900. */
  26901. get: function () {
  26902. if (!this._uid) {
  26903. this._uid = BABYLON.Tools.RandomId();
  26904. }
  26905. return this._uid;
  26906. },
  26907. enumerable: true,
  26908. configurable: true
  26909. });
  26910. /**
  26911. * Add an externaly attached data from its key.
  26912. * This method call will fail and return false, if such key already exists.
  26913. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26914. * @param key the unique key that identifies the data
  26915. * @param data the data object to associate to the key for this Engine instance
  26916. * @return true if no such key were already present and the data was added successfully, false otherwise
  26917. */
  26918. Scene.prototype.addExternalData = function (key, data) {
  26919. if (!this._externalData) {
  26920. this._externalData = new BABYLON.StringDictionary();
  26921. }
  26922. return this._externalData.add(key, data);
  26923. };
  26924. /**
  26925. * Get an externaly attached data from its key
  26926. * @param key the unique key that identifies the data
  26927. * @return the associated data, if present (can be null), or undefined if not present
  26928. */
  26929. Scene.prototype.getExternalData = function (key) {
  26930. if (!this._externalData) {
  26931. return null;
  26932. }
  26933. return this._externalData.get(key);
  26934. };
  26935. /**
  26936. * Get an externaly attached data from its key, create it using a factory if it's not already present
  26937. * @param key the unique key that identifies the data
  26938. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  26939. * @return the associated data, can be null if the factory returned null.
  26940. */
  26941. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  26942. if (!this._externalData) {
  26943. this._externalData = new BABYLON.StringDictionary();
  26944. }
  26945. return this._externalData.getOrAddWithFactory(key, factory);
  26946. };
  26947. /**
  26948. * Remove an externaly attached data from the Engine instance
  26949. * @param key the unique key that identifies the data
  26950. * @return true if the data was successfully removed, false if it doesn't exist
  26951. */
  26952. Scene.prototype.removeExternalData = function (key) {
  26953. return this._externalData.remove(key);
  26954. };
  26955. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  26956. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  26957. if (mesh.showSubMeshesBoundingBox) {
  26958. var boundingInfo = subMesh.getBoundingInfo();
  26959. if (boundingInfo !== null && boundingInfo !== undefined) {
  26960. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  26961. }
  26962. }
  26963. var material = subMesh.getMaterial();
  26964. if (material !== null && material !== undefined) {
  26965. // Render targets
  26966. if (material.getRenderTargetTextures !== undefined) {
  26967. if (this._processedMaterials.indexOf(material) === -1) {
  26968. this._processedMaterials.push(material);
  26969. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  26970. }
  26971. }
  26972. // Dispatch
  26973. this._activeIndices.addCount(subMesh.indexCount, false);
  26974. this._renderingManager.dispatch(subMesh, mesh, material);
  26975. }
  26976. }
  26977. };
  26978. /**
  26979. * Clear the processed materials smart array preventing retention point in material dispose.
  26980. */
  26981. Scene.prototype.freeProcessedMaterials = function () {
  26982. this._processedMaterials.dispose();
  26983. };
  26984. /**
  26985. * Clear the active meshes smart array preventing retention point in mesh dispose.
  26986. */
  26987. Scene.prototype.freeActiveMeshes = function () {
  26988. this._activeMeshes.dispose();
  26989. if (this.activeCamera && this.activeCamera._activeMeshes) {
  26990. this.activeCamera._activeMeshes.dispose();
  26991. }
  26992. if (this.activeCameras) {
  26993. for (var i = 0; i < this.activeCameras.length; i++) {
  26994. var activeCamera = this.activeCameras[i];
  26995. if (activeCamera && activeCamera._activeMeshes) {
  26996. activeCamera._activeMeshes.dispose();
  26997. }
  26998. }
  26999. }
  27000. };
  27001. /**
  27002. * Clear the info related to rendering groups preventing retention points during dispose.
  27003. */
  27004. Scene.prototype.freeRenderingGroups = function () {
  27005. if (this._renderingManager) {
  27006. this._renderingManager.freeRenderingGroups();
  27007. }
  27008. if (this.textures) {
  27009. for (var i = 0; i < this.textures.length; i++) {
  27010. var texture = this.textures[i];
  27011. if (texture && texture.renderList) {
  27012. texture.freeRenderingGroups();
  27013. }
  27014. }
  27015. }
  27016. };
  27017. /** @hidden */
  27018. Scene.prototype._isInIntermediateRendering = function () {
  27019. return this._intermediateRendering;
  27020. };
  27021. /**
  27022. * Defines the current active mesh candidate provider
  27023. * @param provider defines the provider to use
  27024. */
  27025. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27026. this._activeMeshCandidateProvider = provider;
  27027. };
  27028. /**
  27029. * Gets the current active mesh candidate provider
  27030. * @returns the current active mesh candidate provider
  27031. */
  27032. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27033. return this._activeMeshCandidateProvider;
  27034. };
  27035. /**
  27036. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27037. * @returns the current scene
  27038. */
  27039. Scene.prototype.freezeActiveMeshes = function () {
  27040. if (!this.activeCamera) {
  27041. return this;
  27042. }
  27043. if (!this._frustumPlanes) {
  27044. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27045. }
  27046. this._evaluateActiveMeshes();
  27047. this._activeMeshesFrozen = true;
  27048. return this;
  27049. };
  27050. /**
  27051. * Use this function to restart evaluating active meshes on every frame
  27052. * @returns the current scene
  27053. */
  27054. Scene.prototype.unfreezeActiveMeshes = function () {
  27055. this._activeMeshesFrozen = false;
  27056. return this;
  27057. };
  27058. Scene.prototype._evaluateActiveMeshes = function () {
  27059. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27060. return;
  27061. }
  27062. if (!this.activeCamera) {
  27063. return;
  27064. }
  27065. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27066. this.activeCamera._activeMeshes.reset();
  27067. this._activeMeshes.reset();
  27068. this._renderingManager.reset();
  27069. this._processedMaterials.reset();
  27070. this._activeParticleSystems.reset();
  27071. this._activeSkeletons.reset();
  27072. this._softwareSkinnedMeshes.reset();
  27073. if (this._boundingBoxRenderer) {
  27074. this._boundingBoxRenderer.reset();
  27075. }
  27076. // Meshes
  27077. var meshes;
  27078. var len;
  27079. var checkIsEnabled = true;
  27080. // Determine mesh candidates
  27081. if (this._activeMeshCandidateProvider !== undefined) {
  27082. // Use _activeMeshCandidateProvider
  27083. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27084. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27085. if (meshes !== undefined) {
  27086. len = meshes.length;
  27087. }
  27088. else {
  27089. len = 0;
  27090. }
  27091. }
  27092. else if (this._selectionOctree !== undefined) {
  27093. // Octree
  27094. var selection = this._selectionOctree.select(this._frustumPlanes);
  27095. meshes = selection.data;
  27096. len = selection.length;
  27097. }
  27098. else {
  27099. // Full scene traversal
  27100. len = this.meshes.length;
  27101. meshes = this.meshes;
  27102. }
  27103. // Check each mesh
  27104. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27105. mesh = meshes[meshIndex];
  27106. if (mesh.isBlocked) {
  27107. continue;
  27108. }
  27109. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27110. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27111. continue;
  27112. }
  27113. mesh.computeWorldMatrix();
  27114. // Intersections
  27115. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27116. this._meshesForIntersections.pushNoDuplicate(mesh);
  27117. }
  27118. // Switch to current LOD
  27119. meshLOD = mesh.getLOD(this.activeCamera);
  27120. if (meshLOD === undefined || meshLOD === null) {
  27121. continue;
  27122. }
  27123. mesh._preActivate();
  27124. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27125. this._activeMeshes.push(mesh);
  27126. this.activeCamera._activeMeshes.push(mesh);
  27127. mesh._activate(this._renderId);
  27128. if (meshLOD !== mesh) {
  27129. meshLOD._activate(this._renderId);
  27130. }
  27131. this._activeMesh(mesh, meshLOD);
  27132. }
  27133. }
  27134. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27135. // Particle systems
  27136. if (this.particlesEnabled) {
  27137. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27138. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27139. var particleSystem = this.particleSystems[particleIndex];
  27140. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27141. continue;
  27142. }
  27143. var emitter = particleSystem.emitter;
  27144. if (!emitter.position || emitter.isEnabled()) {
  27145. this._activeParticleSystems.push(particleSystem);
  27146. particleSystem.animate();
  27147. this._renderingManager.dispatchParticles(particleSystem);
  27148. }
  27149. }
  27150. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27151. }
  27152. };
  27153. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27154. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27155. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27156. mesh.skeleton.prepare();
  27157. }
  27158. if (!mesh.computeBonesUsingShaders) {
  27159. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27160. }
  27161. }
  27162. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27163. var boundingInfo = sourceMesh.getBoundingInfo();
  27164. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27165. }
  27166. if (mesh !== undefined && mesh !== null
  27167. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27168. // Submeshes Octrees
  27169. var len;
  27170. var subMeshes;
  27171. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27172. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27173. len = intersections.length;
  27174. subMeshes = intersections.data;
  27175. }
  27176. else {
  27177. subMeshes = mesh.subMeshes;
  27178. len = subMeshes.length;
  27179. }
  27180. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27181. subMesh = subMeshes[subIndex];
  27182. this._evaluateSubMesh(subMesh, mesh);
  27183. }
  27184. }
  27185. };
  27186. /**
  27187. * Update the transform matrix to update from the current active camera
  27188. * @param force defines a boolean used to force the update even if cache is up to date
  27189. */
  27190. Scene.prototype.updateTransformMatrix = function (force) {
  27191. if (!this.activeCamera) {
  27192. return;
  27193. }
  27194. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27195. };
  27196. /**
  27197. * 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)
  27198. * @param alternateCamera defines the camera to use
  27199. */
  27200. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27201. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27202. };
  27203. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27204. if (camera && camera._skipRendering) {
  27205. return;
  27206. }
  27207. var engine = this._engine;
  27208. this.activeCamera = camera;
  27209. if (!this.activeCamera)
  27210. throw new Error("Active camera not set");
  27211. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27212. // Viewport
  27213. engine.setViewport(this.activeCamera.viewport);
  27214. // Camera
  27215. this.resetCachedMaterial();
  27216. this._renderId++;
  27217. this.updateTransformMatrix();
  27218. if (camera._alternateCamera) {
  27219. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27220. this._alternateRendering = true;
  27221. }
  27222. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27223. // Meshes
  27224. this._evaluateActiveMeshes();
  27225. // Software skinning
  27226. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27227. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27228. mesh.applySkeleton(mesh.skeleton);
  27229. }
  27230. // Render targets
  27231. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27232. var needsRestoreFrameBuffer = false;
  27233. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27234. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27235. }
  27236. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27237. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27238. }
  27239. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27240. this._intermediateRendering = true;
  27241. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27242. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27243. var renderTarget = this._renderTargets.data[renderIndex];
  27244. if (renderTarget._shouldRender()) {
  27245. this._renderId++;
  27246. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27247. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27248. }
  27249. }
  27250. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27251. this._intermediateRendering = false;
  27252. this._renderId++;
  27253. needsRestoreFrameBuffer = true; // Restore back buffer
  27254. }
  27255. // Render EffecttLayer Texture
  27256. var stencilState = this._engine.getStencilBuffer();
  27257. var renderEffects = false;
  27258. var needStencil = false;
  27259. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27260. this._intermediateRendering = true;
  27261. for (var i = 0; i < this.effectLayers.length; i++) {
  27262. var effectLayer = this.effectLayers[i];
  27263. if (effectLayer.shouldRender() &&
  27264. (!effectLayer.camera ||
  27265. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27266. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27267. renderEffects = true;
  27268. needStencil = needStencil || effectLayer.needStencil();
  27269. var renderTarget = effectLayer._mainTexture;
  27270. if (renderTarget._shouldRender()) {
  27271. this._renderId++;
  27272. renderTarget.render(false, false);
  27273. needsRestoreFrameBuffer = true;
  27274. }
  27275. }
  27276. }
  27277. this._intermediateRendering = false;
  27278. this._renderId++;
  27279. }
  27280. if (needsRestoreFrameBuffer) {
  27281. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27282. }
  27283. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27284. // Prepare Frame
  27285. this.postProcessManager._prepareFrame();
  27286. // Backgrounds
  27287. var layerIndex;
  27288. var layer;
  27289. if (this.layers.length) {
  27290. engine.setDepthBuffer(false);
  27291. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27292. layer = this.layers[layerIndex];
  27293. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27294. layer.render();
  27295. }
  27296. }
  27297. engine.setDepthBuffer(true);
  27298. }
  27299. // Activate effect Layer stencil
  27300. if (needStencil) {
  27301. this._engine.setStencilBuffer(true);
  27302. }
  27303. // Render
  27304. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27305. this._renderingManager.render(null, null, true, true);
  27306. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27307. // Restore effect Layer stencil
  27308. if (needStencil) {
  27309. this._engine.setStencilBuffer(stencilState);
  27310. }
  27311. // Bounding boxes
  27312. if (this._boundingBoxRenderer) {
  27313. this._boundingBoxRenderer.render();
  27314. }
  27315. // Lens flares
  27316. if (this.lensFlaresEnabled) {
  27317. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27318. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27319. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27320. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27321. lensFlareSystem.render();
  27322. }
  27323. }
  27324. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27325. }
  27326. // Effect Layer
  27327. if (renderEffects) {
  27328. engine.setDepthBuffer(false);
  27329. for (var i = 0; i < this.effectLayers.length; i++) {
  27330. if (this.effectLayers[i].shouldRender()) {
  27331. this.effectLayers[i].render();
  27332. }
  27333. }
  27334. engine.setDepthBuffer(true);
  27335. }
  27336. // Foregrounds
  27337. if (this.layers.length) {
  27338. engine.setDepthBuffer(false);
  27339. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27340. layer = this.layers[layerIndex];
  27341. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27342. layer.render();
  27343. }
  27344. }
  27345. engine.setDepthBuffer(true);
  27346. }
  27347. // Finalize frame
  27348. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27349. // Reset some special arrays
  27350. this._renderTargets.reset();
  27351. this._alternateRendering = false;
  27352. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27353. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27354. };
  27355. Scene.prototype._processSubCameras = function (camera) {
  27356. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27357. this._renderForCamera(camera);
  27358. return;
  27359. }
  27360. // rig cameras
  27361. for (var index = 0; index < camera._rigCameras.length; index++) {
  27362. this._renderForCamera(camera._rigCameras[index], camera);
  27363. }
  27364. this.activeCamera = camera;
  27365. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27366. };
  27367. Scene.prototype._checkIntersections = function () {
  27368. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27369. var sourceMesh = this._meshesForIntersections.data[index];
  27370. if (!sourceMesh.actionManager) {
  27371. continue;
  27372. }
  27373. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27374. var action = sourceMesh.actionManager.actions[actionIndex];
  27375. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27376. var parameters = action.getTriggerParameter();
  27377. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27378. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27379. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27380. if (areIntersecting && currentIntersectionInProgress === -1) {
  27381. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27382. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27383. sourceMesh._intersectionsInProgress.push(otherMesh);
  27384. }
  27385. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27386. sourceMesh._intersectionsInProgress.push(otherMesh);
  27387. }
  27388. }
  27389. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27390. //They intersected, and now they don't.
  27391. //is this trigger an exit trigger? execute an event.
  27392. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27393. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27394. }
  27395. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27396. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27397. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27398. return otherMesh === parameterMesh;
  27399. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27400. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27401. }
  27402. }
  27403. }
  27404. }
  27405. }
  27406. };
  27407. /**
  27408. * Render the scene
  27409. */
  27410. Scene.prototype.render = function () {
  27411. if (this.isDisposed) {
  27412. return;
  27413. }
  27414. this._activeParticles.fetchNewFrame();
  27415. this._totalVertices.fetchNewFrame();
  27416. this._activeIndices.fetchNewFrame();
  27417. this._activeBones.fetchNewFrame();
  27418. this._meshesForIntersections.reset();
  27419. this.resetCachedMaterial();
  27420. this.onBeforeAnimationsObservable.notifyObservers(this);
  27421. // Actions
  27422. if (this.actionManager) {
  27423. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27424. }
  27425. //Simplification Queue
  27426. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27427. this.simplificationQueue.executeNext();
  27428. }
  27429. if (this._engine.isDeterministicLockStep()) {
  27430. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27431. var defaultFPS = (60.0 / 1000.0);
  27432. var defaultFrameTime = 1000 / 60; // frame time in MS
  27433. if (this._physicsEngine) {
  27434. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27435. }
  27436. var stepsTaken = 0;
  27437. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27438. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27439. internalSteps = Math.min(internalSteps, maxSubSteps);
  27440. do {
  27441. this.onBeforeStepObservable.notifyObservers(this);
  27442. // Animations
  27443. this._animationRatio = defaultFrameTime * defaultFPS;
  27444. this._animate();
  27445. this.onAfterAnimationsObservable.notifyObservers(this);
  27446. // Physics
  27447. if (this._physicsEngine) {
  27448. this.onBeforePhysicsObservable.notifyObservers(this);
  27449. this._physicsEngine._step(defaultFrameTime / 1000);
  27450. this.onAfterPhysicsObservable.notifyObservers(this);
  27451. }
  27452. this.onAfterStepObservable.notifyObservers(this);
  27453. this._currentStepId++;
  27454. stepsTaken++;
  27455. deltaTime -= defaultFrameTime;
  27456. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27457. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27458. }
  27459. else {
  27460. // Animations
  27461. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27462. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27463. this._animate();
  27464. this.onAfterAnimationsObservable.notifyObservers(this);
  27465. // Physics
  27466. if (this._physicsEngine) {
  27467. this.onBeforePhysicsObservable.notifyObservers(this);
  27468. this._physicsEngine._step(deltaTime / 1000.0);
  27469. this.onAfterPhysicsObservable.notifyObservers(this);
  27470. }
  27471. }
  27472. // update gamepad manager
  27473. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27474. this._gamepadManager._checkGamepadsStatus();
  27475. }
  27476. // Update Cameras
  27477. if (this.activeCameras.length > 0) {
  27478. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27479. var camera = this.activeCameras[cameraIndex];
  27480. camera.update();
  27481. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27482. // rig cameras
  27483. for (var index = 0; index < camera._rigCameras.length; index++) {
  27484. camera._rigCameras[index].update();
  27485. }
  27486. }
  27487. }
  27488. }
  27489. else if (this.activeCamera) {
  27490. this.activeCamera.update();
  27491. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27492. // rig cameras
  27493. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27494. this.activeCamera._rigCameras[index].update();
  27495. }
  27496. }
  27497. }
  27498. // Before render
  27499. this.onBeforeRenderObservable.notifyObservers(this);
  27500. // Customs render targets
  27501. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27502. var engine = this.getEngine();
  27503. var currentActiveCamera = this.activeCamera;
  27504. if (this.renderTargetsEnabled) {
  27505. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27506. this._intermediateRendering = true;
  27507. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27508. var renderTarget = this.customRenderTargets[customIndex];
  27509. if (renderTarget._shouldRender()) {
  27510. this._renderId++;
  27511. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27512. if (!this.activeCamera)
  27513. throw new Error("Active camera not set");
  27514. // Viewport
  27515. engine.setViewport(this.activeCamera.viewport);
  27516. // Camera
  27517. this.updateTransformMatrix();
  27518. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27519. }
  27520. }
  27521. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27522. this._intermediateRendering = false;
  27523. this._renderId++;
  27524. }
  27525. // Restore back buffer
  27526. if (this.customRenderTargets.length > 0) {
  27527. engine.restoreDefaultFramebuffer();
  27528. }
  27529. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27530. this.activeCamera = currentActiveCamera;
  27531. // Procedural textures
  27532. if (this.proceduralTexturesEnabled) {
  27533. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27534. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27535. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27536. if (proceduralTexture._shouldRender()) {
  27537. proceduralTexture.render();
  27538. }
  27539. }
  27540. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27541. }
  27542. // Clear
  27543. if (this.autoClearDepthAndStencil || this.autoClear) {
  27544. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27545. }
  27546. // Shadows
  27547. if (this.shadowsEnabled) {
  27548. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27549. var light = this.lights[lightIndex];
  27550. var shadowGenerator = light.getShadowGenerator();
  27551. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27552. var shadowMap = (shadowGenerator.getShadowMap());
  27553. if (this.textures.indexOf(shadowMap) !== -1) {
  27554. this._renderTargets.push(shadowMap);
  27555. }
  27556. }
  27557. }
  27558. }
  27559. // Depth renderer
  27560. for (var key in this._depthRenderer) {
  27561. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27562. }
  27563. // Geometry renderer
  27564. if (this._geometryBufferRenderer) {
  27565. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27566. }
  27567. // RenderPipeline
  27568. if (this._postProcessRenderPipelineManager) {
  27569. this._postProcessRenderPipelineManager.update();
  27570. }
  27571. // Multi-cameras?
  27572. if (this.activeCameras.length > 0) {
  27573. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27574. if (cameraIndex > 0) {
  27575. this._engine.clear(null, false, true, true);
  27576. }
  27577. this._processSubCameras(this.activeCameras[cameraIndex]);
  27578. }
  27579. }
  27580. else {
  27581. if (!this.activeCamera) {
  27582. throw new Error("No camera defined");
  27583. }
  27584. this._processSubCameras(this.activeCamera);
  27585. }
  27586. // Intersection checks
  27587. this._checkIntersections();
  27588. // Update the audio listener attached to the camera
  27589. if (BABYLON.AudioEngine) {
  27590. this._updateAudioParameters();
  27591. }
  27592. // After render
  27593. if (this.afterRender) {
  27594. this.afterRender();
  27595. }
  27596. this.onAfterRenderObservable.notifyObservers(this);
  27597. // Cleaning
  27598. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27599. var data = this._toBeDisposed.data[index];
  27600. if (data) {
  27601. data.dispose();
  27602. }
  27603. this._toBeDisposed[index] = null;
  27604. }
  27605. this._toBeDisposed.reset();
  27606. if (this.dumpNextRenderTargets) {
  27607. this.dumpNextRenderTargets = false;
  27608. }
  27609. this._activeBones.addCount(0, true);
  27610. this._activeIndices.addCount(0, true);
  27611. this._activeParticles.addCount(0, true);
  27612. };
  27613. Scene.prototype._updateAudioParameters = function () {
  27614. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27615. return;
  27616. }
  27617. var listeningCamera;
  27618. var audioEngine = BABYLON.Engine.audioEngine;
  27619. if (this.activeCameras.length > 0) {
  27620. listeningCamera = this.activeCameras[0];
  27621. }
  27622. else {
  27623. listeningCamera = this.activeCamera;
  27624. }
  27625. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27626. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27627. // for VR cameras
  27628. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27629. listeningCamera = listeningCamera.rigCameras[0];
  27630. }
  27631. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27632. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27633. cameraDirection.normalize();
  27634. // To avoid some errors on GearVR
  27635. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27636. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27637. }
  27638. var i;
  27639. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27640. var sound = this.mainSoundTrack.soundCollection[i];
  27641. if (sound.useCustomAttenuation) {
  27642. sound.updateDistanceFromListener();
  27643. }
  27644. }
  27645. for (i = 0; i < this.soundTracks.length; i++) {
  27646. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27647. sound = this.soundTracks[i].soundCollection[j];
  27648. if (sound.useCustomAttenuation) {
  27649. sound.updateDistanceFromListener();
  27650. }
  27651. }
  27652. }
  27653. }
  27654. };
  27655. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27656. // Audio
  27657. /**
  27658. * Gets or sets if audio support is enabled
  27659. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27660. */
  27661. get: function () {
  27662. return this._audioEnabled;
  27663. },
  27664. set: function (value) {
  27665. this._audioEnabled = value;
  27666. if (BABYLON.AudioEngine) {
  27667. if (this._audioEnabled) {
  27668. this._enableAudio();
  27669. }
  27670. else {
  27671. this._disableAudio();
  27672. }
  27673. }
  27674. },
  27675. enumerable: true,
  27676. configurable: true
  27677. });
  27678. Scene.prototype._disableAudio = function () {
  27679. var i;
  27680. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27681. this.mainSoundTrack.soundCollection[i].pause();
  27682. }
  27683. for (i = 0; i < this.soundTracks.length; i++) {
  27684. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27685. this.soundTracks[i].soundCollection[j].pause();
  27686. }
  27687. }
  27688. };
  27689. Scene.prototype._enableAudio = function () {
  27690. var i;
  27691. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27692. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27693. this.mainSoundTrack.soundCollection[i].play();
  27694. }
  27695. }
  27696. for (i = 0; i < this.soundTracks.length; i++) {
  27697. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27698. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27699. this.soundTracks[i].soundCollection[j].play();
  27700. }
  27701. }
  27702. }
  27703. };
  27704. Object.defineProperty(Scene.prototype, "headphone", {
  27705. /**
  27706. * Gets or sets if audio will be output to headphones
  27707. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27708. */
  27709. get: function () {
  27710. return this._headphone;
  27711. },
  27712. set: function (value) {
  27713. this._headphone = value;
  27714. if (BABYLON.AudioEngine) {
  27715. if (this._headphone) {
  27716. this._switchAudioModeForHeadphones();
  27717. }
  27718. else {
  27719. this._switchAudioModeForNormalSpeakers();
  27720. }
  27721. }
  27722. },
  27723. enumerable: true,
  27724. configurable: true
  27725. });
  27726. Scene.prototype._switchAudioModeForHeadphones = function () {
  27727. this.mainSoundTrack.switchPanningModelToHRTF();
  27728. for (var i = 0; i < this.soundTracks.length; i++) {
  27729. this.soundTracks[i].switchPanningModelToHRTF();
  27730. }
  27731. };
  27732. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27733. this.mainSoundTrack.switchPanningModelToEqualPower();
  27734. for (var i = 0; i < this.soundTracks.length; i++) {
  27735. this.soundTracks[i].switchPanningModelToEqualPower();
  27736. }
  27737. };
  27738. /**
  27739. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27740. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27741. * @returns the created depth renderer
  27742. */
  27743. Scene.prototype.enableDepthRenderer = function (camera) {
  27744. camera = camera || this.activeCamera;
  27745. if (!camera) {
  27746. throw "No camera available to enable depth renderer";
  27747. }
  27748. if (!this._depthRenderer[camera.id]) {
  27749. var textureType = 0;
  27750. if (this._engine.getCaps().textureHalfFloatRender) {
  27751. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27752. }
  27753. else if (this._engine.getCaps().textureFloatRender) {
  27754. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27755. }
  27756. else {
  27757. throw "Depth renderer does not support int texture type";
  27758. }
  27759. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27760. }
  27761. return this._depthRenderer[camera.id];
  27762. };
  27763. /**
  27764. * Disables a depth renderer for a given camera
  27765. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27766. */
  27767. Scene.prototype.disableDepthRenderer = function (camera) {
  27768. camera = camera || this.activeCamera;
  27769. if (!camera || !this._depthRenderer[camera.id]) {
  27770. return;
  27771. }
  27772. this._depthRenderer[camera.id].dispose();
  27773. delete this._depthRenderer[camera.id];
  27774. };
  27775. /**
  27776. * Enables a GeometryBufferRender and associates it with the scene
  27777. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27778. * @returns the GeometryBufferRenderer
  27779. */
  27780. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27781. if (ratio === void 0) { ratio = 1; }
  27782. if (this._geometryBufferRenderer) {
  27783. return this._geometryBufferRenderer;
  27784. }
  27785. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27786. if (!this._geometryBufferRenderer.isSupported) {
  27787. this._geometryBufferRenderer = null;
  27788. }
  27789. return this._geometryBufferRenderer;
  27790. };
  27791. /**
  27792. * Disables the GeometryBufferRender associated with the scene
  27793. */
  27794. Scene.prototype.disableGeometryBufferRenderer = function () {
  27795. if (!this._geometryBufferRenderer) {
  27796. return;
  27797. }
  27798. this._geometryBufferRenderer.dispose();
  27799. this._geometryBufferRenderer = null;
  27800. };
  27801. /**
  27802. * Freeze all materials
  27803. * A frozen material will not be updatable but should be faster to render
  27804. */
  27805. Scene.prototype.freezeMaterials = function () {
  27806. for (var i = 0; i < this.materials.length; i++) {
  27807. this.materials[i].freeze();
  27808. }
  27809. };
  27810. /**
  27811. * Unfreeze all materials
  27812. * A frozen material will not be updatable but should be faster to render
  27813. */
  27814. Scene.prototype.unfreezeMaterials = function () {
  27815. for (var i = 0; i < this.materials.length; i++) {
  27816. this.materials[i].unfreeze();
  27817. }
  27818. };
  27819. /**
  27820. * Releases all held ressources
  27821. */
  27822. Scene.prototype.dispose = function () {
  27823. this.beforeRender = null;
  27824. this.afterRender = null;
  27825. this.skeletons = [];
  27826. this.morphTargetManagers = [];
  27827. this.importedMeshesFiles = new Array();
  27828. this.stopAllAnimations();
  27829. this.resetCachedMaterial();
  27830. for (var key in this._depthRenderer) {
  27831. this._depthRenderer[key].dispose();
  27832. }
  27833. if (this._gamepadManager) {
  27834. this._gamepadManager.dispose();
  27835. this._gamepadManager = null;
  27836. }
  27837. // Smart arrays
  27838. if (this.activeCamera) {
  27839. this.activeCamera._activeMeshes.dispose();
  27840. this.activeCamera = null;
  27841. }
  27842. this._activeMeshes.dispose();
  27843. this._renderingManager.dispose();
  27844. this._processedMaterials.dispose();
  27845. this._activeParticleSystems.dispose();
  27846. this._activeSkeletons.dispose();
  27847. this._softwareSkinnedMeshes.dispose();
  27848. this._renderTargets.dispose();
  27849. this._registeredForLateAnimationBindings.dispose();
  27850. if (this._boundingBoxRenderer) {
  27851. this._boundingBoxRenderer.dispose();
  27852. }
  27853. this._meshesForIntersections.dispose();
  27854. this._toBeDisposed.dispose();
  27855. // Abort active requests
  27856. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27857. var request = _a[_i];
  27858. request.abort();
  27859. }
  27860. // Debug layer
  27861. if (this._debugLayer) {
  27862. this._debugLayer.hide();
  27863. }
  27864. // Events
  27865. this.onDisposeObservable.notifyObservers(this);
  27866. this.onDisposeObservable.clear();
  27867. this.onBeforeRenderObservable.clear();
  27868. this.onAfterRenderObservable.clear();
  27869. this.onBeforeRenderTargetsRenderObservable.clear();
  27870. this.onAfterRenderTargetsRenderObservable.clear();
  27871. this.onAfterStepObservable.clear();
  27872. this.onBeforeStepObservable.clear();
  27873. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27874. this.onAfterActiveMeshesEvaluationObservable.clear();
  27875. this.onBeforeParticlesRenderingObservable.clear();
  27876. this.onAfterParticlesRenderingObservable.clear();
  27877. this.onBeforeSpritesRenderingObservable.clear();
  27878. this.onAfterSpritesRenderingObservable.clear();
  27879. this.onBeforeDrawPhaseObservable.clear();
  27880. this.onAfterDrawPhaseObservable.clear();
  27881. this.onBeforePhysicsObservable.clear();
  27882. this.onAfterPhysicsObservable.clear();
  27883. this.onBeforeAnimationsObservable.clear();
  27884. this.onAfterAnimationsObservable.clear();
  27885. this.onDataLoadedObservable.clear();
  27886. this.detachControl();
  27887. // Release sounds & sounds tracks
  27888. if (BABYLON.AudioEngine) {
  27889. this.disposeSounds();
  27890. }
  27891. // VR Helper
  27892. if (this.VRHelper) {
  27893. this.VRHelper.dispose();
  27894. }
  27895. // Detach cameras
  27896. var canvas = this._engine.getRenderingCanvas();
  27897. if (canvas) {
  27898. var index;
  27899. for (index = 0; index < this.cameras.length; index++) {
  27900. this.cameras[index].detachControl(canvas);
  27901. }
  27902. }
  27903. // Release animation groups
  27904. while (this.animationGroups.length) {
  27905. this.animationGroups[0].dispose();
  27906. }
  27907. // Release lights
  27908. while (this.lights.length) {
  27909. this.lights[0].dispose();
  27910. }
  27911. // Release meshes
  27912. while (this.meshes.length) {
  27913. this.meshes[0].dispose(true);
  27914. }
  27915. while (this.transformNodes.length) {
  27916. this.removeTransformNode(this.transformNodes[0]);
  27917. }
  27918. // Release cameras
  27919. while (this.cameras.length) {
  27920. this.cameras[0].dispose();
  27921. }
  27922. // Release materials
  27923. if (this.defaultMaterial) {
  27924. this.defaultMaterial.dispose();
  27925. }
  27926. while (this.multiMaterials.length) {
  27927. this.multiMaterials[0].dispose();
  27928. }
  27929. while (this.materials.length) {
  27930. this.materials[0].dispose();
  27931. }
  27932. // Release particles
  27933. while (this.particleSystems.length) {
  27934. this.particleSystems[0].dispose();
  27935. }
  27936. // Release sprites
  27937. while (this.spriteManagers.length) {
  27938. this.spriteManagers[0].dispose();
  27939. }
  27940. // Release postProcesses
  27941. while (this.postProcesses.length) {
  27942. this.postProcesses[0].dispose();
  27943. }
  27944. // Release layers
  27945. while (this.layers.length) {
  27946. this.layers[0].dispose();
  27947. }
  27948. while (this.effectLayers.length) {
  27949. this.effectLayers[0].dispose();
  27950. }
  27951. // Release textures
  27952. while (this.textures.length) {
  27953. this.textures[0].dispose();
  27954. }
  27955. // Release UBO
  27956. this._sceneUbo.dispose();
  27957. if (this._alternateSceneUbo) {
  27958. this._alternateSceneUbo.dispose();
  27959. }
  27960. // Post-processes
  27961. this.postProcessManager.dispose();
  27962. if (this._postProcessRenderPipelineManager) {
  27963. this._postProcessRenderPipelineManager.dispose();
  27964. }
  27965. // Physics
  27966. if (this._physicsEngine) {
  27967. this.disablePhysicsEngine();
  27968. }
  27969. // Remove from engine
  27970. index = this._engine.scenes.indexOf(this);
  27971. if (index > -1) {
  27972. this._engine.scenes.splice(index, 1);
  27973. }
  27974. this._engine.wipeCaches(true);
  27975. this._isDisposed = true;
  27976. };
  27977. Object.defineProperty(Scene.prototype, "isDisposed", {
  27978. /**
  27979. * Gets if the scene is already disposed
  27980. */
  27981. get: function () {
  27982. return this._isDisposed;
  27983. },
  27984. enumerable: true,
  27985. configurable: true
  27986. });
  27987. /**
  27988. * Releases sounds & soundtracks
  27989. */
  27990. Scene.prototype.disposeSounds = function () {
  27991. if (!this._mainSoundTrack) {
  27992. return;
  27993. }
  27994. this.mainSoundTrack.dispose();
  27995. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  27996. this.soundTracks[scIndex].dispose();
  27997. }
  27998. };
  27999. // Octrees
  28000. /**
  28001. * Get the world extend vectors with an optional filter
  28002. *
  28003. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28004. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28005. */
  28006. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28007. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28008. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28009. filterPredicate = filterPredicate || (function () { return true; });
  28010. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28011. mesh.computeWorldMatrix(true);
  28012. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28013. return;
  28014. }
  28015. var boundingInfo = mesh.getBoundingInfo();
  28016. var minBox = boundingInfo.boundingBox.minimumWorld;
  28017. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28018. BABYLON.Tools.CheckExtends(minBox, min, max);
  28019. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28020. });
  28021. return {
  28022. min: min,
  28023. max: max
  28024. };
  28025. };
  28026. /**
  28027. * Creates or updates the octree used to boost selection (picking)
  28028. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28029. * @param maxCapacity defines the maximum capacity per leaf
  28030. * @param maxDepth defines the maximum depth of the octree
  28031. * @returns an octree of AbstractMesh
  28032. */
  28033. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28034. if (maxCapacity === void 0) { maxCapacity = 64; }
  28035. if (maxDepth === void 0) { maxDepth = 2; }
  28036. if (!this._selectionOctree) {
  28037. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28038. }
  28039. var worldExtends = this.getWorldExtends();
  28040. // Update octree
  28041. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28042. return this._selectionOctree;
  28043. };
  28044. // Picking
  28045. /**
  28046. * Creates a ray that can be used to pick in the scene
  28047. * @param x defines the x coordinate of the origin (on-screen)
  28048. * @param y defines the y coordinate of the origin (on-screen)
  28049. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28050. * @param camera defines the camera to use for the picking
  28051. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28052. * @returns a Ray
  28053. */
  28054. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28055. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28056. var result = BABYLON.Ray.Zero();
  28057. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28058. return result;
  28059. };
  28060. /**
  28061. * Creates a ray that can be used to pick in the scene
  28062. * @param x defines the x coordinate of the origin (on-screen)
  28063. * @param y defines the y coordinate of the origin (on-screen)
  28064. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28065. * @param result defines the ray where to store the picking ray
  28066. * @param camera defines the camera to use for the picking
  28067. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28068. * @returns the current scene
  28069. */
  28070. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28071. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28072. var engine = this._engine;
  28073. if (!camera) {
  28074. if (!this.activeCamera)
  28075. throw new Error("Active camera not set");
  28076. camera = this.activeCamera;
  28077. }
  28078. var cameraViewport = camera.viewport;
  28079. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28080. // Moving coordinates to local viewport world
  28081. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28082. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28083. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28084. return this;
  28085. };
  28086. /**
  28087. * Creates a ray that can be used to pick in the scene
  28088. * @param x defines the x coordinate of the origin (on-screen)
  28089. * @param y defines the y coordinate of the origin (on-screen)
  28090. * @param camera defines the camera to use for the picking
  28091. * @returns a Ray
  28092. */
  28093. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28094. var result = BABYLON.Ray.Zero();
  28095. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28096. return result;
  28097. };
  28098. /**
  28099. * Creates a ray that can be used to pick in the scene
  28100. * @param x defines the x coordinate of the origin (on-screen)
  28101. * @param y defines the y coordinate of the origin (on-screen)
  28102. * @param result defines the ray where to store the picking ray
  28103. * @param camera defines the camera to use for the picking
  28104. * @returns the current scene
  28105. */
  28106. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28107. if (!BABYLON.PickingInfo) {
  28108. return this;
  28109. }
  28110. var engine = this._engine;
  28111. if (!camera) {
  28112. if (!this.activeCamera)
  28113. throw new Error("Active camera not set");
  28114. camera = this.activeCamera;
  28115. }
  28116. var cameraViewport = camera.viewport;
  28117. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28118. var identity = BABYLON.Matrix.Identity();
  28119. // Moving coordinates to local viewport world
  28120. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28121. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28122. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28123. return this;
  28124. };
  28125. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28126. if (!BABYLON.PickingInfo) {
  28127. return null;
  28128. }
  28129. var pickingInfo = null;
  28130. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28131. var mesh = this.meshes[meshIndex];
  28132. if (predicate) {
  28133. if (!predicate(mesh)) {
  28134. continue;
  28135. }
  28136. }
  28137. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28138. continue;
  28139. }
  28140. var world = mesh.getWorldMatrix();
  28141. var ray = rayFunction(world);
  28142. var result = mesh.intersects(ray, fastCheck);
  28143. if (!result || !result.hit)
  28144. continue;
  28145. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28146. continue;
  28147. pickingInfo = result;
  28148. if (fastCheck) {
  28149. break;
  28150. }
  28151. }
  28152. return pickingInfo || new BABYLON.PickingInfo();
  28153. };
  28154. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28155. if (!BABYLON.PickingInfo) {
  28156. return null;
  28157. }
  28158. var pickingInfos = new Array();
  28159. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28160. var mesh = this.meshes[meshIndex];
  28161. if (predicate) {
  28162. if (!predicate(mesh)) {
  28163. continue;
  28164. }
  28165. }
  28166. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28167. continue;
  28168. }
  28169. var world = mesh.getWorldMatrix();
  28170. var ray = rayFunction(world);
  28171. var result = mesh.intersects(ray, false);
  28172. if (!result || !result.hit)
  28173. continue;
  28174. pickingInfos.push(result);
  28175. }
  28176. return pickingInfos;
  28177. };
  28178. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28179. if (!BABYLON.PickingInfo) {
  28180. return null;
  28181. }
  28182. var pickingInfo = null;
  28183. if (!camera) {
  28184. if (!this.activeCamera) {
  28185. return null;
  28186. }
  28187. camera = this.activeCamera;
  28188. }
  28189. if (this.spriteManagers.length > 0) {
  28190. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28191. var spriteManager = this.spriteManagers[spriteIndex];
  28192. if (!spriteManager.isPickable) {
  28193. continue;
  28194. }
  28195. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28196. if (!result || !result.hit)
  28197. continue;
  28198. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28199. continue;
  28200. pickingInfo = result;
  28201. if (fastCheck) {
  28202. break;
  28203. }
  28204. }
  28205. }
  28206. return pickingInfo || new BABYLON.PickingInfo();
  28207. };
  28208. /** Launch a ray to try to pick a mesh in the scene
  28209. * @param x position on screen
  28210. * @param y position on screen
  28211. * @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
  28212. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28213. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28214. * @returns a PickingInfo
  28215. */
  28216. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28217. var _this = this;
  28218. if (!BABYLON.PickingInfo) {
  28219. return null;
  28220. }
  28221. return this._internalPick(function (world) {
  28222. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28223. return _this._tempPickingRay;
  28224. }, predicate, fastCheck);
  28225. };
  28226. /** Launch a ray to try to pick a sprite in the scene
  28227. * @param x position on screen
  28228. * @param y position on screen
  28229. * @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
  28230. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28231. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28232. * @returns a PickingInfo
  28233. */
  28234. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28235. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28236. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28237. };
  28238. /** Use the given ray to pick a mesh in the scene
  28239. * @param ray The ray to use to pick meshes
  28240. * @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
  28241. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28242. * @returns a PickingInfo
  28243. */
  28244. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28245. var _this = this;
  28246. return this._internalPick(function (world) {
  28247. if (!_this._pickWithRayInverseMatrix) {
  28248. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28249. }
  28250. world.invertToRef(_this._pickWithRayInverseMatrix);
  28251. if (!_this._cachedRayForTransform) {
  28252. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28253. }
  28254. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28255. return _this._cachedRayForTransform;
  28256. }, predicate, fastCheck);
  28257. };
  28258. /**
  28259. * Launch a ray to try to pick a mesh in the scene
  28260. * @param x X position on screen
  28261. * @param y Y position on screen
  28262. * @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
  28263. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28264. * @returns an array of PickingInfo
  28265. */
  28266. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28267. var _this = this;
  28268. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28269. };
  28270. /**
  28271. * Launch a ray to try to pick a mesh in the scene
  28272. * @param ray Ray to use
  28273. * @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
  28274. * @returns an array of PickingInfo
  28275. */
  28276. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28277. var _this = this;
  28278. return this._internalMultiPick(function (world) {
  28279. if (!_this._pickWithRayInverseMatrix) {
  28280. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28281. }
  28282. world.invertToRef(_this._pickWithRayInverseMatrix);
  28283. if (!_this._cachedRayForTransform) {
  28284. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28285. }
  28286. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28287. return _this._cachedRayForTransform;
  28288. }, predicate);
  28289. };
  28290. /**
  28291. * Force the value of meshUnderPointer
  28292. * @param mesh defines the mesh to use
  28293. */
  28294. Scene.prototype.setPointerOverMesh = function (mesh) {
  28295. if (this._pointerOverMesh === mesh) {
  28296. return;
  28297. }
  28298. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28299. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28300. }
  28301. this._pointerOverMesh = mesh;
  28302. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28303. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28304. }
  28305. };
  28306. /**
  28307. * Gets the mesh under the pointer
  28308. * @returns a Mesh or null if no mesh is under the pointer
  28309. */
  28310. Scene.prototype.getPointerOverMesh = function () {
  28311. return this._pointerOverMesh;
  28312. };
  28313. /**
  28314. * Force the sprite under the pointer
  28315. * @param sprite defines the sprite to use
  28316. */
  28317. Scene.prototype.setPointerOverSprite = function (sprite) {
  28318. if (this._pointerOverSprite === sprite) {
  28319. return;
  28320. }
  28321. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28322. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28323. }
  28324. this._pointerOverSprite = sprite;
  28325. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28326. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28327. }
  28328. };
  28329. /**
  28330. * Gets the sprite under the pointer
  28331. * @returns a Sprite or null if no sprite is under the pointer
  28332. */
  28333. Scene.prototype.getPointerOverSprite = function () {
  28334. return this._pointerOverSprite;
  28335. };
  28336. // Physics
  28337. /**
  28338. * Gets the current physics engine
  28339. * @returns a PhysicsEngine or null if none attached
  28340. */
  28341. Scene.prototype.getPhysicsEngine = function () {
  28342. return this._physicsEngine;
  28343. };
  28344. /**
  28345. * Enables physics to the current scene
  28346. * @param gravity defines the scene's gravity for the physics engine
  28347. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28348. * @return a boolean indicating if the physics engine was initialized
  28349. */
  28350. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28351. if (gravity === void 0) { gravity = null; }
  28352. if (this._physicsEngine) {
  28353. return true;
  28354. }
  28355. try {
  28356. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28357. return true;
  28358. }
  28359. catch (e) {
  28360. BABYLON.Tools.Error(e.message);
  28361. return false;
  28362. }
  28363. };
  28364. /**
  28365. * Disables and disposes the physics engine associated with the scene
  28366. */
  28367. Scene.prototype.disablePhysicsEngine = function () {
  28368. if (!this._physicsEngine) {
  28369. return;
  28370. }
  28371. this._physicsEngine.dispose();
  28372. this._physicsEngine = null;
  28373. };
  28374. /**
  28375. * Gets a boolean indicating if there is an active physics engine
  28376. * @returns a boolean indicating if there is an active physics engine
  28377. */
  28378. Scene.prototype.isPhysicsEnabled = function () {
  28379. return this._physicsEngine !== undefined;
  28380. };
  28381. /**
  28382. * Deletes a physics compound impostor
  28383. * @param compound defines the compound to delete
  28384. */
  28385. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28386. var mesh = compound.parts[0].mesh;
  28387. if (mesh.physicsImpostor) {
  28388. mesh.physicsImpostor.dispose( /*true*/);
  28389. mesh.physicsImpostor = null;
  28390. }
  28391. };
  28392. // Misc.
  28393. /** @hidden */
  28394. Scene.prototype._rebuildGeometries = function () {
  28395. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28396. var geometry = _a[_i];
  28397. geometry._rebuild();
  28398. }
  28399. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28400. var mesh = _c[_b];
  28401. mesh._rebuild();
  28402. }
  28403. if (this.postProcessManager) {
  28404. this.postProcessManager._rebuild();
  28405. }
  28406. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28407. var layer = _e[_d];
  28408. layer._rebuild();
  28409. }
  28410. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28411. var effectLayer = _g[_f];
  28412. effectLayer._rebuild();
  28413. }
  28414. if (this._boundingBoxRenderer) {
  28415. this._boundingBoxRenderer._rebuild();
  28416. }
  28417. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28418. var system = _j[_h];
  28419. system.rebuild();
  28420. }
  28421. if (this._postProcessRenderPipelineManager) {
  28422. this._postProcessRenderPipelineManager._rebuild();
  28423. }
  28424. };
  28425. /** @hidden */
  28426. Scene.prototype._rebuildTextures = function () {
  28427. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28428. var texture = _a[_i];
  28429. texture._rebuild();
  28430. }
  28431. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28432. };
  28433. /**
  28434. * Creates a default light for the scene.
  28435. * @param replace Whether to replace the existing lights in the scene.
  28436. */
  28437. Scene.prototype.createDefaultLight = function (replace) {
  28438. if (replace === void 0) { replace = false; }
  28439. // Dispose existing light in replace mode.
  28440. if (replace) {
  28441. if (this.lights) {
  28442. for (var i = 0; i < this.lights.length; i++) {
  28443. this.lights[i].dispose();
  28444. }
  28445. }
  28446. }
  28447. // Light
  28448. if (this.lights.length === 0) {
  28449. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28450. }
  28451. };
  28452. /**
  28453. * Creates a default camera for the scene.
  28454. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28455. * @param replace Whether to replace the existing active camera in the scene.
  28456. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28457. */
  28458. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28459. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28460. if (replace === void 0) { replace = false; }
  28461. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28462. // Dispose existing camera in replace mode.
  28463. if (replace) {
  28464. if (this.activeCamera) {
  28465. this.activeCamera.dispose();
  28466. this.activeCamera = null;
  28467. }
  28468. }
  28469. // Camera
  28470. if (!this.activeCamera) {
  28471. var worldExtends = this.getWorldExtends();
  28472. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28473. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28474. var camera;
  28475. var radius = worldSize.length() * 1.5;
  28476. // empty scene scenario!
  28477. if (!isFinite(radius)) {
  28478. radius = 1;
  28479. worldCenter.copyFromFloats(0, 0, 0);
  28480. }
  28481. if (createArcRotateCamera) {
  28482. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28483. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28484. arcRotateCamera.wheelPrecision = 100 / radius;
  28485. camera = arcRotateCamera;
  28486. }
  28487. else {
  28488. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28489. freeCamera.setTarget(worldCenter);
  28490. camera = freeCamera;
  28491. }
  28492. camera.minZ = radius * 0.01;
  28493. camera.maxZ = radius * 1000;
  28494. camera.speed = radius * 0.2;
  28495. this.activeCamera = camera;
  28496. var canvas = this.getEngine().getRenderingCanvas();
  28497. if (attachCameraControls && canvas) {
  28498. camera.attachControl(canvas);
  28499. }
  28500. }
  28501. };
  28502. /**
  28503. * Creates a default camera and a default light
  28504. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28505. * @param replace defines if the camera and/or light will replace the existing ones
  28506. * @param attachCameraControls defines if attachControl will be called on the new camera
  28507. */
  28508. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28509. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28510. if (replace === void 0) { replace = false; }
  28511. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28512. this.createDefaultLight(replace);
  28513. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28514. };
  28515. /**
  28516. * Creates a new sky box
  28517. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28518. * @param environmentTexture defines the texture to use as environment texture
  28519. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28520. * @param scale defines the overall scale of the skybox
  28521. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28522. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28523. * @returns a new mesh holding the sky box
  28524. */
  28525. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28526. if (pbr === void 0) { pbr = false; }
  28527. if (scale === void 0) { scale = 1000; }
  28528. if (blur === void 0) { blur = 0; }
  28529. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28530. if (!environmentTexture) {
  28531. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28532. return null;
  28533. }
  28534. if (setGlobalEnvTexture) {
  28535. if (environmentTexture) {
  28536. this.environmentTexture = environmentTexture;
  28537. }
  28538. }
  28539. // Skybox
  28540. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28541. if (pbr) {
  28542. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28543. hdrSkyboxMaterial.backFaceCulling = false;
  28544. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28545. if (hdrSkyboxMaterial.reflectionTexture) {
  28546. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28547. }
  28548. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28549. hdrSkyboxMaterial.disableLighting = true;
  28550. hdrSkyboxMaterial.twoSidedLighting = true;
  28551. hdrSkybox.infiniteDistance = true;
  28552. hdrSkybox.material = hdrSkyboxMaterial;
  28553. }
  28554. else {
  28555. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28556. skyboxMaterial.backFaceCulling = false;
  28557. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28558. if (skyboxMaterial.reflectionTexture) {
  28559. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28560. }
  28561. skyboxMaterial.disableLighting = true;
  28562. hdrSkybox.infiniteDistance = true;
  28563. hdrSkybox.material = skyboxMaterial;
  28564. }
  28565. return hdrSkybox;
  28566. };
  28567. /**
  28568. * Creates a new environment
  28569. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28570. * @param options defines the options you can use to configure the environment
  28571. * @returns the new EnvironmentHelper
  28572. */
  28573. Scene.prototype.createDefaultEnvironment = function (options) {
  28574. if (BABYLON.EnvironmentHelper) {
  28575. return new BABYLON.EnvironmentHelper(options, this);
  28576. }
  28577. return null;
  28578. };
  28579. /**
  28580. * Creates a new VREXperienceHelper
  28581. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28582. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28583. * @returns a new VREXperienceHelper
  28584. */
  28585. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28586. if (webVROptions === void 0) { webVROptions = {}; }
  28587. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28588. };
  28589. // Tags
  28590. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28591. if (tagsQuery === undefined) {
  28592. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28593. return list;
  28594. }
  28595. var listByTags = [];
  28596. forEach = forEach || (function (item) { return; });
  28597. for (var i in list) {
  28598. var item = list[i];
  28599. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28600. listByTags.push(item);
  28601. forEach(item);
  28602. }
  28603. }
  28604. return listByTags;
  28605. };
  28606. /**
  28607. * Get a list of meshes by tags
  28608. * @param tagsQuery defines the tags query to use
  28609. * @param forEach defines a predicate used to filter results
  28610. * @returns an array of Mesh
  28611. */
  28612. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28613. return this._getByTags(this.meshes, tagsQuery, forEach);
  28614. };
  28615. /**
  28616. * Get a list of cameras by tags
  28617. * @param tagsQuery defines the tags query to use
  28618. * @param forEach defines a predicate used to filter results
  28619. * @returns an array of Camera
  28620. */
  28621. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28622. return this._getByTags(this.cameras, tagsQuery, forEach);
  28623. };
  28624. /**
  28625. * Get a list of lights by tags
  28626. * @param tagsQuery defines the tags query to use
  28627. * @param forEach defines a predicate used to filter results
  28628. * @returns an array of Light
  28629. */
  28630. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28631. return this._getByTags(this.lights, tagsQuery, forEach);
  28632. };
  28633. /**
  28634. * Get a list of materials by tags
  28635. * @param tagsQuery defines the tags query to use
  28636. * @param forEach defines a predicate used to filter results
  28637. * @returns an array of Material
  28638. */
  28639. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28640. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28641. };
  28642. /**
  28643. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28644. * This allowed control for front to back rendering or reversly depending of the special needs.
  28645. *
  28646. * @param renderingGroupId The rendering group id corresponding to its index
  28647. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28648. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28649. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28650. */
  28651. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28652. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28653. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28654. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28655. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28656. };
  28657. /**
  28658. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28659. *
  28660. * @param renderingGroupId The rendering group id corresponding to its index
  28661. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28662. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28663. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28664. */
  28665. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28666. if (depth === void 0) { depth = true; }
  28667. if (stencil === void 0) { stencil = true; }
  28668. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28669. };
  28670. /**
  28671. * Will flag all materials as dirty to trigger new shader compilation
  28672. * @param flag defines the flag used to specify which material part must be marked as dirty
  28673. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28674. */
  28675. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28676. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28677. var material = _a[_i];
  28678. if (predicate && !predicate(material)) {
  28679. continue;
  28680. }
  28681. material.markAsDirty(flag);
  28682. }
  28683. };
  28684. /** @hidden */
  28685. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28686. var _this = this;
  28687. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28688. this._activeRequests.push(request);
  28689. request.onCompleteObservable.add(function (request) {
  28690. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28691. });
  28692. return request;
  28693. };
  28694. /** @hidden */
  28695. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28696. var _this = this;
  28697. return new Promise(function (resolve, reject) {
  28698. _this._loadFile(url, function (data) {
  28699. resolve(data);
  28700. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28701. reject(exception);
  28702. });
  28703. });
  28704. };
  28705. // Statics
  28706. Scene._FOGMODE_NONE = 0;
  28707. Scene._FOGMODE_EXP = 1;
  28708. Scene._FOGMODE_EXP2 = 2;
  28709. Scene._FOGMODE_LINEAR = 3;
  28710. Scene._uniqueIdCounter = 0;
  28711. /**
  28712. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28713. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28714. */
  28715. Scene.MinDeltaTime = 1.0;
  28716. /**
  28717. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28718. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28719. */
  28720. Scene.MaxDeltaTime = 1000.0;
  28721. /** The distance in pixel that you have to move to prevent some events */
  28722. Scene.DragMovementThreshold = 10; // in pixels
  28723. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28724. Scene.LongPressDelay = 500; // in milliseconds
  28725. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28726. Scene.DoubleClickDelay = 300; // in milliseconds
  28727. /** If you need to check double click without raising a single click at first click, enable this flag */
  28728. Scene.ExclusiveDoubleClickMode = false;
  28729. return Scene;
  28730. }());
  28731. BABYLON.Scene = Scene;
  28732. })(BABYLON || (BABYLON = {}));
  28733. //# sourceMappingURL=babylon.scene.js.map
  28734. var BABYLON;
  28735. (function (BABYLON) {
  28736. /**
  28737. * Set of assets to keep when moving a scene into an asset container.
  28738. */
  28739. var KeepAssets = /** @class */ (function () {
  28740. function KeepAssets() {
  28741. /**
  28742. * Cameras to keep.
  28743. */
  28744. this.cameras = new Array();
  28745. /**
  28746. * Lights to keep.
  28747. */
  28748. this.lights = new Array();
  28749. /**
  28750. * Meshes to keep.
  28751. */
  28752. this.meshes = new Array();
  28753. /**
  28754. * Skeletons to keep.
  28755. */
  28756. this.skeletons = new Array();
  28757. /**
  28758. * ParticleSystems to keep.
  28759. */
  28760. this.particleSystems = new Array();
  28761. /**
  28762. * Animations to keep.
  28763. */
  28764. this.animations = new Array();
  28765. /**
  28766. * AnimationGroups to keep.
  28767. */
  28768. this.animationGroups = new Array();
  28769. /**
  28770. * MultiMaterials to keep.
  28771. */
  28772. this.multiMaterials = new Array();
  28773. /**
  28774. * Materials to keep.
  28775. */
  28776. this.materials = new Array();
  28777. /**
  28778. * MorphTargetManagers to keep.
  28779. */
  28780. this.morphTargetManagers = new Array();
  28781. /**
  28782. * Geometries to keep.
  28783. */
  28784. this.geometries = new Array();
  28785. /**
  28786. * TransformNodes to keep.
  28787. */
  28788. this.transformNodes = new Array();
  28789. /**
  28790. * LensFlareSystems to keep.
  28791. */
  28792. this.lensFlareSystems = new Array();
  28793. /**
  28794. * ShadowGenerators to keep.
  28795. */
  28796. this.shadowGenerators = new Array();
  28797. /**
  28798. * ActionManagers to keep.
  28799. */
  28800. this.actionManagers = new Array();
  28801. /**
  28802. * Sounds to keep.
  28803. */
  28804. this.sounds = new Array();
  28805. /**
  28806. * Textures to keep.
  28807. */
  28808. this.textures = new Array();
  28809. /**
  28810. * Effect layers to keep.
  28811. */
  28812. this.effectLayers = new Array();
  28813. }
  28814. return KeepAssets;
  28815. }());
  28816. BABYLON.KeepAssets = KeepAssets;
  28817. /**
  28818. * Container with a set of assets that can be added or removed from a scene.
  28819. */
  28820. var AssetContainer = /** @class */ (function () {
  28821. /**
  28822. * Instantiates an AssetContainer.
  28823. * @param scene The scene the AssetContainer belongs to.
  28824. */
  28825. function AssetContainer(scene) {
  28826. // Objects
  28827. /**
  28828. * Cameras populated in the container.
  28829. */
  28830. this.cameras = new Array();
  28831. /**
  28832. * Lights populated in the container.
  28833. */
  28834. this.lights = new Array();
  28835. /**
  28836. * Meshes populated in the container.
  28837. */
  28838. this.meshes = new Array();
  28839. /**
  28840. * Skeletons populated in the container.
  28841. */
  28842. this.skeletons = new Array();
  28843. /**
  28844. * ParticleSystems populated in the container.
  28845. */
  28846. this.particleSystems = new Array();
  28847. /**
  28848. * Animations populated in the container.
  28849. */
  28850. this.animations = new Array();
  28851. /**
  28852. * AnimationGroups populated in the container.
  28853. */
  28854. this.animationGroups = new Array();
  28855. /**
  28856. * MultiMaterials populated in the container.
  28857. */
  28858. this.multiMaterials = new Array();
  28859. /**
  28860. * Materials populated in the container.
  28861. */
  28862. this.materials = new Array();
  28863. /**
  28864. * MorphTargetManagers populated in the container.
  28865. */
  28866. this.morphTargetManagers = new Array();
  28867. /**
  28868. * Geometries populated in the container.
  28869. */
  28870. this.geometries = new Array();
  28871. /**
  28872. * TransformNodes populated in the container.
  28873. */
  28874. this.transformNodes = new Array();
  28875. /**
  28876. * LensFlareSystems populated in the container.
  28877. */
  28878. this.lensFlareSystems = new Array();
  28879. /**
  28880. * ShadowGenerators populated in the container.
  28881. */
  28882. this.shadowGenerators = new Array();
  28883. /**
  28884. * ActionManagers populated in the container.
  28885. */
  28886. this.actionManagers = new Array();
  28887. /**
  28888. * Sounds populated in the container.
  28889. */
  28890. this.sounds = new Array();
  28891. /**
  28892. * Textures populated in the container.
  28893. */
  28894. this.textures = new Array();
  28895. /**
  28896. * Effect layers populated in the container.
  28897. */
  28898. this.effectLayers = new Array();
  28899. this.scene = scene;
  28900. }
  28901. /**
  28902. * Adds all the assets from the container to the scene.
  28903. */
  28904. AssetContainer.prototype.addAllToScene = function () {
  28905. var _this = this;
  28906. this.cameras.forEach(function (o) {
  28907. _this.scene.addCamera(o);
  28908. });
  28909. this.lights.forEach(function (o) {
  28910. _this.scene.addLight(o);
  28911. });
  28912. this.meshes.forEach(function (o) {
  28913. _this.scene.addMesh(o);
  28914. });
  28915. this.skeletons.forEach(function (o) {
  28916. _this.scene.addSkeleton(o);
  28917. });
  28918. this.particleSystems.forEach(function (o) {
  28919. _this.scene.addParticleSystem(o);
  28920. });
  28921. this.animations.forEach(function (o) {
  28922. _this.scene.addAnimation(o);
  28923. });
  28924. this.animationGroups.forEach(function (o) {
  28925. _this.scene.addAnimationGroup(o);
  28926. });
  28927. this.multiMaterials.forEach(function (o) {
  28928. _this.scene.addMultiMaterial(o);
  28929. });
  28930. this.materials.forEach(function (o) {
  28931. _this.scene.addMaterial(o);
  28932. });
  28933. this.morphTargetManagers.forEach(function (o) {
  28934. _this.scene.addMorphTargetManager(o);
  28935. });
  28936. this.geometries.forEach(function (o) {
  28937. _this.scene.addGeometry(o);
  28938. });
  28939. this.transformNodes.forEach(function (o) {
  28940. _this.scene.addTransformNode(o);
  28941. });
  28942. this.lensFlareSystems.forEach(function (o) {
  28943. _this.scene.addLensFlareSystem(o);
  28944. });
  28945. this.actionManagers.forEach(function (o) {
  28946. _this.scene.addActionManager(o);
  28947. });
  28948. this.sounds.forEach(function (o) {
  28949. o.play();
  28950. o.autoplay = true;
  28951. _this.scene.mainSoundTrack.AddSound(o);
  28952. });
  28953. this.textures.forEach(function (o) {
  28954. _this.scene.addTexture(o);
  28955. });
  28956. this.effectLayers.forEach(function (o) {
  28957. _this.scene.addEffectLayer(o);
  28958. });
  28959. };
  28960. /**
  28961. * Removes all the assets in the container from the scene
  28962. */
  28963. AssetContainer.prototype.removeAllFromScene = function () {
  28964. var _this = this;
  28965. this.cameras.forEach(function (o) {
  28966. _this.scene.removeCamera(o);
  28967. });
  28968. this.lights.forEach(function (o) {
  28969. _this.scene.removeLight(o);
  28970. });
  28971. this.meshes.forEach(function (o) {
  28972. _this.scene.removeMesh(o);
  28973. });
  28974. this.skeletons.forEach(function (o) {
  28975. _this.scene.removeSkeleton(o);
  28976. });
  28977. this.particleSystems.forEach(function (o) {
  28978. _this.scene.removeParticleSystem(o);
  28979. });
  28980. this.animations.forEach(function (o) {
  28981. _this.scene.removeAnimation(o);
  28982. });
  28983. this.animationGroups.forEach(function (o) {
  28984. _this.scene.removeAnimationGroup(o);
  28985. });
  28986. this.multiMaterials.forEach(function (o) {
  28987. _this.scene.removeMultiMaterial(o);
  28988. });
  28989. this.materials.forEach(function (o) {
  28990. _this.scene.removeMaterial(o);
  28991. });
  28992. this.morphTargetManagers.forEach(function (o) {
  28993. _this.scene.removeMorphTargetManager(o);
  28994. });
  28995. this.geometries.forEach(function (o) {
  28996. _this.scene.removeGeometry(o);
  28997. });
  28998. this.transformNodes.forEach(function (o) {
  28999. _this.scene.removeTransformNode(o);
  29000. });
  29001. this.lensFlareSystems.forEach(function (o) {
  29002. _this.scene.removeLensFlareSystem(o);
  29003. });
  29004. this.actionManagers.forEach(function (o) {
  29005. _this.scene.removeActionManager(o);
  29006. });
  29007. this.sounds.forEach(function (o) {
  29008. o.stop();
  29009. o.autoplay = false;
  29010. _this.scene.mainSoundTrack.RemoveSound(o);
  29011. });
  29012. this.textures.forEach(function (o) {
  29013. _this.scene.removeTexture(o);
  29014. });
  29015. this.effectLayers.forEach(function (o) {
  29016. _this.scene.removeEffectLayer(o);
  29017. });
  29018. };
  29019. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29020. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29021. var asset = sourceAssets_1[_i];
  29022. var move = true;
  29023. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29024. var keepAsset = keepAssets_1[_a];
  29025. if (asset === keepAsset) {
  29026. move = false;
  29027. break;
  29028. }
  29029. }
  29030. if (move) {
  29031. targetAssets.push(asset);
  29032. }
  29033. }
  29034. };
  29035. /**
  29036. * Removes all the assets contained in the scene and adds them to the container.
  29037. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29038. */
  29039. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29040. if (keepAssets === undefined) {
  29041. keepAssets = new KeepAssets();
  29042. }
  29043. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29044. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29045. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29046. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29047. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29048. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29049. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29050. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29051. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29052. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29053. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29054. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29055. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29056. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29057. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29058. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29059. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29060. this.removeAllFromScene();
  29061. };
  29062. return AssetContainer;
  29063. }());
  29064. BABYLON.AssetContainer = AssetContainer;
  29065. })(BABYLON || (BABYLON = {}));
  29066. //# sourceMappingURL=babylon.assetContainer.js.map
  29067. var BABYLON;
  29068. (function (BABYLON) {
  29069. var Buffer = /** @class */ (function () {
  29070. /**
  29071. * Constructor
  29072. * @param engine the engine
  29073. * @param data the data to use for this buffer
  29074. * @param updatable whether the data is updatable
  29075. * @param stride the stride (optional)
  29076. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29077. * @param instanced whether the buffer is instanced (optional)
  29078. * @param useBytes set to true if the stride in in bytes (optional)
  29079. */
  29080. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29081. if (stride === void 0) { stride = 0; }
  29082. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29083. if (instanced === void 0) { instanced = false; }
  29084. if (useBytes === void 0) { useBytes = false; }
  29085. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29086. this._engine = engine.getScene().getEngine();
  29087. }
  29088. else {
  29089. this._engine = engine;
  29090. }
  29091. this._updatable = updatable;
  29092. this._instanced = instanced;
  29093. this._data = data;
  29094. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29095. if (!postponeInternalCreation) { // by default
  29096. this.create();
  29097. }
  29098. }
  29099. /**
  29100. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29101. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29102. * @param offset defines offset in the buffer (0 by default)
  29103. * @param size defines the size in floats of attributes (position is 3 for instance)
  29104. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29105. * @param instanced defines if the vertex buffer contains indexed data
  29106. * @param useBytes defines if the offset and stride are in bytes
  29107. * @returns the new vertex buffer
  29108. */
  29109. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29110. if (useBytes === void 0) { useBytes = false; }
  29111. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29112. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29113. // a lot of these parameters are ignored as they are overriden by the buffer
  29114. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29115. };
  29116. // Properties
  29117. Buffer.prototype.isUpdatable = function () {
  29118. return this._updatable;
  29119. };
  29120. Buffer.prototype.getData = function () {
  29121. return this._data;
  29122. };
  29123. Buffer.prototype.getBuffer = function () {
  29124. return this._buffer;
  29125. };
  29126. /**
  29127. * Gets the stride in float32 units (i.e. byte stride / 4).
  29128. * May not be an integer if the byte stride is not divisible by 4.
  29129. * DEPRECATED. Use byteStride instead.
  29130. * @returns the stride in float32 units
  29131. */
  29132. Buffer.prototype.getStrideSize = function () {
  29133. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29134. };
  29135. // Methods
  29136. Buffer.prototype.create = function (data) {
  29137. if (data === void 0) { data = null; }
  29138. if (!data && this._buffer) {
  29139. return; // nothing to do
  29140. }
  29141. data = data || this._data;
  29142. if (!data) {
  29143. return;
  29144. }
  29145. if (!this._buffer) { // create buffer
  29146. if (this._updatable) {
  29147. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29148. this._data = data;
  29149. }
  29150. else {
  29151. this._buffer = this._engine.createVertexBuffer(data);
  29152. }
  29153. }
  29154. else if (this._updatable) { // update buffer
  29155. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29156. this._data = data;
  29157. }
  29158. };
  29159. Buffer.prototype._rebuild = function () {
  29160. this._buffer = null;
  29161. this.create(this._data);
  29162. };
  29163. Buffer.prototype.update = function (data) {
  29164. this.create(data);
  29165. };
  29166. /**
  29167. * Updates the data directly.
  29168. * @param data the new data
  29169. * @param offset the new offset
  29170. * @param vertexCount the vertex count (optional)
  29171. * @param useBytes set to true if the offset is in bytes
  29172. */
  29173. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29174. if (useBytes === void 0) { useBytes = false; }
  29175. if (!this._buffer) {
  29176. return;
  29177. }
  29178. if (this._updatable) { // update buffer
  29179. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29180. this._data = null;
  29181. }
  29182. };
  29183. Buffer.prototype.dispose = function () {
  29184. if (!this._buffer) {
  29185. return;
  29186. }
  29187. if (this._engine._releaseBuffer(this._buffer)) {
  29188. this._buffer = null;
  29189. }
  29190. };
  29191. return Buffer;
  29192. }());
  29193. BABYLON.Buffer = Buffer;
  29194. })(BABYLON || (BABYLON = {}));
  29195. //# sourceMappingURL=babylon.buffer.js.map
  29196. var BABYLON;
  29197. (function (BABYLON) {
  29198. var VertexBuffer = /** @class */ (function () {
  29199. /**
  29200. * Constructor
  29201. * @param engine the engine
  29202. * @param data the data to use for this vertex buffer
  29203. * @param kind the vertex buffer kind
  29204. * @param updatable whether the data is updatable
  29205. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29206. * @param stride the stride (optional)
  29207. * @param instanced whether the buffer is instanced (optional)
  29208. * @param offset the offset of the data (optional)
  29209. * @param size the number of components (optional)
  29210. * @param type the type of the component (optional)
  29211. * @param normalized whether the data contains normalized data (optional)
  29212. * @param useBytes set to true if stride and offset are in bytes (optional)
  29213. */
  29214. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29215. if (normalized === void 0) { normalized = false; }
  29216. if (useBytes === void 0) { useBytes = false; }
  29217. if (data instanceof BABYLON.Buffer) {
  29218. this._buffer = data;
  29219. this._ownsBuffer = false;
  29220. }
  29221. else {
  29222. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29223. this._ownsBuffer = true;
  29224. }
  29225. this._kind = kind;
  29226. if (type == undefined) {
  29227. var data_1 = this.getData();
  29228. this.type = VertexBuffer.FLOAT;
  29229. if (data_1 instanceof Int8Array)
  29230. this.type = VertexBuffer.BYTE;
  29231. else if (data_1 instanceof Uint8Array)
  29232. this.type = VertexBuffer.UNSIGNED_BYTE;
  29233. else if (data_1 instanceof Int16Array)
  29234. this.type = VertexBuffer.SHORT;
  29235. else if (data_1 instanceof Uint16Array)
  29236. this.type = VertexBuffer.UNSIGNED_SHORT;
  29237. else if (data_1 instanceof Int32Array)
  29238. this.type = VertexBuffer.INT;
  29239. else if (data_1 instanceof Uint32Array)
  29240. this.type = VertexBuffer.UNSIGNED_INT;
  29241. }
  29242. else {
  29243. this.type = type;
  29244. }
  29245. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29246. if (useBytes) {
  29247. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29248. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29249. this.byteOffset = offset || 0;
  29250. }
  29251. else {
  29252. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29253. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29254. this.byteOffset = (offset || 0) * typeByteLength;
  29255. }
  29256. this.normalized = normalized;
  29257. this._instanced = instanced !== undefined ? instanced : false;
  29258. this._instanceDivisor = instanced ? 1 : 0;
  29259. }
  29260. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29261. /**
  29262. * Gets or sets the instance divisor when in instanced mode
  29263. */
  29264. get: function () {
  29265. return this._instanceDivisor;
  29266. },
  29267. set: function (value) {
  29268. this._instanceDivisor = value;
  29269. if (value == 0) {
  29270. this._instanced = false;
  29271. }
  29272. else {
  29273. this._instanced = true;
  29274. }
  29275. },
  29276. enumerable: true,
  29277. configurable: true
  29278. });
  29279. VertexBuffer.prototype._rebuild = function () {
  29280. if (!this._buffer) {
  29281. return;
  29282. }
  29283. this._buffer._rebuild();
  29284. };
  29285. /**
  29286. * Returns the kind of the VertexBuffer (string).
  29287. */
  29288. VertexBuffer.prototype.getKind = function () {
  29289. return this._kind;
  29290. };
  29291. // Properties
  29292. /**
  29293. * Boolean : is the VertexBuffer updatable ?
  29294. */
  29295. VertexBuffer.prototype.isUpdatable = function () {
  29296. return this._buffer.isUpdatable();
  29297. };
  29298. /**
  29299. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29300. */
  29301. VertexBuffer.prototype.getData = function () {
  29302. return this._buffer.getData();
  29303. };
  29304. /**
  29305. * Returns the WebGLBuffer associated to the VertexBuffer.
  29306. */
  29307. VertexBuffer.prototype.getBuffer = function () {
  29308. return this._buffer.getBuffer();
  29309. };
  29310. /**
  29311. * Returns the stride as a multiple of the type byte length.
  29312. * DEPRECATED. Use byteStride instead.
  29313. */
  29314. VertexBuffer.prototype.getStrideSize = function () {
  29315. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29316. };
  29317. /**
  29318. * Returns the offset as a multiple of the type byte length.
  29319. * DEPRECATED. Use byteOffset instead.
  29320. */
  29321. VertexBuffer.prototype.getOffset = function () {
  29322. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29323. };
  29324. /**
  29325. * Returns the number of components per vertex attribute (integer).
  29326. */
  29327. VertexBuffer.prototype.getSize = function () {
  29328. return this._size;
  29329. };
  29330. /**
  29331. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29332. */
  29333. VertexBuffer.prototype.getIsInstanced = function () {
  29334. return this._instanced;
  29335. };
  29336. /**
  29337. * Returns the instancing divisor, zero for non-instanced (integer).
  29338. */
  29339. VertexBuffer.prototype.getInstanceDivisor = function () {
  29340. return this._instanceDivisor;
  29341. };
  29342. // Methods
  29343. /**
  29344. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29345. * Returns the created WebGLBuffer.
  29346. */
  29347. VertexBuffer.prototype.create = function (data) {
  29348. return this._buffer.create(data);
  29349. };
  29350. /**
  29351. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29352. * This function will create a new buffer if the current one is not updatable
  29353. * Returns the updated WebGLBuffer.
  29354. */
  29355. VertexBuffer.prototype.update = function (data) {
  29356. return this._buffer.update(data);
  29357. };
  29358. /**
  29359. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29360. * Returns the directly updated WebGLBuffer.
  29361. * @param data the new data
  29362. * @param offset the new offset
  29363. * @param useBytes set to true if the offset is in bytes
  29364. */
  29365. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29366. if (useBytes === void 0) { useBytes = false; }
  29367. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29368. };
  29369. /**
  29370. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29371. */
  29372. VertexBuffer.prototype.dispose = function () {
  29373. if (this._ownsBuffer) {
  29374. this._buffer.dispose();
  29375. }
  29376. };
  29377. /**
  29378. * Enumerates each value of this vertex buffer as numbers.
  29379. * @param count the number of values to enumerate
  29380. * @param callback the callback function called for each value
  29381. */
  29382. VertexBuffer.prototype.forEach = function (count, callback) {
  29383. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29384. };
  29385. Object.defineProperty(VertexBuffer, "PositionKind", {
  29386. get: function () {
  29387. return VertexBuffer._PositionKind;
  29388. },
  29389. enumerable: true,
  29390. configurable: true
  29391. });
  29392. Object.defineProperty(VertexBuffer, "NormalKind", {
  29393. get: function () {
  29394. return VertexBuffer._NormalKind;
  29395. },
  29396. enumerable: true,
  29397. configurable: true
  29398. });
  29399. Object.defineProperty(VertexBuffer, "TangentKind", {
  29400. get: function () {
  29401. return VertexBuffer._TangentKind;
  29402. },
  29403. enumerable: true,
  29404. configurable: true
  29405. });
  29406. Object.defineProperty(VertexBuffer, "UVKind", {
  29407. get: function () {
  29408. return VertexBuffer._UVKind;
  29409. },
  29410. enumerable: true,
  29411. configurable: true
  29412. });
  29413. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29414. get: function () {
  29415. return VertexBuffer._UV2Kind;
  29416. },
  29417. enumerable: true,
  29418. configurable: true
  29419. });
  29420. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29421. get: function () {
  29422. return VertexBuffer._UV3Kind;
  29423. },
  29424. enumerable: true,
  29425. configurable: true
  29426. });
  29427. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29428. get: function () {
  29429. return VertexBuffer._UV4Kind;
  29430. },
  29431. enumerable: true,
  29432. configurable: true
  29433. });
  29434. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29435. get: function () {
  29436. return VertexBuffer._UV5Kind;
  29437. },
  29438. enumerable: true,
  29439. configurable: true
  29440. });
  29441. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29442. get: function () {
  29443. return VertexBuffer._UV6Kind;
  29444. },
  29445. enumerable: true,
  29446. configurable: true
  29447. });
  29448. Object.defineProperty(VertexBuffer, "ColorKind", {
  29449. get: function () {
  29450. return VertexBuffer._ColorKind;
  29451. },
  29452. enumerable: true,
  29453. configurable: true
  29454. });
  29455. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29456. get: function () {
  29457. return VertexBuffer._MatricesIndicesKind;
  29458. },
  29459. enumerable: true,
  29460. configurable: true
  29461. });
  29462. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29463. get: function () {
  29464. return VertexBuffer._MatricesWeightsKind;
  29465. },
  29466. enumerable: true,
  29467. configurable: true
  29468. });
  29469. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29470. get: function () {
  29471. return VertexBuffer._MatricesIndicesExtraKind;
  29472. },
  29473. enumerable: true,
  29474. configurable: true
  29475. });
  29476. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29477. get: function () {
  29478. return VertexBuffer._MatricesWeightsExtraKind;
  29479. },
  29480. enumerable: true,
  29481. configurable: true
  29482. });
  29483. /**
  29484. * Deduces the stride given a kind.
  29485. * @param kind The kind string to deduce
  29486. * @returns The deduced stride
  29487. */
  29488. VertexBuffer.DeduceStride = function (kind) {
  29489. switch (kind) {
  29490. case VertexBuffer.UVKind:
  29491. case VertexBuffer.UV2Kind:
  29492. case VertexBuffer.UV3Kind:
  29493. case VertexBuffer.UV4Kind:
  29494. case VertexBuffer.UV5Kind:
  29495. case VertexBuffer.UV6Kind:
  29496. return 2;
  29497. case VertexBuffer.NormalKind:
  29498. case VertexBuffer.PositionKind:
  29499. return 3;
  29500. case VertexBuffer.ColorKind:
  29501. case VertexBuffer.MatricesIndicesKind:
  29502. case VertexBuffer.MatricesIndicesExtraKind:
  29503. case VertexBuffer.MatricesWeightsKind:
  29504. case VertexBuffer.MatricesWeightsExtraKind:
  29505. case VertexBuffer.TangentKind:
  29506. return 4;
  29507. default:
  29508. throw new Error("Invalid kind '" + kind + "'");
  29509. }
  29510. };
  29511. /**
  29512. * Gets the byte length of the given type.
  29513. * @param type the type
  29514. * @returns the number of bytes
  29515. */
  29516. VertexBuffer.GetTypeByteLength = function (type) {
  29517. switch (type) {
  29518. case VertexBuffer.BYTE:
  29519. case VertexBuffer.UNSIGNED_BYTE:
  29520. return 1;
  29521. case VertexBuffer.SHORT:
  29522. case VertexBuffer.UNSIGNED_SHORT:
  29523. return 2;
  29524. case VertexBuffer.INT:
  29525. case VertexBuffer.FLOAT:
  29526. return 4;
  29527. default:
  29528. throw new Error("Invalid type '" + type + "'");
  29529. }
  29530. };
  29531. /**
  29532. * Enumerates each value of the given parameters as numbers.
  29533. * @param data the data to enumerate
  29534. * @param byteOffset the byte offset of the data
  29535. * @param byteStride the byte stride of the data
  29536. * @param componentCount the number of components per element
  29537. * @param componentType the type of the component
  29538. * @param count the total number of components
  29539. * @param normalized whether the data is normalized
  29540. * @param callback the callback function called for each value
  29541. */
  29542. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29543. if (data instanceof Array) {
  29544. var offset = byteOffset / 4;
  29545. var stride = byteStride / 4;
  29546. for (var index = 0; index < count; index += componentCount) {
  29547. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29548. callback(data[offset + componentIndex], index + componentIndex);
  29549. }
  29550. offset += stride;
  29551. }
  29552. }
  29553. else {
  29554. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29555. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29556. for (var index = 0; index < count; index += componentCount) {
  29557. var componentByteOffset = byteOffset;
  29558. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29559. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29560. callback(value, index + componentIndex);
  29561. componentByteOffset += componentByteLength;
  29562. }
  29563. byteOffset += byteStride;
  29564. }
  29565. }
  29566. };
  29567. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29568. switch (type) {
  29569. case VertexBuffer.BYTE: {
  29570. var value = dataView.getInt8(byteOffset);
  29571. if (normalized) {
  29572. value = (value + 0.5) / 127.5;
  29573. }
  29574. return value;
  29575. }
  29576. case VertexBuffer.UNSIGNED_BYTE: {
  29577. var value = dataView.getUint8(byteOffset);
  29578. if (normalized) {
  29579. value = value / 255;
  29580. }
  29581. return value;
  29582. }
  29583. case VertexBuffer.SHORT: {
  29584. var value = dataView.getInt16(byteOffset, true);
  29585. if (normalized) {
  29586. value = (value + 0.5) / 16383.5;
  29587. }
  29588. return value;
  29589. }
  29590. case VertexBuffer.UNSIGNED_SHORT: {
  29591. var value = dataView.getUint16(byteOffset, true);
  29592. if (normalized) {
  29593. value = value / 65535;
  29594. }
  29595. return value;
  29596. }
  29597. case VertexBuffer.FLOAT: {
  29598. return dataView.getFloat32(byteOffset, true);
  29599. }
  29600. default: {
  29601. throw new Error("Invalid component type " + type);
  29602. }
  29603. }
  29604. };
  29605. /**
  29606. * The byte type.
  29607. */
  29608. VertexBuffer.BYTE = 5120;
  29609. /**
  29610. * The unsigned byte type.
  29611. */
  29612. VertexBuffer.UNSIGNED_BYTE = 5121;
  29613. /**
  29614. * The short type.
  29615. */
  29616. VertexBuffer.SHORT = 5122;
  29617. /**
  29618. * The unsigned short type.
  29619. */
  29620. VertexBuffer.UNSIGNED_SHORT = 5123;
  29621. /**
  29622. * The integer type.
  29623. */
  29624. VertexBuffer.INT = 5124;
  29625. /**
  29626. * The unsigned integer type.
  29627. */
  29628. VertexBuffer.UNSIGNED_INT = 5125;
  29629. /**
  29630. * The float type.
  29631. */
  29632. VertexBuffer.FLOAT = 5126;
  29633. // Enums
  29634. VertexBuffer._PositionKind = "position";
  29635. VertexBuffer._NormalKind = "normal";
  29636. VertexBuffer._TangentKind = "tangent";
  29637. VertexBuffer._UVKind = "uv";
  29638. VertexBuffer._UV2Kind = "uv2";
  29639. VertexBuffer._UV3Kind = "uv3";
  29640. VertexBuffer._UV4Kind = "uv4";
  29641. VertexBuffer._UV5Kind = "uv5";
  29642. VertexBuffer._UV6Kind = "uv6";
  29643. VertexBuffer._ColorKind = "color";
  29644. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29645. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29646. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29647. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29648. return VertexBuffer;
  29649. }());
  29650. BABYLON.VertexBuffer = VertexBuffer;
  29651. })(BABYLON || (BABYLON = {}));
  29652. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29653. var BABYLON;
  29654. (function (BABYLON) {
  29655. /**
  29656. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29657. */
  29658. var DummyInternalTextureTracker = /** @class */ (function () {
  29659. function DummyInternalTextureTracker() {
  29660. /**
  29661. * Gets or set the previous tracker in the list
  29662. */
  29663. this.previous = null;
  29664. /**
  29665. * Gets or set the next tracker in the list
  29666. */
  29667. this.next = null;
  29668. }
  29669. return DummyInternalTextureTracker;
  29670. }());
  29671. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29672. })(BABYLON || (BABYLON = {}));
  29673. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29674. var BABYLON;
  29675. (function (BABYLON) {
  29676. /**
  29677. * Class used to store data associated with WebGL texture data for the engine
  29678. * This class should not be used directly
  29679. */
  29680. var InternalTexture = /** @class */ (function () {
  29681. /**
  29682. * Creates a new InternalTexture
  29683. * @param engine defines the engine to use
  29684. * @param dataSource defines the type of data that will be used
  29685. */
  29686. function InternalTexture(engine, dataSource) {
  29687. /**
  29688. * Observable called when the texture is loaded
  29689. */
  29690. this.onLoadedObservable = new BABYLON.Observable();
  29691. /**
  29692. * Gets or set the previous tracker in the list
  29693. */
  29694. this.previous = null;
  29695. /**
  29696. * Gets or set the next tracker in the list
  29697. */
  29698. this.next = null;
  29699. // Private
  29700. /** @hidden */
  29701. this._initialSlot = -1;
  29702. /** @hidden */
  29703. this._designatedSlot = -1;
  29704. /** @hidden */
  29705. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29706. /** @hidden */
  29707. this._comparisonFunction = 0;
  29708. /** @hidden */
  29709. this._references = 1;
  29710. this._engine = engine;
  29711. this._dataSource = dataSource;
  29712. this._webGLTexture = engine._createTexture();
  29713. }
  29714. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29715. /**
  29716. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29717. */
  29718. get: function () {
  29719. return this._dataSource;
  29720. },
  29721. enumerable: true,
  29722. configurable: true
  29723. });
  29724. /**
  29725. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29726. */
  29727. InternalTexture.prototype.incrementReferences = function () {
  29728. this._references++;
  29729. };
  29730. /**
  29731. * Change the size of the texture (not the size of the content)
  29732. * @param width defines the new width
  29733. * @param height defines the new height
  29734. * @param depth defines the new depth (1 by default)
  29735. */
  29736. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29737. if (depth === void 0) { depth = 1; }
  29738. this.width = width;
  29739. this.height = height;
  29740. this.depth = depth;
  29741. this.baseWidth = width;
  29742. this.baseHeight = height;
  29743. this.baseDepth = depth;
  29744. this._size = width * height * depth;
  29745. };
  29746. /** @hidden */
  29747. InternalTexture.prototype._rebuild = function () {
  29748. var _this = this;
  29749. var proxy;
  29750. this.isReady = false;
  29751. this._cachedCoordinatesMode = null;
  29752. this._cachedWrapU = null;
  29753. this._cachedWrapV = null;
  29754. this._cachedAnisotropicFilteringLevel = null;
  29755. switch (this._dataSource) {
  29756. case InternalTexture.DATASOURCE_TEMP:
  29757. return;
  29758. case InternalTexture.DATASOURCE_URL:
  29759. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29760. _this.isReady = true;
  29761. }, null, this._buffer, undefined, this.format);
  29762. proxy._swapAndDie(this);
  29763. return;
  29764. case InternalTexture.DATASOURCE_RAW:
  29765. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29766. proxy._swapAndDie(this);
  29767. this.isReady = true;
  29768. return;
  29769. case InternalTexture.DATASOURCE_RAW3D:
  29770. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29771. proxy._swapAndDie(this);
  29772. this.isReady = true;
  29773. return;
  29774. case InternalTexture.DATASOURCE_DYNAMIC:
  29775. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29776. proxy._swapAndDie(this);
  29777. // The engine will make sure to update content so no need to flag it as isReady = true
  29778. return;
  29779. case InternalTexture.DATASOURCE_RENDERTARGET:
  29780. var options = new BABYLON.RenderTargetCreationOptions();
  29781. options.generateDepthBuffer = this._generateDepthBuffer;
  29782. options.generateMipMaps = this.generateMipMaps;
  29783. options.generateStencilBuffer = this._generateStencilBuffer;
  29784. options.samplingMode = this.samplingMode;
  29785. options.type = this.type;
  29786. if (this.isCube) {
  29787. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29788. }
  29789. else {
  29790. var size = {
  29791. width: this.width,
  29792. height: this.height
  29793. };
  29794. proxy = this._engine.createRenderTargetTexture(size, options);
  29795. }
  29796. proxy._swapAndDie(this);
  29797. this.isReady = true;
  29798. return;
  29799. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29800. var depthTextureOptions = {
  29801. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29802. comparisonFunction: this._comparisonFunction,
  29803. generateStencil: this._generateStencilBuffer,
  29804. isCube: this.isCube
  29805. };
  29806. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29807. proxy._swapAndDie(this);
  29808. this.isReady = true;
  29809. return;
  29810. case InternalTexture.DATASOURCE_CUBE:
  29811. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29812. _this.isReady = true;
  29813. }, null, this.format, this._extension);
  29814. proxy._swapAndDie(this);
  29815. return;
  29816. case InternalTexture.DATASOURCE_CUBERAW:
  29817. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29818. proxy._swapAndDie(this);
  29819. this.isReady = true;
  29820. return;
  29821. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29822. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29823. if (proxy) {
  29824. proxy._swapAndDie(_this);
  29825. }
  29826. _this.isReady = true;
  29827. }, null, this.format, this._extension);
  29828. return;
  29829. }
  29830. };
  29831. InternalTexture.prototype._swapAndDie = function (target) {
  29832. target._webGLTexture = this._webGLTexture;
  29833. if (this._framebuffer) {
  29834. target._framebuffer = this._framebuffer;
  29835. }
  29836. if (this._depthStencilBuffer) {
  29837. target._depthStencilBuffer = this._depthStencilBuffer;
  29838. }
  29839. if (this._lodTextureHigh) {
  29840. if (target._lodTextureHigh) {
  29841. target._lodTextureHigh.dispose();
  29842. }
  29843. target._lodTextureHigh = this._lodTextureHigh;
  29844. }
  29845. if (this._lodTextureMid) {
  29846. if (target._lodTextureMid) {
  29847. target._lodTextureMid.dispose();
  29848. }
  29849. target._lodTextureMid = this._lodTextureMid;
  29850. }
  29851. if (this._lodTextureLow) {
  29852. if (target._lodTextureLow) {
  29853. target._lodTextureLow.dispose();
  29854. }
  29855. target._lodTextureLow = this._lodTextureLow;
  29856. }
  29857. var cache = this._engine.getLoadedTexturesCache();
  29858. var index = cache.indexOf(this);
  29859. if (index !== -1) {
  29860. cache.splice(index, 1);
  29861. }
  29862. };
  29863. /**
  29864. * Dispose the current allocated resources
  29865. */
  29866. InternalTexture.prototype.dispose = function () {
  29867. if (!this._webGLTexture) {
  29868. return;
  29869. }
  29870. this._references--;
  29871. if (this._references === 0) {
  29872. this._engine._releaseTexture(this);
  29873. this._webGLTexture = null;
  29874. this.previous = null;
  29875. this.next = null;
  29876. }
  29877. };
  29878. /**
  29879. * The source of the texture data is unknown
  29880. */
  29881. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29882. /**
  29883. * Texture data comes from an URL
  29884. */
  29885. InternalTexture.DATASOURCE_URL = 1;
  29886. /**
  29887. * Texture data is only used for temporary storage
  29888. */
  29889. InternalTexture.DATASOURCE_TEMP = 2;
  29890. /**
  29891. * Texture data comes from raw data (ArrayBuffer)
  29892. */
  29893. InternalTexture.DATASOURCE_RAW = 3;
  29894. /**
  29895. * Texture content is dynamic (video or dynamic texture)
  29896. */
  29897. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29898. /**
  29899. * Texture content is generated by rendering to it
  29900. */
  29901. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29902. /**
  29903. * Texture content is part of a multi render target process
  29904. */
  29905. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29906. /**
  29907. * Texture data comes from a cube data file
  29908. */
  29909. InternalTexture.DATASOURCE_CUBE = 7;
  29910. /**
  29911. * Texture data comes from a raw cube data
  29912. */
  29913. InternalTexture.DATASOURCE_CUBERAW = 8;
  29914. /**
  29915. * Texture data come from a prefiltered cube data file
  29916. */
  29917. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29918. /**
  29919. * Texture content is raw 3D data
  29920. */
  29921. InternalTexture.DATASOURCE_RAW3D = 10;
  29922. /**
  29923. * Texture content is a depth texture
  29924. */
  29925. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  29926. return InternalTexture;
  29927. }());
  29928. BABYLON.InternalTexture = InternalTexture;
  29929. })(BABYLON || (BABYLON = {}));
  29930. //# sourceMappingURL=babylon.internalTexture.js.map
  29931. var BABYLON;
  29932. (function (BABYLON) {
  29933. var BaseTexture = /** @class */ (function () {
  29934. function BaseTexture(scene) {
  29935. this._hasAlpha = false;
  29936. this.getAlphaFromRGB = false;
  29937. this.level = 1;
  29938. this.coordinatesIndex = 0;
  29939. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  29940. /**
  29941. * | Value | Type | Description |
  29942. * | ----- | ------------------ | ----------- |
  29943. * | 0 | CLAMP_ADDRESSMODE | |
  29944. * | 1 | WRAP_ADDRESSMODE | |
  29945. * | 2 | MIRROR_ADDRESSMODE | |
  29946. */
  29947. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29948. /**
  29949. * | Value | Type | Description |
  29950. * | ----- | ------------------ | ----------- |
  29951. * | 0 | CLAMP_ADDRESSMODE | |
  29952. * | 1 | WRAP_ADDRESSMODE | |
  29953. * | 2 | MIRROR_ADDRESSMODE | |
  29954. */
  29955. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29956. /**
  29957. * | Value | Type | Description |
  29958. * | ----- | ------------------ | ----------- |
  29959. * | 0 | CLAMP_ADDRESSMODE | |
  29960. * | 1 | WRAP_ADDRESSMODE | |
  29961. * | 2 | MIRROR_ADDRESSMODE | |
  29962. */
  29963. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  29964. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  29965. this.isCube = false;
  29966. this.is3D = false;
  29967. this.gammaSpace = true;
  29968. this.invertZ = false;
  29969. this.lodLevelInAlpha = false;
  29970. this.lodGenerationOffset = 0.0;
  29971. this.lodGenerationScale = 0.8;
  29972. this.isRenderTarget = false;
  29973. this.animations = new Array();
  29974. /**
  29975. * An event triggered when the texture is disposed.
  29976. */
  29977. this.onDisposeObservable = new BABYLON.Observable();
  29978. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  29979. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  29980. if (this._scene) {
  29981. this._scene.textures.push(this);
  29982. }
  29983. this._uid = null;
  29984. }
  29985. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  29986. get: function () {
  29987. return this._hasAlpha;
  29988. },
  29989. set: function (value) {
  29990. if (this._hasAlpha === value) {
  29991. return;
  29992. }
  29993. this._hasAlpha = value;
  29994. if (this._scene) {
  29995. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  29996. }
  29997. },
  29998. enumerable: true,
  29999. configurable: true
  30000. });
  30001. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30002. get: function () {
  30003. return this._coordinatesMode;
  30004. },
  30005. /**
  30006. * How a texture is mapped.
  30007. *
  30008. * | Value | Type | Description |
  30009. * | ----- | ----------------------------------- | ----------- |
  30010. * | 0 | EXPLICIT_MODE | |
  30011. * | 1 | SPHERICAL_MODE | |
  30012. * | 2 | PLANAR_MODE | |
  30013. * | 3 | CUBIC_MODE | |
  30014. * | 4 | PROJECTION_MODE | |
  30015. * | 5 | SKYBOX_MODE | |
  30016. * | 6 | INVCUBIC_MODE | |
  30017. * | 7 | EQUIRECTANGULAR_MODE | |
  30018. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30019. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30020. */
  30021. set: function (value) {
  30022. if (this._coordinatesMode === value) {
  30023. return;
  30024. }
  30025. this._coordinatesMode = value;
  30026. if (this._scene) {
  30027. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30028. }
  30029. },
  30030. enumerable: true,
  30031. configurable: true
  30032. });
  30033. Object.defineProperty(BaseTexture.prototype, "uid", {
  30034. get: function () {
  30035. if (!this._uid) {
  30036. this._uid = BABYLON.Tools.RandomId();
  30037. }
  30038. return this._uid;
  30039. },
  30040. enumerable: true,
  30041. configurable: true
  30042. });
  30043. BaseTexture.prototype.toString = function () {
  30044. return this.name;
  30045. };
  30046. BaseTexture.prototype.getClassName = function () {
  30047. return "BaseTexture";
  30048. };
  30049. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30050. set: function (callback) {
  30051. if (this._onDisposeObserver) {
  30052. this.onDisposeObservable.remove(this._onDisposeObserver);
  30053. }
  30054. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30055. },
  30056. enumerable: true,
  30057. configurable: true
  30058. });
  30059. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30060. get: function () {
  30061. return true;
  30062. },
  30063. enumerable: true,
  30064. configurable: true
  30065. });
  30066. BaseTexture.prototype.getScene = function () {
  30067. return this._scene;
  30068. };
  30069. BaseTexture.prototype.getTextureMatrix = function () {
  30070. return BABYLON.Matrix.IdentityReadOnly;
  30071. };
  30072. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30073. return BABYLON.Matrix.IdentityReadOnly;
  30074. };
  30075. BaseTexture.prototype.getInternalTexture = function () {
  30076. return this._texture;
  30077. };
  30078. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30079. return !this.isBlocking || this.isReady();
  30080. };
  30081. BaseTexture.prototype.isReady = function () {
  30082. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30083. this.delayLoad();
  30084. return false;
  30085. }
  30086. if (this._texture) {
  30087. return this._texture.isReady;
  30088. }
  30089. return false;
  30090. };
  30091. BaseTexture.prototype.getSize = function () {
  30092. if (this._texture && this._texture.width) {
  30093. return new BABYLON.Size(this._texture.width, this._texture.height);
  30094. }
  30095. if (this._texture && this._texture._size) {
  30096. return new BABYLON.Size(this._texture._size, this._texture._size);
  30097. }
  30098. return BABYLON.Size.Zero();
  30099. };
  30100. BaseTexture.prototype.getBaseSize = function () {
  30101. if (!this.isReady() || !this._texture)
  30102. return BABYLON.Size.Zero();
  30103. if (this._texture._size) {
  30104. return new BABYLON.Size(this._texture._size, this._texture._size);
  30105. }
  30106. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30107. };
  30108. BaseTexture.prototype.scale = function (ratio) {
  30109. };
  30110. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30111. get: function () {
  30112. return false;
  30113. },
  30114. enumerable: true,
  30115. configurable: true
  30116. });
  30117. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30118. if (!this._scene) {
  30119. return null;
  30120. }
  30121. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30122. for (var index = 0; index < texturesCache.length; index++) {
  30123. var texturesCacheEntry = texturesCache[index];
  30124. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30125. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30126. texturesCacheEntry.incrementReferences();
  30127. return texturesCacheEntry;
  30128. }
  30129. }
  30130. }
  30131. return null;
  30132. };
  30133. BaseTexture.prototype._rebuild = function () {
  30134. };
  30135. BaseTexture.prototype.delayLoad = function () {
  30136. };
  30137. BaseTexture.prototype.clone = function () {
  30138. return null;
  30139. };
  30140. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30141. get: function () {
  30142. if (!this._texture) {
  30143. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30144. }
  30145. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30146. },
  30147. enumerable: true,
  30148. configurable: true
  30149. });
  30150. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30151. get: function () {
  30152. if (!this._texture) {
  30153. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30154. }
  30155. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30156. },
  30157. enumerable: true,
  30158. configurable: true
  30159. });
  30160. BaseTexture.prototype.readPixels = function (faceIndex) {
  30161. if (faceIndex === void 0) { faceIndex = 0; }
  30162. if (!this._texture) {
  30163. return null;
  30164. }
  30165. var size = this.getSize();
  30166. var scene = this.getScene();
  30167. if (!scene) {
  30168. return null;
  30169. }
  30170. var engine = scene.getEngine();
  30171. if (this._texture.isCube) {
  30172. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30173. }
  30174. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30175. };
  30176. BaseTexture.prototype.releaseInternalTexture = function () {
  30177. if (this._texture) {
  30178. this._texture.dispose();
  30179. this._texture = null;
  30180. }
  30181. };
  30182. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30183. get: function () {
  30184. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30185. return null;
  30186. }
  30187. if (!this._texture._sphericalPolynomial) {
  30188. this._texture._sphericalPolynomial =
  30189. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30190. }
  30191. return this._texture._sphericalPolynomial;
  30192. },
  30193. set: function (value) {
  30194. if (this._texture) {
  30195. this._texture._sphericalPolynomial = value;
  30196. }
  30197. },
  30198. enumerable: true,
  30199. configurable: true
  30200. });
  30201. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30202. get: function () {
  30203. if (this._texture) {
  30204. return this._texture._lodTextureHigh;
  30205. }
  30206. return null;
  30207. },
  30208. enumerable: true,
  30209. configurable: true
  30210. });
  30211. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30212. get: function () {
  30213. if (this._texture) {
  30214. return this._texture._lodTextureMid;
  30215. }
  30216. return null;
  30217. },
  30218. enumerable: true,
  30219. configurable: true
  30220. });
  30221. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30222. get: function () {
  30223. if (this._texture) {
  30224. return this._texture._lodTextureLow;
  30225. }
  30226. return null;
  30227. },
  30228. enumerable: true,
  30229. configurable: true
  30230. });
  30231. BaseTexture.prototype.dispose = function () {
  30232. if (!this._scene) {
  30233. return;
  30234. }
  30235. // Animations
  30236. this._scene.stopAnimation(this);
  30237. // Remove from scene
  30238. this._scene._removePendingData(this);
  30239. var index = this._scene.textures.indexOf(this);
  30240. if (index >= 0) {
  30241. this._scene.textures.splice(index, 1);
  30242. }
  30243. if (this._texture === undefined) {
  30244. return;
  30245. }
  30246. // Release
  30247. this.releaseInternalTexture();
  30248. // Callback
  30249. this.onDisposeObservable.notifyObservers(this);
  30250. this.onDisposeObservable.clear();
  30251. };
  30252. BaseTexture.prototype.serialize = function () {
  30253. if (!this.name) {
  30254. return null;
  30255. }
  30256. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30257. // Animations
  30258. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30259. return serializationObject;
  30260. };
  30261. BaseTexture.WhenAllReady = function (textures, callback) {
  30262. var numRemaining = textures.length;
  30263. if (numRemaining === 0) {
  30264. callback();
  30265. return;
  30266. }
  30267. var _loop_1 = function () {
  30268. texture = textures[i];
  30269. if (texture.isReady()) {
  30270. if (--numRemaining === 0) {
  30271. callback();
  30272. }
  30273. }
  30274. else {
  30275. onLoadObservable = texture.onLoadObservable;
  30276. var onLoadCallback_1 = function () {
  30277. onLoadObservable.removeCallback(onLoadCallback_1);
  30278. if (--numRemaining === 0) {
  30279. callback();
  30280. }
  30281. };
  30282. onLoadObservable.add(onLoadCallback_1);
  30283. }
  30284. };
  30285. var texture, onLoadObservable;
  30286. for (var i = 0; i < textures.length; i++) {
  30287. _loop_1();
  30288. }
  30289. };
  30290. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30291. __decorate([
  30292. BABYLON.serialize()
  30293. ], BaseTexture.prototype, "name", void 0);
  30294. __decorate([
  30295. BABYLON.serialize("hasAlpha")
  30296. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30297. __decorate([
  30298. BABYLON.serialize()
  30299. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30300. __decorate([
  30301. BABYLON.serialize()
  30302. ], BaseTexture.prototype, "level", void 0);
  30303. __decorate([
  30304. BABYLON.serialize()
  30305. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30306. __decorate([
  30307. BABYLON.serialize("coordinatesMode")
  30308. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30309. __decorate([
  30310. BABYLON.serialize()
  30311. ], BaseTexture.prototype, "wrapU", void 0);
  30312. __decorate([
  30313. BABYLON.serialize()
  30314. ], BaseTexture.prototype, "wrapV", void 0);
  30315. __decorate([
  30316. BABYLON.serialize()
  30317. ], BaseTexture.prototype, "wrapR", void 0);
  30318. __decorate([
  30319. BABYLON.serialize()
  30320. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30321. __decorate([
  30322. BABYLON.serialize()
  30323. ], BaseTexture.prototype, "isCube", void 0);
  30324. __decorate([
  30325. BABYLON.serialize()
  30326. ], BaseTexture.prototype, "is3D", void 0);
  30327. __decorate([
  30328. BABYLON.serialize()
  30329. ], BaseTexture.prototype, "gammaSpace", void 0);
  30330. __decorate([
  30331. BABYLON.serialize()
  30332. ], BaseTexture.prototype, "invertZ", void 0);
  30333. __decorate([
  30334. BABYLON.serialize()
  30335. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30336. __decorate([
  30337. BABYLON.serialize()
  30338. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30339. __decorate([
  30340. BABYLON.serialize()
  30341. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30342. __decorate([
  30343. BABYLON.serialize()
  30344. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30345. return BaseTexture;
  30346. }());
  30347. BABYLON.BaseTexture = BaseTexture;
  30348. })(BABYLON || (BABYLON = {}));
  30349. //# sourceMappingURL=babylon.baseTexture.js.map
  30350. var BABYLON;
  30351. (function (BABYLON) {
  30352. var Texture = /** @class */ (function (_super) {
  30353. __extends(Texture, _super);
  30354. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30355. if (noMipmap === void 0) { noMipmap = false; }
  30356. if (invertY === void 0) { invertY = true; }
  30357. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30358. if (onLoad === void 0) { onLoad = null; }
  30359. if (onError === void 0) { onError = null; }
  30360. if (buffer === void 0) { buffer = null; }
  30361. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30362. var _this = _super.call(this, scene) || this;
  30363. _this.uOffset = 0;
  30364. _this.vOffset = 0;
  30365. _this.uScale = 1.0;
  30366. _this.vScale = 1.0;
  30367. _this.uAng = 0;
  30368. _this.vAng = 0;
  30369. _this.wAng = 0;
  30370. _this._isBlocking = true;
  30371. _this.name = url || "";
  30372. _this.url = url;
  30373. _this._noMipmap = noMipmap;
  30374. _this._invertY = invertY;
  30375. _this._samplingMode = samplingMode;
  30376. _this._buffer = buffer;
  30377. _this._deleteBuffer = deleteBuffer;
  30378. if (format) {
  30379. _this._format = format;
  30380. }
  30381. scene = _this.getScene();
  30382. if (!scene) {
  30383. return _this;
  30384. }
  30385. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30386. var load = function () {
  30387. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30388. _this.onLoadObservable.notifyObservers(_this);
  30389. }
  30390. if (onLoad) {
  30391. onLoad();
  30392. }
  30393. if (!_this.isBlocking && scene) {
  30394. scene.resetCachedMaterial();
  30395. }
  30396. };
  30397. if (!_this.url) {
  30398. _this._delayedOnLoad = load;
  30399. _this._delayedOnError = onError;
  30400. return _this;
  30401. }
  30402. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30403. if (!_this._texture) {
  30404. if (!scene.useDelayedTextureLoading) {
  30405. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30406. if (deleteBuffer) {
  30407. delete _this._buffer;
  30408. }
  30409. }
  30410. else {
  30411. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30412. _this._delayedOnLoad = load;
  30413. _this._delayedOnError = onError;
  30414. }
  30415. }
  30416. else {
  30417. if (_this._texture.isReady) {
  30418. BABYLON.Tools.SetImmediate(function () { return load(); });
  30419. }
  30420. else {
  30421. _this._texture.onLoadedObservable.add(load);
  30422. }
  30423. }
  30424. return _this;
  30425. }
  30426. Object.defineProperty(Texture.prototype, "noMipmap", {
  30427. get: function () {
  30428. return this._noMipmap;
  30429. },
  30430. enumerable: true,
  30431. configurable: true
  30432. });
  30433. Object.defineProperty(Texture.prototype, "isBlocking", {
  30434. get: function () {
  30435. return this._isBlocking;
  30436. },
  30437. set: function (value) {
  30438. this._isBlocking = value;
  30439. },
  30440. enumerable: true,
  30441. configurable: true
  30442. });
  30443. Object.defineProperty(Texture.prototype, "samplingMode", {
  30444. get: function () {
  30445. return this._samplingMode;
  30446. },
  30447. enumerable: true,
  30448. configurable: true
  30449. });
  30450. Texture.prototype.updateURL = function (url) {
  30451. this.url = url;
  30452. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30453. this.delayLoad();
  30454. };
  30455. Texture.prototype.delayLoad = function () {
  30456. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30457. return;
  30458. }
  30459. var scene = this.getScene();
  30460. if (!scene) {
  30461. return;
  30462. }
  30463. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30464. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30465. if (!this._texture) {
  30466. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30467. if (this._deleteBuffer) {
  30468. delete this._buffer;
  30469. }
  30470. }
  30471. else {
  30472. if (this._delayedOnLoad) {
  30473. if (this._texture.isReady) {
  30474. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30475. }
  30476. else {
  30477. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30478. }
  30479. }
  30480. }
  30481. this._delayedOnLoad = null;
  30482. this._delayedOnError = null;
  30483. };
  30484. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30485. if (!this._texture) {
  30486. return;
  30487. }
  30488. var scene = this.getScene();
  30489. if (!scene) {
  30490. return;
  30491. }
  30492. this._samplingMode = samplingMode;
  30493. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30494. };
  30495. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30496. x *= this.uScale;
  30497. y *= this.vScale;
  30498. x -= 0.5 * this.uScale;
  30499. y -= 0.5 * this.vScale;
  30500. z -= 0.5;
  30501. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30502. t.x += 0.5 * this.uScale + this.uOffset;
  30503. t.y += 0.5 * this.vScale + this.vOffset;
  30504. t.z += 0.5;
  30505. };
  30506. Texture.prototype.getTextureMatrix = function () {
  30507. var _this = this;
  30508. if (this.uOffset === this._cachedUOffset &&
  30509. this.vOffset === this._cachedVOffset &&
  30510. this.uScale === this._cachedUScale &&
  30511. this.vScale === this._cachedVScale &&
  30512. this.uAng === this._cachedUAng &&
  30513. this.vAng === this._cachedVAng &&
  30514. this.wAng === this._cachedWAng) {
  30515. return this._cachedTextureMatrix;
  30516. }
  30517. this._cachedUOffset = this.uOffset;
  30518. this._cachedVOffset = this.vOffset;
  30519. this._cachedUScale = this.uScale;
  30520. this._cachedVScale = this.vScale;
  30521. this._cachedUAng = this.uAng;
  30522. this._cachedVAng = this.vAng;
  30523. this._cachedWAng = this.wAng;
  30524. if (!this._cachedTextureMatrix) {
  30525. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30526. this._rowGenerationMatrix = new BABYLON.Matrix();
  30527. this._t0 = BABYLON.Vector3.Zero();
  30528. this._t1 = BABYLON.Vector3.Zero();
  30529. this._t2 = BABYLON.Vector3.Zero();
  30530. }
  30531. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30532. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30533. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30534. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30535. this._t1.subtractInPlace(this._t0);
  30536. this._t2.subtractInPlace(this._t0);
  30537. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30538. this._cachedTextureMatrix.m[0] = this._t1.x;
  30539. this._cachedTextureMatrix.m[1] = this._t1.y;
  30540. this._cachedTextureMatrix.m[2] = this._t1.z;
  30541. this._cachedTextureMatrix.m[4] = this._t2.x;
  30542. this._cachedTextureMatrix.m[5] = this._t2.y;
  30543. this._cachedTextureMatrix.m[6] = this._t2.z;
  30544. this._cachedTextureMatrix.m[8] = this._t0.x;
  30545. this._cachedTextureMatrix.m[9] = this._t0.y;
  30546. this._cachedTextureMatrix.m[10] = this._t0.z;
  30547. var scene = this.getScene();
  30548. if (!scene) {
  30549. return this._cachedTextureMatrix;
  30550. }
  30551. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30552. return mat.hasTexture(_this);
  30553. });
  30554. return this._cachedTextureMatrix;
  30555. };
  30556. Texture.prototype.getReflectionTextureMatrix = function () {
  30557. var _this = this;
  30558. var scene = this.getScene();
  30559. if (!scene) {
  30560. return this._cachedTextureMatrix;
  30561. }
  30562. if (this.uOffset === this._cachedUOffset &&
  30563. this.vOffset === this._cachedVOffset &&
  30564. this.uScale === this._cachedUScale &&
  30565. this.vScale === this._cachedVScale &&
  30566. this.coordinatesMode === this._cachedCoordinatesMode) {
  30567. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30568. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30569. return this._cachedTextureMatrix;
  30570. }
  30571. }
  30572. else {
  30573. return this._cachedTextureMatrix;
  30574. }
  30575. }
  30576. if (!this._cachedTextureMatrix) {
  30577. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30578. }
  30579. if (!this._projectionModeMatrix) {
  30580. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30581. }
  30582. this._cachedUOffset = this.uOffset;
  30583. this._cachedVOffset = this.vOffset;
  30584. this._cachedUScale = this.uScale;
  30585. this._cachedVScale = this.vScale;
  30586. this._cachedCoordinatesMode = this.coordinatesMode;
  30587. switch (this.coordinatesMode) {
  30588. case Texture.PLANAR_MODE:
  30589. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30590. this._cachedTextureMatrix[0] = this.uScale;
  30591. this._cachedTextureMatrix[5] = this.vScale;
  30592. this._cachedTextureMatrix[12] = this.uOffset;
  30593. this._cachedTextureMatrix[13] = this.vOffset;
  30594. break;
  30595. case Texture.PROJECTION_MODE:
  30596. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30597. this._projectionModeMatrix.m[0] = 0.5;
  30598. this._projectionModeMatrix.m[5] = -0.5;
  30599. this._projectionModeMatrix.m[10] = 0.0;
  30600. this._projectionModeMatrix.m[12] = 0.5;
  30601. this._projectionModeMatrix.m[13] = 0.5;
  30602. this._projectionModeMatrix.m[14] = 1.0;
  30603. this._projectionModeMatrix.m[15] = 1.0;
  30604. var projectionMatrix = scene.getProjectionMatrix();
  30605. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30606. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30607. break;
  30608. default:
  30609. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30610. break;
  30611. }
  30612. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30613. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30614. });
  30615. return this._cachedTextureMatrix;
  30616. };
  30617. Texture.prototype.clone = function () {
  30618. var _this = this;
  30619. return BABYLON.SerializationHelper.Clone(function () {
  30620. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30621. }, this);
  30622. };
  30623. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30624. get: function () {
  30625. if (!this._onLoadObservable) {
  30626. this._onLoadObservable = new BABYLON.Observable();
  30627. }
  30628. return this._onLoadObservable;
  30629. },
  30630. enumerable: true,
  30631. configurable: true
  30632. });
  30633. Texture.prototype.serialize = function () {
  30634. var serializationObject = _super.prototype.serialize.call(this);
  30635. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30636. serializationObject.base64String = this._buffer;
  30637. serializationObject.name = serializationObject.name.replace("data:", "");
  30638. }
  30639. serializationObject.invertY = this._invertY;
  30640. serializationObject.samplingMode = this.samplingMode;
  30641. return serializationObject;
  30642. };
  30643. Texture.prototype.getClassName = function () {
  30644. return "Texture";
  30645. };
  30646. Texture.prototype.dispose = function () {
  30647. _super.prototype.dispose.call(this);
  30648. if (this.onLoadObservable) {
  30649. this.onLoadObservable.clear();
  30650. this._onLoadObservable = null;
  30651. }
  30652. this._delayedOnLoad = null;
  30653. this._delayedOnError = null;
  30654. };
  30655. // Statics
  30656. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30657. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30658. if (onLoad === void 0) { onLoad = null; }
  30659. if (onError === void 0) { onError = null; }
  30660. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30661. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30662. };
  30663. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30664. if (parsedTexture.customType) {
  30665. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30666. // Update Sampling Mode
  30667. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30668. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30669. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30670. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30671. }
  30672. }
  30673. return parsedCustomTexture;
  30674. }
  30675. if (parsedTexture.isCube) {
  30676. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30677. }
  30678. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30679. return null;
  30680. }
  30681. var texture = BABYLON.SerializationHelper.Parse(function () {
  30682. var generateMipMaps = true;
  30683. if (parsedTexture.noMipmap) {
  30684. generateMipMaps = false;
  30685. }
  30686. if (parsedTexture.mirrorPlane) {
  30687. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30688. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30689. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30690. return mirrorTexture;
  30691. }
  30692. else if (parsedTexture.isRenderTarget) {
  30693. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30694. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30695. return renderTargetTexture;
  30696. }
  30697. else {
  30698. var texture;
  30699. if (parsedTexture.base64String) {
  30700. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30701. }
  30702. else {
  30703. var url = rootUrl + parsedTexture.name;
  30704. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30705. url = parsedTexture.url;
  30706. }
  30707. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30708. }
  30709. return texture;
  30710. }
  30711. }, parsedTexture, scene);
  30712. // Update Sampling Mode
  30713. if (parsedTexture.samplingMode) {
  30714. var sampling = parsedTexture.samplingMode;
  30715. if (texture._samplingMode !== sampling) {
  30716. texture.updateSamplingMode(sampling);
  30717. }
  30718. }
  30719. // Animations
  30720. if (parsedTexture.animations) {
  30721. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30722. var parsedAnimation = parsedTexture.animations[animationIndex];
  30723. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30724. }
  30725. }
  30726. return texture;
  30727. };
  30728. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30729. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30730. if (noMipmap === void 0) { noMipmap = false; }
  30731. if (invertY === void 0) { invertY = true; }
  30732. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30733. if (onLoad === void 0) { onLoad = null; }
  30734. if (onError === void 0) { onError = null; }
  30735. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30736. if (name.substr(0, 5) !== "data:") {
  30737. name = "data:" + name;
  30738. }
  30739. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30740. };
  30741. // Constants
  30742. Texture.NEAREST_SAMPLINGMODE = 1;
  30743. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30744. Texture.BILINEAR_SAMPLINGMODE = 2;
  30745. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30746. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30747. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30748. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30749. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30750. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30751. Texture.NEAREST_LINEAR = 7;
  30752. Texture.NEAREST_NEAREST = 8;
  30753. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30754. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30755. Texture.LINEAR_LINEAR = 11;
  30756. Texture.LINEAR_NEAREST = 12;
  30757. Texture.EXPLICIT_MODE = 0;
  30758. Texture.SPHERICAL_MODE = 1;
  30759. Texture.PLANAR_MODE = 2;
  30760. Texture.CUBIC_MODE = 3;
  30761. Texture.PROJECTION_MODE = 4;
  30762. Texture.SKYBOX_MODE = 5;
  30763. Texture.INVCUBIC_MODE = 6;
  30764. Texture.EQUIRECTANGULAR_MODE = 7;
  30765. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30766. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30767. Texture.CLAMP_ADDRESSMODE = 0;
  30768. Texture.WRAP_ADDRESSMODE = 1;
  30769. Texture.MIRROR_ADDRESSMODE = 2;
  30770. /**
  30771. * 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
  30772. */
  30773. Texture.UseSerializedUrlIfAny = false;
  30774. __decorate([
  30775. BABYLON.serialize()
  30776. ], Texture.prototype, "url", void 0);
  30777. __decorate([
  30778. BABYLON.serialize()
  30779. ], Texture.prototype, "uOffset", void 0);
  30780. __decorate([
  30781. BABYLON.serialize()
  30782. ], Texture.prototype, "vOffset", void 0);
  30783. __decorate([
  30784. BABYLON.serialize()
  30785. ], Texture.prototype, "uScale", void 0);
  30786. __decorate([
  30787. BABYLON.serialize()
  30788. ], Texture.prototype, "vScale", void 0);
  30789. __decorate([
  30790. BABYLON.serialize()
  30791. ], Texture.prototype, "uAng", void 0);
  30792. __decorate([
  30793. BABYLON.serialize()
  30794. ], Texture.prototype, "vAng", void 0);
  30795. __decorate([
  30796. BABYLON.serialize()
  30797. ], Texture.prototype, "wAng", void 0);
  30798. __decorate([
  30799. BABYLON.serialize()
  30800. ], Texture.prototype, "isBlocking", null);
  30801. return Texture;
  30802. }(BABYLON.BaseTexture));
  30803. BABYLON.Texture = Texture;
  30804. })(BABYLON || (BABYLON = {}));
  30805. //# sourceMappingURL=babylon.texture.js.map
  30806. var BABYLON;
  30807. (function (BABYLON) {
  30808. /**
  30809. * @hidden
  30810. **/
  30811. var _InstancesBatch = /** @class */ (function () {
  30812. function _InstancesBatch() {
  30813. this.mustReturn = false;
  30814. this.visibleInstances = new Array();
  30815. this.renderSelf = new Array();
  30816. }
  30817. return _InstancesBatch;
  30818. }());
  30819. BABYLON._InstancesBatch = _InstancesBatch;
  30820. var Mesh = /** @class */ (function (_super) {
  30821. __extends(Mesh, _super);
  30822. /**
  30823. * @constructor
  30824. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30825. * @param {Scene} scene The scene to add this mesh to.
  30826. * @param {Node} parent The parent of this mesh, if it has one
  30827. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30828. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30829. * When false, achieved by calling a clone(), also passing False.
  30830. * This will make creation of children, recursive.
  30831. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30832. */
  30833. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30834. if (scene === void 0) { scene = null; }
  30835. if (parent === void 0) { parent = null; }
  30836. if (source === void 0) { source = null; }
  30837. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30838. var _this = _super.call(this, name, scene) || this;
  30839. // Events
  30840. /**
  30841. * An event triggered before rendering the mesh
  30842. */
  30843. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30844. /**
  30845. * An event triggered after rendering the mesh
  30846. */
  30847. _this.onAfterRenderObservable = new BABYLON.Observable();
  30848. /**
  30849. * An event triggered before drawing the mesh
  30850. */
  30851. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30852. // Members
  30853. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30854. _this.instances = new Array();
  30855. _this._LODLevels = new Array();
  30856. _this._visibleInstances = {};
  30857. _this._renderIdForInstances = new Array();
  30858. _this._batchCache = new _InstancesBatch();
  30859. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30860. // Use by builder only to know what orientation were the mesh build in.
  30861. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30862. _this.overrideMaterialSideOrientation = null;
  30863. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30864. // Will be used to save a source mesh reference, If any
  30865. _this._source = null;
  30866. scene = _this.getScene();
  30867. if (source) {
  30868. // Source mesh
  30869. _this._source = source;
  30870. // Geometry
  30871. if (source._geometry) {
  30872. source._geometry.applyToMesh(_this);
  30873. }
  30874. // Deep copy
  30875. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30876. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30877. // Metadata
  30878. if (source.metadata && source.metadata.clone) {
  30879. _this.metadata = source.metadata.clone();
  30880. }
  30881. else {
  30882. _this.metadata = source.metadata;
  30883. }
  30884. // Tags
  30885. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30886. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30887. }
  30888. // Parent
  30889. _this.parent = source.parent;
  30890. // Pivot
  30891. _this.setPivotMatrix(source.getPivotMatrix());
  30892. _this.id = name + "." + source.id;
  30893. // Material
  30894. _this.material = source.material;
  30895. var index;
  30896. if (!doNotCloneChildren) {
  30897. // Children
  30898. var directDescendants = source.getDescendants(true);
  30899. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30900. var child = directDescendants[index_1];
  30901. if (child.clone) {
  30902. child.clone(name + "." + child.name, _this);
  30903. }
  30904. }
  30905. }
  30906. // Physics clone
  30907. var physicsEngine = _this.getScene().getPhysicsEngine();
  30908. if (clonePhysicsImpostor && physicsEngine) {
  30909. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30910. if (impostor) {
  30911. _this.physicsImpostor = impostor.clone(_this);
  30912. }
  30913. }
  30914. // Particles
  30915. for (index = 0; index < scene.particleSystems.length; index++) {
  30916. var system = scene.particleSystems[index];
  30917. if (system.emitter === source) {
  30918. system.clone(system.name, _this);
  30919. }
  30920. }
  30921. _this.computeWorldMatrix(true);
  30922. }
  30923. // Parent
  30924. if (parent !== null) {
  30925. _this.parent = parent;
  30926. }
  30927. return _this;
  30928. }
  30929. Object.defineProperty(Mesh, "FRONTSIDE", {
  30930. /**
  30931. * Mesh side orientation : usually the external or front surface
  30932. */
  30933. get: function () {
  30934. return Mesh._FRONTSIDE;
  30935. },
  30936. enumerable: true,
  30937. configurable: true
  30938. });
  30939. Object.defineProperty(Mesh, "BACKSIDE", {
  30940. /**
  30941. * Mesh side orientation : usually the internal or back surface
  30942. */
  30943. get: function () {
  30944. return Mesh._BACKSIDE;
  30945. },
  30946. enumerable: true,
  30947. configurable: true
  30948. });
  30949. Object.defineProperty(Mesh, "DOUBLESIDE", {
  30950. /**
  30951. * Mesh side orientation : both internal and external or front and back surfaces
  30952. */
  30953. get: function () {
  30954. return Mesh._DOUBLESIDE;
  30955. },
  30956. enumerable: true,
  30957. configurable: true
  30958. });
  30959. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  30960. /**
  30961. * Mesh side orientation : by default, `FRONTSIDE`
  30962. */
  30963. get: function () {
  30964. return Mesh._DEFAULTSIDE;
  30965. },
  30966. enumerable: true,
  30967. configurable: true
  30968. });
  30969. Object.defineProperty(Mesh, "NO_CAP", {
  30970. /**
  30971. * Mesh cap setting : no cap
  30972. */
  30973. get: function () {
  30974. return Mesh._NO_CAP;
  30975. },
  30976. enumerable: true,
  30977. configurable: true
  30978. });
  30979. Object.defineProperty(Mesh, "CAP_START", {
  30980. /**
  30981. * Mesh cap setting : one cap at the beginning of the mesh
  30982. */
  30983. get: function () {
  30984. return Mesh._CAP_START;
  30985. },
  30986. enumerable: true,
  30987. configurable: true
  30988. });
  30989. Object.defineProperty(Mesh, "CAP_END", {
  30990. /**
  30991. * Mesh cap setting : one cap at the end of the mesh
  30992. */
  30993. get: function () {
  30994. return Mesh._CAP_END;
  30995. },
  30996. enumerable: true,
  30997. configurable: true
  30998. });
  30999. Object.defineProperty(Mesh, "CAP_ALL", {
  31000. /**
  31001. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31002. */
  31003. get: function () {
  31004. return Mesh._CAP_ALL;
  31005. },
  31006. enumerable: true,
  31007. configurable: true
  31008. });
  31009. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31010. set: function (callback) {
  31011. if (this._onBeforeDrawObserver) {
  31012. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31013. }
  31014. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31015. },
  31016. enumerable: true,
  31017. configurable: true
  31018. });
  31019. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31020. get: function () {
  31021. return this._morphTargetManager;
  31022. },
  31023. set: function (value) {
  31024. if (this._morphTargetManager === value) {
  31025. return;
  31026. }
  31027. this._morphTargetManager = value;
  31028. this._syncGeometryWithMorphTargetManager();
  31029. },
  31030. enumerable: true,
  31031. configurable: true
  31032. });
  31033. Object.defineProperty(Mesh.prototype, "source", {
  31034. get: function () {
  31035. return this._source;
  31036. },
  31037. enumerable: true,
  31038. configurable: true
  31039. });
  31040. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31041. get: function () {
  31042. return this._unIndexed;
  31043. },
  31044. set: function (value) {
  31045. if (this._unIndexed !== value) {
  31046. this._unIndexed = value;
  31047. this._markSubMeshesAsAttributesDirty();
  31048. }
  31049. },
  31050. enumerable: true,
  31051. configurable: true
  31052. });
  31053. // Methods
  31054. /**
  31055. * Returns the string "Mesh".
  31056. */
  31057. Mesh.prototype.getClassName = function () {
  31058. return "Mesh";
  31059. };
  31060. /**
  31061. * Returns a string.
  31062. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31063. */
  31064. Mesh.prototype.toString = function (fullDetails) {
  31065. var ret = _super.prototype.toString.call(this, fullDetails);
  31066. ret += ", n vertices: " + this.getTotalVertices();
  31067. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31068. if (this.animations) {
  31069. for (var i = 0; i < this.animations.length; i++) {
  31070. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31071. }
  31072. }
  31073. if (fullDetails) {
  31074. if (this._geometry) {
  31075. var ib = this.getIndices();
  31076. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31077. if (vb && ib) {
  31078. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31079. }
  31080. }
  31081. else {
  31082. ret += ", flat shading: UNKNOWN";
  31083. }
  31084. }
  31085. return ret;
  31086. };
  31087. Mesh.prototype._unBindEffect = function () {
  31088. _super.prototype._unBindEffect.call(this);
  31089. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31090. var instance = _a[_i];
  31091. instance._unBindEffect();
  31092. }
  31093. };
  31094. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31095. /**
  31096. * True if the mesh has some Levels Of Details (LOD).
  31097. * Returns a boolean.
  31098. */
  31099. get: function () {
  31100. return this._LODLevels.length > 0;
  31101. },
  31102. enumerable: true,
  31103. configurable: true
  31104. });
  31105. /**
  31106. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31107. * @returns an array of {BABYLON.MeshLODLevel}
  31108. */
  31109. Mesh.prototype.getLODLevels = function () {
  31110. return this._LODLevels;
  31111. };
  31112. Mesh.prototype._sortLODLevels = function () {
  31113. this._LODLevels.sort(function (a, b) {
  31114. if (a.distance < b.distance) {
  31115. return 1;
  31116. }
  31117. if (a.distance > b.distance) {
  31118. return -1;
  31119. }
  31120. return 0;
  31121. });
  31122. };
  31123. /**
  31124. * Add a mesh as LOD level triggered at the given distance.
  31125. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31126. * @param {number} distance The distance from the center of the object to show this level
  31127. * @param {Mesh} mesh The mesh to be added as LOD level
  31128. * @return {Mesh} This mesh (for chaining)
  31129. */
  31130. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31131. if (mesh && mesh._masterMesh) {
  31132. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31133. return this;
  31134. }
  31135. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31136. this._LODLevels.push(level);
  31137. if (mesh) {
  31138. mesh._masterMesh = this;
  31139. }
  31140. this._sortLODLevels();
  31141. return this;
  31142. };
  31143. /**
  31144. * Returns the LOD level mesh at the passed distance or null if not found.
  31145. * It is related to the method `addLODLevel(distance, mesh)`.
  31146. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31147. * Returns an object Mesh or `null`.
  31148. */
  31149. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31150. for (var index = 0; index < this._LODLevels.length; index++) {
  31151. var level = this._LODLevels[index];
  31152. if (level.distance === distance) {
  31153. return level.mesh;
  31154. }
  31155. }
  31156. return null;
  31157. };
  31158. /**
  31159. * Remove a mesh from the LOD array
  31160. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31161. * @param {Mesh} mesh The mesh to be removed.
  31162. * @return {Mesh} This mesh (for chaining)
  31163. */
  31164. Mesh.prototype.removeLODLevel = function (mesh) {
  31165. for (var index = 0; index < this._LODLevels.length; index++) {
  31166. if (this._LODLevels[index].mesh === mesh) {
  31167. this._LODLevels.splice(index, 1);
  31168. if (mesh) {
  31169. mesh._masterMesh = null;
  31170. }
  31171. }
  31172. }
  31173. this._sortLODLevels();
  31174. return this;
  31175. };
  31176. /**
  31177. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31178. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31179. */
  31180. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31181. if (!this._LODLevels || this._LODLevels.length === 0) {
  31182. return this;
  31183. }
  31184. var bSphere;
  31185. if (boundingSphere) {
  31186. bSphere = boundingSphere;
  31187. }
  31188. else {
  31189. var boundingInfo = this.getBoundingInfo();
  31190. bSphere = boundingInfo.boundingSphere;
  31191. }
  31192. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31193. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31194. if (this.onLODLevelSelection) {
  31195. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31196. }
  31197. return this;
  31198. }
  31199. for (var index = 0; index < this._LODLevels.length; index++) {
  31200. var level = this._LODLevels[index];
  31201. if (level.distance < distanceToCamera) {
  31202. if (level.mesh) {
  31203. level.mesh._preActivate();
  31204. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31205. }
  31206. if (this.onLODLevelSelection) {
  31207. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31208. }
  31209. return level.mesh;
  31210. }
  31211. }
  31212. if (this.onLODLevelSelection) {
  31213. this.onLODLevelSelection(distanceToCamera, this, this);
  31214. }
  31215. return this;
  31216. };
  31217. Object.defineProperty(Mesh.prototype, "geometry", {
  31218. /**
  31219. * Returns the mesh internal Geometry object.
  31220. */
  31221. get: function () {
  31222. return this._geometry;
  31223. },
  31224. enumerable: true,
  31225. configurable: true
  31226. });
  31227. /**
  31228. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31229. */
  31230. Mesh.prototype.getTotalVertices = function () {
  31231. if (this._geometry === null || this._geometry === undefined) {
  31232. return 0;
  31233. }
  31234. return this._geometry.getTotalVertices();
  31235. };
  31236. /**
  31237. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31238. * 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.
  31239. * You can force the copy with forceCopy === true
  31240. * Returns null if the mesh has no geometry or no vertex buffer.
  31241. * Possible `kind` values :
  31242. * - BABYLON.VertexBuffer.PositionKind
  31243. * - BABYLON.VertexBuffer.UVKind
  31244. * - BABYLON.VertexBuffer.UV2Kind
  31245. * - BABYLON.VertexBuffer.UV3Kind
  31246. * - BABYLON.VertexBuffer.UV4Kind
  31247. * - BABYLON.VertexBuffer.UV5Kind
  31248. * - BABYLON.VertexBuffer.UV6Kind
  31249. * - BABYLON.VertexBuffer.ColorKind
  31250. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31251. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31252. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31253. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31254. */
  31255. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31256. if (!this._geometry) {
  31257. return null;
  31258. }
  31259. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31260. };
  31261. /**
  31262. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31263. * Returns `null` if the mesh has no geometry.
  31264. * Possible `kind` values :
  31265. * - BABYLON.VertexBuffer.PositionKind
  31266. * - BABYLON.VertexBuffer.UVKind
  31267. * - BABYLON.VertexBuffer.UV2Kind
  31268. * - BABYLON.VertexBuffer.UV3Kind
  31269. * - BABYLON.VertexBuffer.UV4Kind
  31270. * - BABYLON.VertexBuffer.UV5Kind
  31271. * - BABYLON.VertexBuffer.UV6Kind
  31272. * - BABYLON.VertexBuffer.ColorKind
  31273. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31274. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31275. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31276. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31277. */
  31278. Mesh.prototype.getVertexBuffer = function (kind) {
  31279. if (!this._geometry) {
  31280. return null;
  31281. }
  31282. return this._geometry.getVertexBuffer(kind);
  31283. };
  31284. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31285. if (!this._geometry) {
  31286. if (this._delayInfo) {
  31287. return this._delayInfo.indexOf(kind) !== -1;
  31288. }
  31289. return false;
  31290. }
  31291. return this._geometry.isVerticesDataPresent(kind);
  31292. };
  31293. /**
  31294. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31295. * Possible `kind` values :
  31296. * - BABYLON.VertexBuffer.PositionKind
  31297. * - BABYLON.VertexBuffer.UVKind
  31298. * - BABYLON.VertexBuffer.UV2Kind
  31299. * - BABYLON.VertexBuffer.UV3Kind
  31300. * - BABYLON.VertexBuffer.UV4Kind
  31301. * - BABYLON.VertexBuffer.UV5Kind
  31302. * - BABYLON.VertexBuffer.UV6Kind
  31303. * - BABYLON.VertexBuffer.ColorKind
  31304. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31305. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31306. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31307. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31308. */
  31309. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31310. if (!this._geometry) {
  31311. if (this._delayInfo) {
  31312. return this._delayInfo.indexOf(kind) !== -1;
  31313. }
  31314. return false;
  31315. }
  31316. return this._geometry.isVertexBufferUpdatable(kind);
  31317. };
  31318. /**
  31319. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31320. * Possible `kind` values :
  31321. * - BABYLON.VertexBuffer.PositionKind
  31322. * - BABYLON.VertexBuffer.UVKind
  31323. * - BABYLON.VertexBuffer.UV2Kind
  31324. * - BABYLON.VertexBuffer.UV3Kind
  31325. * - BABYLON.VertexBuffer.UV4Kind
  31326. * - BABYLON.VertexBuffer.UV5Kind
  31327. * - BABYLON.VertexBuffer.UV6Kind
  31328. * - BABYLON.VertexBuffer.ColorKind
  31329. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31330. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31331. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31332. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31333. */
  31334. Mesh.prototype.getVerticesDataKinds = function () {
  31335. if (!this._geometry) {
  31336. var result = new Array();
  31337. if (this._delayInfo) {
  31338. this._delayInfo.forEach(function (kind, index, array) {
  31339. result.push(kind);
  31340. });
  31341. }
  31342. return result;
  31343. }
  31344. return this._geometry.getVerticesDataKinds();
  31345. };
  31346. /**
  31347. * Returns a positive integer : the total number of indices in this mesh geometry.
  31348. * Returns zero if the mesh has no geometry.
  31349. */
  31350. Mesh.prototype.getTotalIndices = function () {
  31351. if (!this._geometry) {
  31352. return 0;
  31353. }
  31354. return this._geometry.getTotalIndices();
  31355. };
  31356. /**
  31357. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31358. * 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.
  31359. * Returns an empty array if the mesh has no geometry.
  31360. */
  31361. Mesh.prototype.getIndices = function (copyWhenShared) {
  31362. if (!this._geometry) {
  31363. return [];
  31364. }
  31365. return this._geometry.getIndices(copyWhenShared);
  31366. };
  31367. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31368. get: function () {
  31369. return this._masterMesh !== null && this._masterMesh !== undefined;
  31370. },
  31371. enumerable: true,
  31372. configurable: true
  31373. });
  31374. /**
  31375. * Determine if the current mesh is ready to be rendered
  31376. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31377. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31378. * @returns true if all associated assets are ready (material, textures, shaders)
  31379. */
  31380. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31381. if (completeCheck === void 0) { completeCheck = false; }
  31382. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31383. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31384. return false;
  31385. }
  31386. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31387. return false;
  31388. }
  31389. if (!this.subMeshes || this.subMeshes.length === 0) {
  31390. return true;
  31391. }
  31392. if (!completeCheck) {
  31393. return true;
  31394. }
  31395. var engine = this.getEngine();
  31396. var scene = this.getScene();
  31397. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31398. this.computeWorldMatrix();
  31399. var mat = this.material || scene.defaultMaterial;
  31400. if (mat) {
  31401. if (mat.storeEffectOnSubMeshes) {
  31402. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31403. var subMesh = _a[_i];
  31404. var effectiveMaterial = subMesh.getMaterial();
  31405. if (effectiveMaterial) {
  31406. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31407. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31408. return false;
  31409. }
  31410. }
  31411. else {
  31412. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31413. return false;
  31414. }
  31415. }
  31416. }
  31417. }
  31418. }
  31419. else {
  31420. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31421. return false;
  31422. }
  31423. }
  31424. }
  31425. // Shadows
  31426. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31427. var light = _c[_b];
  31428. var generator = light.getShadowGenerator();
  31429. if (generator) {
  31430. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31431. var subMesh = _e[_d];
  31432. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31433. return false;
  31434. }
  31435. }
  31436. }
  31437. }
  31438. // LOD
  31439. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31440. var lod = _g[_f];
  31441. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31442. return false;
  31443. }
  31444. }
  31445. return true;
  31446. };
  31447. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31448. /**
  31449. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31450. * This property is pertinent only for updatable parametric shapes.
  31451. */
  31452. get: function () {
  31453. return this._areNormalsFrozen;
  31454. },
  31455. enumerable: true,
  31456. configurable: true
  31457. });
  31458. /**
  31459. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31460. * It has no effect at all on other shapes.
  31461. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31462. * Returns the Mesh.
  31463. */
  31464. Mesh.prototype.freezeNormals = function () {
  31465. this._areNormalsFrozen = true;
  31466. return this;
  31467. };
  31468. /**
  31469. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31470. * It has no effect at all on other shapes.
  31471. * It reactivates the mesh normals computation if it was previously frozen.
  31472. * Returns the Mesh.
  31473. */
  31474. Mesh.prototype.unfreezeNormals = function () {
  31475. this._areNormalsFrozen = false;
  31476. return this;
  31477. };
  31478. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31479. /**
  31480. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31481. */
  31482. set: function (count) {
  31483. this._overridenInstanceCount = count;
  31484. },
  31485. enumerable: true,
  31486. configurable: true
  31487. });
  31488. // Methods
  31489. Mesh.prototype._preActivate = function () {
  31490. var sceneRenderId = this.getScene().getRenderId();
  31491. if (this._preActivateId === sceneRenderId) {
  31492. return this;
  31493. }
  31494. this._preActivateId = sceneRenderId;
  31495. this._visibleInstances = null;
  31496. return this;
  31497. };
  31498. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31499. if (this._visibleInstances) {
  31500. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31501. }
  31502. return this;
  31503. };
  31504. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31505. if (!this._visibleInstances) {
  31506. this._visibleInstances = {};
  31507. this._visibleInstances.defaultRenderId = renderId;
  31508. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31509. }
  31510. if (!this._visibleInstances[renderId]) {
  31511. this._visibleInstances[renderId] = new Array();
  31512. }
  31513. this._visibleInstances[renderId].push(instance);
  31514. return this;
  31515. };
  31516. /**
  31517. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31518. * This means the mesh underlying bounding box and sphere are recomputed.
  31519. * Returns the Mesh.
  31520. */
  31521. Mesh.prototype.refreshBoundingInfo = function () {
  31522. return this._refreshBoundingInfo(false);
  31523. };
  31524. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31525. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31526. return this;
  31527. }
  31528. var data = this._getPositionData(applySkeleton);
  31529. if (data) {
  31530. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31531. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31532. }
  31533. if (this.subMeshes) {
  31534. for (var index = 0; index < this.subMeshes.length; index++) {
  31535. this.subMeshes[index].refreshBoundingInfo();
  31536. }
  31537. }
  31538. this._updateBoundingInfo();
  31539. return this;
  31540. };
  31541. Mesh.prototype._getPositionData = function (applySkeleton) {
  31542. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31543. if (data && applySkeleton && this.skeleton) {
  31544. data = BABYLON.Tools.Slice(data);
  31545. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31546. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31547. if (matricesWeightsData && matricesIndicesData) {
  31548. var needExtras = this.numBoneInfluencers > 4;
  31549. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31550. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31551. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31552. var tempVector = BABYLON.Tmp.Vector3[0];
  31553. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31554. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31555. var matWeightIdx = 0;
  31556. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31557. finalMatrix.reset();
  31558. var inf;
  31559. var weight;
  31560. for (inf = 0; inf < 4; inf++) {
  31561. weight = matricesWeightsData[matWeightIdx + inf];
  31562. if (weight <= 0)
  31563. break;
  31564. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31565. finalMatrix.addToSelf(tempMatrix);
  31566. }
  31567. if (needExtras) {
  31568. for (inf = 0; inf < 4; inf++) {
  31569. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31570. if (weight <= 0)
  31571. break;
  31572. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31573. finalMatrix.addToSelf(tempMatrix);
  31574. }
  31575. }
  31576. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31577. tempVector.toArray(data, index);
  31578. }
  31579. }
  31580. }
  31581. return data;
  31582. };
  31583. Mesh.prototype._createGlobalSubMesh = function (force) {
  31584. var totalVertices = this.getTotalVertices();
  31585. if (!totalVertices || !this.getIndices()) {
  31586. return null;
  31587. }
  31588. // Check if we need to recreate the submeshes
  31589. if (this.subMeshes && this.subMeshes.length > 0) {
  31590. var ib = this.getIndices();
  31591. if (!ib) {
  31592. return null;
  31593. }
  31594. var totalIndices = ib.length;
  31595. var needToRecreate = false;
  31596. if (force) {
  31597. needToRecreate = true;
  31598. }
  31599. else {
  31600. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31601. var submesh = _a[_i];
  31602. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31603. needToRecreate = true;
  31604. break;
  31605. }
  31606. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31607. needToRecreate = true;
  31608. break;
  31609. }
  31610. }
  31611. }
  31612. if (!needToRecreate) {
  31613. return this.subMeshes[0];
  31614. }
  31615. }
  31616. this.releaseSubMeshes();
  31617. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31618. };
  31619. Mesh.prototype.subdivide = function (count) {
  31620. if (count < 1) {
  31621. return;
  31622. }
  31623. var totalIndices = this.getTotalIndices();
  31624. var subdivisionSize = (totalIndices / count) | 0;
  31625. var offset = 0;
  31626. // Ensure that subdivisionSize is a multiple of 3
  31627. while (subdivisionSize % 3 !== 0) {
  31628. subdivisionSize++;
  31629. }
  31630. this.releaseSubMeshes();
  31631. for (var index = 0; index < count; index++) {
  31632. if (offset >= totalIndices) {
  31633. break;
  31634. }
  31635. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31636. offset += subdivisionSize;
  31637. }
  31638. this.synchronizeInstances();
  31639. };
  31640. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31641. if (updatable === void 0) { updatable = false; }
  31642. if (!this._geometry) {
  31643. var vertexData = new BABYLON.VertexData();
  31644. vertexData.set(data, kind);
  31645. var scene = this.getScene();
  31646. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31647. }
  31648. else {
  31649. this._geometry.setVerticesData(kind, data, updatable, stride);
  31650. }
  31651. return this;
  31652. };
  31653. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31654. if (updatable === void 0) { updatable = true; }
  31655. var vb = this.getVertexBuffer(kind);
  31656. if (!vb || vb.isUpdatable() === updatable) {
  31657. return;
  31658. }
  31659. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31660. };
  31661. /**
  31662. * Sets the mesh VertexBuffer.
  31663. * Returns the Mesh.
  31664. */
  31665. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31666. if (!this._geometry) {
  31667. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31668. }
  31669. this._geometry.setVerticesBuffer(buffer);
  31670. return this;
  31671. };
  31672. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31673. if (!this._geometry) {
  31674. return this;
  31675. }
  31676. if (!makeItUnique) {
  31677. this._geometry.updateVerticesData(kind, data, updateExtends);
  31678. }
  31679. else {
  31680. this.makeGeometryUnique();
  31681. this.updateVerticesData(kind, data, updateExtends, false);
  31682. }
  31683. return this;
  31684. };
  31685. /**
  31686. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31687. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31688. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31689. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31690. * Returns the Mesh.
  31691. */
  31692. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31693. if (computeNormals === void 0) { computeNormals = true; }
  31694. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31695. if (!positions) {
  31696. return this;
  31697. }
  31698. positionFunction(positions);
  31699. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31700. if (computeNormals) {
  31701. var indices = this.getIndices();
  31702. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31703. if (!normals) {
  31704. return this;
  31705. }
  31706. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31707. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31708. }
  31709. return this;
  31710. };
  31711. /**
  31712. * Creates a un-shared specific occurence of the geometry for the mesh.
  31713. * Returns the Mesh.
  31714. */
  31715. Mesh.prototype.makeGeometryUnique = function () {
  31716. if (!this._geometry) {
  31717. return this;
  31718. }
  31719. var oldGeometry = this._geometry;
  31720. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31721. oldGeometry.releaseForMesh(this, true);
  31722. geometry.applyToMesh(this);
  31723. return this;
  31724. };
  31725. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31726. if (totalVertices === void 0) { totalVertices = null; }
  31727. if (updatable === void 0) { updatable = false; }
  31728. if (!this._geometry) {
  31729. var vertexData = new BABYLON.VertexData();
  31730. vertexData.indices = indices;
  31731. var scene = this.getScene();
  31732. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31733. }
  31734. else {
  31735. this._geometry.setIndices(indices, totalVertices, updatable);
  31736. }
  31737. return this;
  31738. };
  31739. /**
  31740. * Update the current index buffer
  31741. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31742. * Returns the Mesh.
  31743. */
  31744. Mesh.prototype.updateIndices = function (indices, offset) {
  31745. if (!this._geometry) {
  31746. return this;
  31747. }
  31748. this._geometry.updateIndices(indices, offset);
  31749. return this;
  31750. };
  31751. /**
  31752. * Invert the geometry to move from a right handed system to a left handed one.
  31753. * Returns the Mesh.
  31754. */
  31755. Mesh.prototype.toLeftHanded = function () {
  31756. if (!this._geometry) {
  31757. return this;
  31758. }
  31759. this._geometry.toLeftHanded();
  31760. return this;
  31761. };
  31762. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31763. if (!this._geometry) {
  31764. return this;
  31765. }
  31766. var engine = this.getScene().getEngine();
  31767. // Wireframe
  31768. var indexToBind;
  31769. if (this._unIndexed) {
  31770. indexToBind = null;
  31771. }
  31772. else {
  31773. switch (fillMode) {
  31774. case BABYLON.Material.PointFillMode:
  31775. indexToBind = null;
  31776. break;
  31777. case BABYLON.Material.WireFrameFillMode:
  31778. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31779. break;
  31780. default:
  31781. case BABYLON.Material.TriangleFillMode:
  31782. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31783. break;
  31784. }
  31785. }
  31786. // VBOs
  31787. this._geometry._bind(effect, indexToBind);
  31788. return this;
  31789. };
  31790. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31791. if (alternate === void 0) { alternate = false; }
  31792. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31793. return this;
  31794. }
  31795. this.onBeforeDrawObservable.notifyObservers(this);
  31796. var scene = this.getScene();
  31797. var engine = scene.getEngine();
  31798. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31799. // or triangles as points
  31800. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31801. }
  31802. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31803. // Triangles as wireframe
  31804. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31805. }
  31806. else {
  31807. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31808. }
  31809. if (scene._isAlternateRenderingEnabled && !alternate) {
  31810. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31811. if (!effect || !scene.activeCamera) {
  31812. return this;
  31813. }
  31814. scene._switchToAlternateCameraConfiguration(true);
  31815. this._effectiveMaterial.bindView(effect);
  31816. this._effectiveMaterial.bindViewProjection(effect);
  31817. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31818. this._draw(subMesh, fillMode, instancesCount, true);
  31819. engine.setViewport(scene.activeCamera.viewport);
  31820. scene._switchToAlternateCameraConfiguration(false);
  31821. this._effectiveMaterial.bindView(effect);
  31822. this._effectiveMaterial.bindViewProjection(effect);
  31823. }
  31824. return this;
  31825. };
  31826. /**
  31827. * Registers for this mesh a javascript function called just before the rendering process.
  31828. * This function is passed the current mesh.
  31829. * Return the Mesh.
  31830. */
  31831. Mesh.prototype.registerBeforeRender = function (func) {
  31832. this.onBeforeRenderObservable.add(func);
  31833. return this;
  31834. };
  31835. /**
  31836. * Disposes a previously registered javascript function called before the rendering.
  31837. * This function is passed the current mesh.
  31838. * Returns the Mesh.
  31839. */
  31840. Mesh.prototype.unregisterBeforeRender = function (func) {
  31841. this.onBeforeRenderObservable.removeCallback(func);
  31842. return this;
  31843. };
  31844. /**
  31845. * Registers for this mesh a javascript function called just after the rendering is complete.
  31846. * This function is passed the current mesh.
  31847. * Returns the Mesh.
  31848. */
  31849. Mesh.prototype.registerAfterRender = function (func) {
  31850. this.onAfterRenderObservable.add(func);
  31851. return this;
  31852. };
  31853. /**
  31854. * Disposes a previously registered javascript function called after the rendering.
  31855. * This function is passed the current mesh.
  31856. * Return the Mesh.
  31857. */
  31858. Mesh.prototype.unregisterAfterRender = function (func) {
  31859. this.onAfterRenderObservable.removeCallback(func);
  31860. return this;
  31861. };
  31862. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31863. var scene = this.getScene();
  31864. this._batchCache.mustReturn = false;
  31865. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31866. this._batchCache.visibleInstances[subMeshId] = null;
  31867. if (this._visibleInstances) {
  31868. var currentRenderId = scene.getRenderId();
  31869. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31870. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31871. var selfRenderId = this._renderId;
  31872. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31873. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31874. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31875. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31876. }
  31877. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31878. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31879. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31880. this._batchCache.mustReturn = true;
  31881. return this._batchCache;
  31882. }
  31883. if (currentRenderId !== selfRenderId) {
  31884. this._batchCache.renderSelf[subMeshId] = false;
  31885. }
  31886. }
  31887. this._renderIdForInstances[subMeshId] = currentRenderId;
  31888. }
  31889. return this._batchCache;
  31890. };
  31891. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31892. var visibleInstances = batch.visibleInstances[subMesh._id];
  31893. if (!visibleInstances) {
  31894. return this;
  31895. }
  31896. var matricesCount = visibleInstances.length + 1;
  31897. var bufferSize = matricesCount * 16 * 4;
  31898. var currentInstancesBufferSize = this._instancesBufferSize;
  31899. var instancesBuffer = this._instancesBuffer;
  31900. while (this._instancesBufferSize < bufferSize) {
  31901. this._instancesBufferSize *= 2;
  31902. }
  31903. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31904. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31905. }
  31906. var offset = 0;
  31907. var instancesCount = 0;
  31908. var world = this.getWorldMatrix();
  31909. if (batch.renderSelf[subMesh._id]) {
  31910. world.copyToArray(this._instancesData, offset);
  31911. offset += 16;
  31912. instancesCount++;
  31913. }
  31914. if (visibleInstances) {
  31915. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31916. var instance = visibleInstances[instanceIndex];
  31917. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31918. offset += 16;
  31919. instancesCount++;
  31920. }
  31921. }
  31922. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31923. if (instancesBuffer) {
  31924. instancesBuffer.dispose();
  31925. }
  31926. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  31927. this._instancesBuffer = instancesBuffer;
  31928. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  31929. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  31930. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  31931. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  31932. }
  31933. else {
  31934. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  31935. }
  31936. this._bind(subMesh, effect, fillMode);
  31937. this._draw(subMesh, fillMode, instancesCount);
  31938. engine.unbindInstanceAttributes();
  31939. return this;
  31940. };
  31941. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  31942. var scene = this.getScene();
  31943. var engine = scene.getEngine();
  31944. if (hardwareInstancedRendering) {
  31945. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  31946. }
  31947. else {
  31948. if (batch.renderSelf[subMesh._id]) {
  31949. // Draw
  31950. if (onBeforeDraw) {
  31951. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  31952. }
  31953. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  31954. }
  31955. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  31956. if (visibleInstancesForSubMesh) {
  31957. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  31958. var instance = visibleInstancesForSubMesh[instanceIndex];
  31959. // World
  31960. var world = instance.getWorldMatrix();
  31961. if (onBeforeDraw) {
  31962. onBeforeDraw(true, world, effectiveMaterial);
  31963. }
  31964. // Draw
  31965. this._draw(subMesh, fillMode);
  31966. }
  31967. }
  31968. }
  31969. return this;
  31970. };
  31971. /**
  31972. * Triggers the draw call for the mesh.
  31973. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  31974. * Returns the Mesh.
  31975. */
  31976. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  31977. this._checkOcclusionQuery();
  31978. if (this._isOccluded) {
  31979. return this;
  31980. }
  31981. var scene = this.getScene();
  31982. // Managing instances
  31983. var batch = this._getInstancesRenderList(subMesh._id);
  31984. if (batch.mustReturn) {
  31985. return this;
  31986. }
  31987. // Checking geometry state
  31988. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31989. return this;
  31990. }
  31991. this.onBeforeRenderObservable.notifyObservers(this);
  31992. var engine = scene.getEngine();
  31993. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  31994. // Material
  31995. var material = subMesh.getMaterial();
  31996. if (!material) {
  31997. return this;
  31998. }
  31999. this._effectiveMaterial = material;
  32000. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32001. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32002. return this;
  32003. }
  32004. }
  32005. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32006. return this;
  32007. }
  32008. // Alpha mode
  32009. if (enableAlphaMode) {
  32010. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32011. }
  32012. // Outline - step 1
  32013. var savedDepthWrite = engine.getDepthWrite();
  32014. if (this.renderOutline) {
  32015. engine.setDepthWrite(false);
  32016. scene.getOutlineRenderer().render(subMesh, batch);
  32017. engine.setDepthWrite(savedDepthWrite);
  32018. }
  32019. var effect;
  32020. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32021. effect = subMesh.effect;
  32022. }
  32023. else {
  32024. effect = this._effectiveMaterial.getEffect();
  32025. }
  32026. if (!effect) {
  32027. return this;
  32028. }
  32029. var sideOrientation = this.overrideMaterialSideOrientation;
  32030. if (sideOrientation == null) {
  32031. sideOrientation = this._effectiveMaterial.sideOrientation;
  32032. if (this._getWorldMatrixDeterminant() < 0) {
  32033. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32034. }
  32035. }
  32036. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32037. if (this._effectiveMaterial.forceDepthWrite) {
  32038. engine.setDepthWrite(true);
  32039. }
  32040. // Bind
  32041. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32042. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32043. this._bind(subMesh, effect, fillMode);
  32044. }
  32045. var world = this.getWorldMatrix();
  32046. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32047. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32048. }
  32049. else {
  32050. this._effectiveMaterial.bind(world, this);
  32051. }
  32052. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32053. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32054. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32055. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32056. }
  32057. // Draw
  32058. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32059. // Unbind
  32060. this._effectiveMaterial.unbind();
  32061. // Outline - step 2
  32062. if (this.renderOutline && savedDepthWrite) {
  32063. engine.setDepthWrite(true);
  32064. engine.setColorWrite(false);
  32065. scene.getOutlineRenderer().render(subMesh, batch);
  32066. engine.setColorWrite(true);
  32067. }
  32068. // Overlay
  32069. if (this.renderOverlay) {
  32070. var currentMode = engine.getAlphaMode();
  32071. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32072. scene.getOutlineRenderer().render(subMesh, batch, true);
  32073. engine.setAlphaMode(currentMode);
  32074. }
  32075. this.onAfterRenderObservable.notifyObservers(this);
  32076. return this;
  32077. };
  32078. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32079. if (isInstance && effectiveMaterial) {
  32080. effectiveMaterial.bindOnlyWorldMatrix(world);
  32081. }
  32082. };
  32083. /**
  32084. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32085. */
  32086. Mesh.prototype.getEmittedParticleSystems = function () {
  32087. var results = new Array();
  32088. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32089. var particleSystem = this.getScene().particleSystems[index];
  32090. if (particleSystem.emitter === this) {
  32091. results.push(particleSystem);
  32092. }
  32093. }
  32094. return results;
  32095. };
  32096. /**
  32097. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32098. */
  32099. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32100. var results = new Array();
  32101. var descendants = this.getDescendants();
  32102. descendants.push(this);
  32103. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32104. var particleSystem = this.getScene().particleSystems[index];
  32105. var emitter = particleSystem.emitter;
  32106. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32107. results.push(particleSystem);
  32108. }
  32109. }
  32110. return results;
  32111. };
  32112. Mesh.prototype._checkDelayState = function () {
  32113. var scene = this.getScene();
  32114. if (this._geometry) {
  32115. this._geometry.load(scene);
  32116. }
  32117. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32118. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32119. this._queueLoad(scene);
  32120. }
  32121. return this;
  32122. };
  32123. Mesh.prototype._queueLoad = function (scene) {
  32124. var _this = this;
  32125. scene._addPendingData(this);
  32126. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32127. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32128. if (data instanceof ArrayBuffer) {
  32129. _this._delayLoadingFunction(data, _this);
  32130. }
  32131. else {
  32132. _this._delayLoadingFunction(JSON.parse(data), _this);
  32133. }
  32134. _this.instances.forEach(function (instance) {
  32135. instance._syncSubMeshes();
  32136. });
  32137. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32138. scene._removePendingData(_this);
  32139. }, function () { }, scene.database, getBinaryData);
  32140. return this;
  32141. };
  32142. /**
  32143. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32144. */
  32145. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32146. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32147. return false;
  32148. }
  32149. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32150. return false;
  32151. }
  32152. this._checkDelayState();
  32153. return true;
  32154. };
  32155. /**
  32156. * Sets the mesh material by the material or multiMaterial `id` property.
  32157. * The material `id` is a string identifying the material or the multiMaterial.
  32158. * This method returns the Mesh.
  32159. */
  32160. Mesh.prototype.setMaterialByID = function (id) {
  32161. var materials = this.getScene().materials;
  32162. var index;
  32163. for (index = materials.length - 1; index > -1; index--) {
  32164. if (materials[index].id === id) {
  32165. this.material = materials[index];
  32166. return this;
  32167. }
  32168. }
  32169. // Multi
  32170. var multiMaterials = this.getScene().multiMaterials;
  32171. for (index = multiMaterials.length - 1; index > -1; index--) {
  32172. if (multiMaterials[index].id === id) {
  32173. this.material = multiMaterials[index];
  32174. return this;
  32175. }
  32176. }
  32177. return this;
  32178. };
  32179. /**
  32180. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32181. */
  32182. Mesh.prototype.getAnimatables = function () {
  32183. var results = new Array();
  32184. if (this.material) {
  32185. results.push(this.material);
  32186. }
  32187. if (this.skeleton) {
  32188. results.push(this.skeleton);
  32189. }
  32190. return results;
  32191. };
  32192. /**
  32193. * Modifies the mesh geometry according to the passed transformation matrix.
  32194. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32195. * The mesh normals are modified accordingly the same transformation.
  32196. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32197. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32198. * Returns the Mesh.
  32199. */
  32200. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32201. // Position
  32202. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32203. return this;
  32204. }
  32205. var submeshes = this.subMeshes.splice(0);
  32206. this._resetPointsArrayCache();
  32207. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32208. var temp = new Array();
  32209. var index;
  32210. for (index = 0; index < data.length; index += 3) {
  32211. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32212. }
  32213. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32214. // Normals
  32215. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32216. return this;
  32217. }
  32218. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32219. temp = [];
  32220. for (index = 0; index < data.length; index += 3) {
  32221. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32222. }
  32223. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32224. // flip faces?
  32225. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32226. this.flipFaces();
  32227. }
  32228. // Restore submeshes
  32229. this.releaseSubMeshes();
  32230. this.subMeshes = submeshes;
  32231. return this;
  32232. };
  32233. /**
  32234. * Modifies the mesh geometry according to its own current World Matrix.
  32235. * The mesh World Matrix is then reset.
  32236. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32237. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32238. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32239. * Returns the Mesh.
  32240. */
  32241. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32242. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32243. this.scaling.copyFromFloats(1, 1, 1);
  32244. this.position.copyFromFloats(0, 0, 0);
  32245. this.rotation.copyFromFloats(0, 0, 0);
  32246. //only if quaternion is already set
  32247. if (this.rotationQuaternion) {
  32248. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32249. }
  32250. this._worldMatrix = BABYLON.Matrix.Identity();
  32251. return this;
  32252. };
  32253. Object.defineProperty(Mesh.prototype, "_positions", {
  32254. // Cache
  32255. get: function () {
  32256. if (this._geometry) {
  32257. return this._geometry._positions;
  32258. }
  32259. return null;
  32260. },
  32261. enumerable: true,
  32262. configurable: true
  32263. });
  32264. Mesh.prototype._resetPointsArrayCache = function () {
  32265. if (this._geometry) {
  32266. this._geometry._resetPointsArrayCache();
  32267. }
  32268. return this;
  32269. };
  32270. Mesh.prototype._generatePointsArray = function () {
  32271. if (this._geometry) {
  32272. return this._geometry._generatePointsArray();
  32273. }
  32274. return false;
  32275. };
  32276. /**
  32277. * Returns a new Mesh object generated from the current mesh properties.
  32278. * This method must not get confused with createInstance().
  32279. * The parameter `name` is a string, the name given to the new mesh.
  32280. * The optional parameter `newParent` can be any Node object (default `null`).
  32281. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32282. * 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.
  32283. */
  32284. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32285. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32286. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32287. };
  32288. /**
  32289. * Releases resources associated with this mesh.
  32290. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32291. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32292. */
  32293. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32294. var _this = this;
  32295. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32296. this.morphTargetManager = null;
  32297. if (this._geometry) {
  32298. this._geometry.releaseForMesh(this, true);
  32299. }
  32300. // Sources
  32301. var meshes = this.getScene().meshes;
  32302. meshes.forEach(function (abstractMesh) {
  32303. var mesh = abstractMesh;
  32304. if (mesh._source && mesh._source === _this) {
  32305. mesh._source = null;
  32306. }
  32307. });
  32308. this._source = null;
  32309. // Instances
  32310. if (this._instancesBuffer) {
  32311. this._instancesBuffer.dispose();
  32312. this._instancesBuffer = null;
  32313. }
  32314. while (this.instances.length) {
  32315. this.instances[0].dispose();
  32316. }
  32317. // Effect layers.
  32318. var effectLayers = this.getScene().effectLayers;
  32319. for (var i = 0; i < effectLayers.length; i++) {
  32320. var effectLayer = effectLayers[i];
  32321. if (effectLayer) {
  32322. effectLayer._disposeMesh(this);
  32323. }
  32324. }
  32325. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32326. };
  32327. /**
  32328. * Modifies the mesh geometry according to a displacement map.
  32329. * 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.
  32330. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32331. * This method returns nothing.
  32332. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32333. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32334. * 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.
  32335. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32336. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32337. *
  32338. * Returns the Mesh.
  32339. */
  32340. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32341. var _this = this;
  32342. var scene = this.getScene();
  32343. var onload = function (img) {
  32344. // Getting height map data
  32345. var canvas = document.createElement("canvas");
  32346. var context = canvas.getContext("2d");
  32347. var heightMapWidth = img.width;
  32348. var heightMapHeight = img.height;
  32349. canvas.width = heightMapWidth;
  32350. canvas.height = heightMapHeight;
  32351. context.drawImage(img, 0, 0);
  32352. // Create VertexData from map data
  32353. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32354. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32355. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32356. //execute success callback, if set
  32357. if (onSuccess) {
  32358. onSuccess(_this);
  32359. }
  32360. };
  32361. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32362. return this;
  32363. };
  32364. /**
  32365. * Modifies the mesh geometry according to a displacementMap buffer.
  32366. * 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.
  32367. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32368. * This method returns nothing.
  32369. * 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.
  32370. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32371. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32372. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32373. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32374. *
  32375. * Returns the Mesh.
  32376. */
  32377. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32378. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32379. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32380. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32381. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32382. return this;
  32383. }
  32384. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32385. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32386. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32387. var position = BABYLON.Vector3.Zero();
  32388. var normal = BABYLON.Vector3.Zero();
  32389. var uv = BABYLON.Vector2.Zero();
  32390. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32391. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32392. for (var index = 0; index < positions.length; index += 3) {
  32393. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32394. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32395. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32396. // Compute height
  32397. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32398. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32399. var pos = (u + v * heightMapWidth) * 4;
  32400. var r = buffer[pos] / 255.0;
  32401. var g = buffer[pos + 1] / 255.0;
  32402. var b = buffer[pos + 2] / 255.0;
  32403. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32404. normal.normalize();
  32405. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32406. position = position.add(normal);
  32407. position.toArray(positions, index);
  32408. }
  32409. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32410. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32411. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32412. return this;
  32413. };
  32414. /**
  32415. * Modify the mesh to get a flat shading rendering.
  32416. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32417. * This method returns the Mesh.
  32418. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32419. */
  32420. Mesh.prototype.convertToFlatShadedMesh = function () {
  32421. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32422. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32423. var kinds = this.getVerticesDataKinds();
  32424. var vbs = {};
  32425. var data = {};
  32426. var newdata = {};
  32427. var updatableNormals = false;
  32428. var kindIndex;
  32429. var kind;
  32430. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32431. kind = kinds[kindIndex];
  32432. var vertexBuffer = this.getVertexBuffer(kind);
  32433. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32434. updatableNormals = vertexBuffer.isUpdatable();
  32435. kinds.splice(kindIndex, 1);
  32436. kindIndex--;
  32437. continue;
  32438. }
  32439. vbs[kind] = vertexBuffer;
  32440. data[kind] = vbs[kind].getData();
  32441. newdata[kind] = [];
  32442. }
  32443. // Save previous submeshes
  32444. var previousSubmeshes = this.subMeshes.slice(0);
  32445. var indices = this.getIndices();
  32446. var totalIndices = this.getTotalIndices();
  32447. // Generating unique vertices per face
  32448. var index;
  32449. for (index = 0; index < totalIndices; index++) {
  32450. var vertexIndex = indices[index];
  32451. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32452. kind = kinds[kindIndex];
  32453. var stride = vbs[kind].getStrideSize();
  32454. for (var offset = 0; offset < stride; offset++) {
  32455. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32456. }
  32457. }
  32458. }
  32459. // Updating faces & normal
  32460. var normals = [];
  32461. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32462. for (index = 0; index < totalIndices; index += 3) {
  32463. indices[index] = index;
  32464. indices[index + 1] = index + 1;
  32465. indices[index + 2] = index + 2;
  32466. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32467. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32468. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32469. var p1p2 = p1.subtract(p2);
  32470. var p3p2 = p3.subtract(p2);
  32471. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32472. // Store same normals for every vertex
  32473. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32474. normals.push(normal.x);
  32475. normals.push(normal.y);
  32476. normals.push(normal.z);
  32477. }
  32478. }
  32479. this.setIndices(indices);
  32480. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32481. // Updating vertex buffers
  32482. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32483. kind = kinds[kindIndex];
  32484. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32485. }
  32486. // Updating submeshes
  32487. this.releaseSubMeshes();
  32488. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32489. var previousOne = previousSubmeshes[submeshIndex];
  32490. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32491. }
  32492. this.synchronizeInstances();
  32493. return this;
  32494. };
  32495. /**
  32496. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32497. * In other words, more vertices, no more indices and a single bigger VBO.
  32498. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32499. * Returns the Mesh.
  32500. */
  32501. Mesh.prototype.convertToUnIndexedMesh = function () {
  32502. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32503. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32504. var kinds = this.getVerticesDataKinds();
  32505. var vbs = {};
  32506. var data = {};
  32507. var newdata = {};
  32508. var kindIndex;
  32509. var kind;
  32510. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32511. kind = kinds[kindIndex];
  32512. var vertexBuffer = this.getVertexBuffer(kind);
  32513. vbs[kind] = vertexBuffer;
  32514. data[kind] = vbs[kind].getData();
  32515. newdata[kind] = [];
  32516. }
  32517. // Save previous submeshes
  32518. var previousSubmeshes = this.subMeshes.slice(0);
  32519. var indices = this.getIndices();
  32520. var totalIndices = this.getTotalIndices();
  32521. // Generating unique vertices per face
  32522. var index;
  32523. for (index = 0; index < totalIndices; index++) {
  32524. var vertexIndex = indices[index];
  32525. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32526. kind = kinds[kindIndex];
  32527. var stride = vbs[kind].getStrideSize();
  32528. for (var offset = 0; offset < stride; offset++) {
  32529. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32530. }
  32531. }
  32532. }
  32533. // Updating indices
  32534. for (index = 0; index < totalIndices; index += 3) {
  32535. indices[index] = index;
  32536. indices[index + 1] = index + 1;
  32537. indices[index + 2] = index + 2;
  32538. }
  32539. this.setIndices(indices);
  32540. // Updating vertex buffers
  32541. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32542. kind = kinds[kindIndex];
  32543. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32544. }
  32545. // Updating submeshes
  32546. this.releaseSubMeshes();
  32547. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32548. var previousOne = previousSubmeshes[submeshIndex];
  32549. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32550. }
  32551. this._unIndexed = true;
  32552. this.synchronizeInstances();
  32553. return this;
  32554. };
  32555. /**
  32556. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32557. * This method returns the Mesh.
  32558. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32559. */
  32560. Mesh.prototype.flipFaces = function (flipNormals) {
  32561. if (flipNormals === void 0) { flipNormals = false; }
  32562. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32563. var i;
  32564. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32565. for (i = 0; i < vertex_data.normals.length; i++) {
  32566. vertex_data.normals[i] *= -1;
  32567. }
  32568. }
  32569. if (vertex_data.indices) {
  32570. var temp;
  32571. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32572. // reassign indices
  32573. temp = vertex_data.indices[i + 1];
  32574. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32575. vertex_data.indices[i + 2] = temp;
  32576. }
  32577. }
  32578. vertex_data.applyToMesh(this);
  32579. return this;
  32580. };
  32581. // Instances
  32582. /**
  32583. * Creates a new InstancedMesh object from the mesh model.
  32584. * An instance shares the same properties and the same material than its model.
  32585. * Only these properties of each instance can then be set individually :
  32586. * - position
  32587. * - rotation
  32588. * - rotationQuaternion
  32589. * - setPivotMatrix
  32590. * - scaling
  32591. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32592. * Warning : this method is not supported for Line mesh and LineSystem
  32593. */
  32594. Mesh.prototype.createInstance = function (name) {
  32595. return new BABYLON.InstancedMesh(name, this);
  32596. };
  32597. /**
  32598. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32599. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32600. * This method returns the Mesh.
  32601. */
  32602. Mesh.prototype.synchronizeInstances = function () {
  32603. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32604. var instance = this.instances[instanceIndex];
  32605. instance._syncSubMeshes();
  32606. }
  32607. return this;
  32608. };
  32609. /**
  32610. * Simplify the mesh according to the given array of settings.
  32611. * Function will return immediately and will simplify async. It returns the Mesh.
  32612. * @param settings a collection of simplification settings.
  32613. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32614. * @param type the type of simplification to run.
  32615. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32616. */
  32617. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32618. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32619. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32620. this.getScene().simplificationQueue.addTask({
  32621. settings: settings,
  32622. parallelProcessing: parallelProcessing,
  32623. mesh: this,
  32624. simplificationType: simplificationType,
  32625. successCallback: successCallback
  32626. });
  32627. return this;
  32628. };
  32629. /**
  32630. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32631. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32632. * This should be used together with the simplification to avoid disappearing triangles.
  32633. * Returns the Mesh.
  32634. * @param successCallback an optional success callback to be called after the optimization finished.
  32635. */
  32636. Mesh.prototype.optimizeIndices = function (successCallback) {
  32637. var _this = this;
  32638. var indices = this.getIndices();
  32639. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32640. if (!positions || !indices) {
  32641. return this;
  32642. }
  32643. var vectorPositions = new Array();
  32644. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32645. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32646. }
  32647. var dupes = new Array();
  32648. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32649. var realPos = vectorPositions.length - 1 - iteration;
  32650. var testedPosition = vectorPositions[realPos];
  32651. for (var j = 0; j < realPos; ++j) {
  32652. var againstPosition = vectorPositions[j];
  32653. if (testedPosition.equals(againstPosition)) {
  32654. dupes[realPos] = j;
  32655. break;
  32656. }
  32657. }
  32658. }, function () {
  32659. for (var i = 0; i < indices.length; ++i) {
  32660. indices[i] = dupes[indices[i]] || indices[i];
  32661. }
  32662. //indices are now reordered
  32663. var originalSubMeshes = _this.subMeshes.slice(0);
  32664. _this.setIndices(indices);
  32665. _this.subMeshes = originalSubMeshes;
  32666. if (successCallback) {
  32667. successCallback(_this);
  32668. }
  32669. });
  32670. return this;
  32671. };
  32672. Mesh.prototype.serialize = function (serializationObject) {
  32673. serializationObject.name = this.name;
  32674. serializationObject.id = this.id;
  32675. serializationObject.type = this.getClassName();
  32676. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32677. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32678. }
  32679. serializationObject.position = this.position.asArray();
  32680. if (this.rotationQuaternion) {
  32681. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32682. }
  32683. else if (this.rotation) {
  32684. serializationObject.rotation = this.rotation.asArray();
  32685. }
  32686. serializationObject.scaling = this.scaling.asArray();
  32687. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32688. serializationObject.isEnabled = this.isEnabled(false);
  32689. serializationObject.isVisible = this.isVisible;
  32690. serializationObject.infiniteDistance = this.infiniteDistance;
  32691. serializationObject.pickable = this.isPickable;
  32692. serializationObject.receiveShadows = this.receiveShadows;
  32693. serializationObject.billboardMode = this.billboardMode;
  32694. serializationObject.visibility = this.visibility;
  32695. serializationObject.checkCollisions = this.checkCollisions;
  32696. serializationObject.isBlocker = this.isBlocker;
  32697. // Parent
  32698. if (this.parent) {
  32699. serializationObject.parentId = this.parent.id;
  32700. }
  32701. // Geometry
  32702. serializationObject.isUnIndexed = this.isUnIndexed;
  32703. var geometry = this._geometry;
  32704. if (geometry) {
  32705. var geometryId = geometry.id;
  32706. serializationObject.geometryId = geometryId;
  32707. // SubMeshes
  32708. serializationObject.subMeshes = [];
  32709. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32710. var subMesh = this.subMeshes[subIndex];
  32711. serializationObject.subMeshes.push({
  32712. materialIndex: subMesh.materialIndex,
  32713. verticesStart: subMesh.verticesStart,
  32714. verticesCount: subMesh.verticesCount,
  32715. indexStart: subMesh.indexStart,
  32716. indexCount: subMesh.indexCount
  32717. });
  32718. }
  32719. }
  32720. // Material
  32721. if (this.material) {
  32722. serializationObject.materialId = this.material.id;
  32723. }
  32724. else {
  32725. this.material = null;
  32726. }
  32727. // Morph targets
  32728. if (this.morphTargetManager) {
  32729. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32730. }
  32731. // Skeleton
  32732. if (this.skeleton) {
  32733. serializationObject.skeletonId = this.skeleton.id;
  32734. }
  32735. // Physics
  32736. //TODO implement correct serialization for physics impostors.
  32737. var impostor = this.getPhysicsImpostor();
  32738. if (impostor) {
  32739. serializationObject.physicsMass = impostor.getParam("mass");
  32740. serializationObject.physicsFriction = impostor.getParam("friction");
  32741. serializationObject.physicsRestitution = impostor.getParam("mass");
  32742. serializationObject.physicsImpostor = impostor.type;
  32743. }
  32744. // Metadata
  32745. if (this.metadata) {
  32746. serializationObject.metadata = this.metadata;
  32747. }
  32748. // Instances
  32749. serializationObject.instances = [];
  32750. for (var index = 0; index < this.instances.length; index++) {
  32751. var instance = this.instances[index];
  32752. var serializationInstance = {
  32753. name: instance.name,
  32754. id: instance.id,
  32755. position: instance.position.asArray(),
  32756. scaling: instance.scaling.asArray()
  32757. };
  32758. if (instance.rotationQuaternion) {
  32759. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32760. }
  32761. else if (instance.rotation) {
  32762. serializationInstance.rotation = instance.rotation.asArray();
  32763. }
  32764. serializationObject.instances.push(serializationInstance);
  32765. // Animations
  32766. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32767. serializationInstance.ranges = instance.serializeAnimationRanges();
  32768. }
  32769. //
  32770. // Animations
  32771. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32772. serializationObject.ranges = this.serializeAnimationRanges();
  32773. // Layer mask
  32774. serializationObject.layerMask = this.layerMask;
  32775. // Alpha
  32776. serializationObject.alphaIndex = this.alphaIndex;
  32777. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32778. // Overlay
  32779. serializationObject.overlayAlpha = this.overlayAlpha;
  32780. serializationObject.overlayColor = this.overlayColor.asArray();
  32781. serializationObject.renderOverlay = this.renderOverlay;
  32782. // Fog
  32783. serializationObject.applyFog = this.applyFog;
  32784. // Action Manager
  32785. if (this.actionManager) {
  32786. serializationObject.actions = this.actionManager.serialize(this.name);
  32787. }
  32788. };
  32789. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32790. if (!this.geometry) {
  32791. return;
  32792. }
  32793. this._markSubMeshesAsAttributesDirty();
  32794. var morphTargetManager = this._morphTargetManager;
  32795. if (morphTargetManager && morphTargetManager.vertexCount) {
  32796. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32797. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32798. this.morphTargetManager = null;
  32799. return;
  32800. }
  32801. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32802. var morphTarget = morphTargetManager.getActiveTarget(index);
  32803. var positions = morphTarget.getPositions();
  32804. if (!positions) {
  32805. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32806. return;
  32807. }
  32808. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32809. var normals = morphTarget.getNormals();
  32810. if (normals) {
  32811. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32812. }
  32813. var tangents = morphTarget.getTangents();
  32814. if (tangents) {
  32815. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32816. }
  32817. }
  32818. }
  32819. else {
  32820. var index = 0;
  32821. // Positions
  32822. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32823. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32824. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32825. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32826. }
  32827. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32828. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32829. }
  32830. index++;
  32831. }
  32832. }
  32833. };
  32834. // Statics
  32835. /**
  32836. * Returns a new Mesh object parsed from the source provided.
  32837. * The parameter `parsedMesh` is the source.
  32838. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32839. */
  32840. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32841. var mesh;
  32842. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32843. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32844. }
  32845. else {
  32846. mesh = new Mesh(parsedMesh.name, scene);
  32847. }
  32848. mesh.id = parsedMesh.id;
  32849. if (BABYLON.Tags) {
  32850. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32851. }
  32852. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  32853. if (parsedMesh.metadata !== undefined) {
  32854. mesh.metadata = parsedMesh.metadata;
  32855. }
  32856. if (parsedMesh.rotationQuaternion) {
  32857. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  32858. }
  32859. else if (parsedMesh.rotation) {
  32860. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  32861. }
  32862. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  32863. if (parsedMesh.localMatrix) {
  32864. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  32865. }
  32866. else if (parsedMesh.pivotMatrix) {
  32867. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  32868. }
  32869. mesh.setEnabled(parsedMesh.isEnabled);
  32870. mesh.isVisible = parsedMesh.isVisible;
  32871. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  32872. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  32873. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  32874. if (parsedMesh.applyFog !== undefined) {
  32875. mesh.applyFog = parsedMesh.applyFog;
  32876. }
  32877. if (parsedMesh.pickable !== undefined) {
  32878. mesh.isPickable = parsedMesh.pickable;
  32879. }
  32880. if (parsedMesh.alphaIndex !== undefined) {
  32881. mesh.alphaIndex = parsedMesh.alphaIndex;
  32882. }
  32883. mesh.receiveShadows = parsedMesh.receiveShadows;
  32884. mesh.billboardMode = parsedMesh.billboardMode;
  32885. if (parsedMesh.visibility !== undefined) {
  32886. mesh.visibility = parsedMesh.visibility;
  32887. }
  32888. mesh.checkCollisions = parsedMesh.checkCollisions;
  32889. if (parsedMesh.isBlocker !== undefined) {
  32890. mesh.isBlocker = parsedMesh.isBlocker;
  32891. }
  32892. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  32893. // freezeWorldMatrix
  32894. if (parsedMesh.freezeWorldMatrix) {
  32895. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  32896. }
  32897. // Parent
  32898. if (parsedMesh.parentId) {
  32899. mesh._waitingParentId = parsedMesh.parentId;
  32900. }
  32901. // Actions
  32902. if (parsedMesh.actions !== undefined) {
  32903. mesh._waitingActions = parsedMesh.actions;
  32904. }
  32905. // Overlay
  32906. if (parsedMesh.overlayAlpha !== undefined) {
  32907. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  32908. }
  32909. if (parsedMesh.overlayColor !== undefined) {
  32910. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  32911. }
  32912. if (parsedMesh.renderOverlay !== undefined) {
  32913. mesh.renderOverlay = parsedMesh.renderOverlay;
  32914. }
  32915. // Geometry
  32916. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  32917. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  32918. if (parsedMesh.delayLoadingFile) {
  32919. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  32920. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  32921. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  32922. if (parsedMesh._binaryInfo) {
  32923. mesh._binaryInfo = parsedMesh._binaryInfo;
  32924. }
  32925. mesh._delayInfo = [];
  32926. if (parsedMesh.hasUVs) {
  32927. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  32928. }
  32929. if (parsedMesh.hasUVs2) {
  32930. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  32931. }
  32932. if (parsedMesh.hasUVs3) {
  32933. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  32934. }
  32935. if (parsedMesh.hasUVs4) {
  32936. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  32937. }
  32938. if (parsedMesh.hasUVs5) {
  32939. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  32940. }
  32941. if (parsedMesh.hasUVs6) {
  32942. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  32943. }
  32944. if (parsedMesh.hasColors) {
  32945. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  32946. }
  32947. if (parsedMesh.hasMatricesIndices) {
  32948. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  32949. }
  32950. if (parsedMesh.hasMatricesWeights) {
  32951. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  32952. }
  32953. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  32954. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  32955. mesh._checkDelayState();
  32956. }
  32957. }
  32958. else {
  32959. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  32960. }
  32961. // Material
  32962. if (parsedMesh.materialId) {
  32963. mesh.setMaterialByID(parsedMesh.materialId);
  32964. }
  32965. else {
  32966. mesh.material = null;
  32967. }
  32968. // Morph targets
  32969. if (parsedMesh.morphTargetManagerId > -1) {
  32970. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  32971. }
  32972. // Skeleton
  32973. if (parsedMesh.skeletonId > -1) {
  32974. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  32975. if (parsedMesh.numBoneInfluencers) {
  32976. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  32977. }
  32978. }
  32979. // Animations
  32980. if (parsedMesh.animations) {
  32981. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  32982. var parsedAnimation = parsedMesh.animations[animationIndex];
  32983. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  32984. }
  32985. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  32986. }
  32987. if (parsedMesh.autoAnimate) {
  32988. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  32989. }
  32990. // Layer Mask
  32991. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  32992. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  32993. }
  32994. else {
  32995. mesh.layerMask = 0x0FFFFFFF;
  32996. }
  32997. // Physics
  32998. if (parsedMesh.physicsImpostor) {
  32999. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33000. mass: parsedMesh.physicsMass,
  33001. friction: parsedMesh.physicsFriction,
  33002. restitution: parsedMesh.physicsRestitution
  33003. }, scene);
  33004. }
  33005. // Instances
  33006. if (parsedMesh.instances) {
  33007. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33008. var parsedInstance = parsedMesh.instances[index];
  33009. var instance = mesh.createInstance(parsedInstance.name);
  33010. if (parsedInstance.id) {
  33011. instance.id = parsedInstance.id;
  33012. }
  33013. if (BABYLON.Tags) {
  33014. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33015. }
  33016. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33017. if (parsedInstance.parentId) {
  33018. instance._waitingParentId = parsedInstance.parentId;
  33019. }
  33020. if (parsedInstance.rotationQuaternion) {
  33021. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33022. }
  33023. else if (parsedInstance.rotation) {
  33024. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33025. }
  33026. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33027. instance.checkCollisions = mesh.checkCollisions;
  33028. if (parsedMesh.animations) {
  33029. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33030. parsedAnimation = parsedMesh.animations[animationIndex];
  33031. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33032. }
  33033. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33034. }
  33035. }
  33036. }
  33037. return mesh;
  33038. };
  33039. /**
  33040. * Creates a ribbon mesh.
  33041. * Please consider using the same method from the MeshBuilder class instead.
  33042. * 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.
  33043. *
  33044. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33045. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33046. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33047. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33048. * 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.
  33049. * 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.
  33050. * 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
  33051. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33052. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33053. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33054. */
  33055. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33056. if (closeArray === void 0) { closeArray = false; }
  33057. if (updatable === void 0) { updatable = false; }
  33058. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33059. pathArray: pathArray,
  33060. closeArray: closeArray,
  33061. closePath: closePath,
  33062. offset: offset,
  33063. updatable: updatable,
  33064. sideOrientation: sideOrientation,
  33065. instance: instance
  33066. }, scene);
  33067. };
  33068. /**
  33069. * Creates a plane polygonal mesh. By default, this is a disc.
  33070. * Please consider using the same method from the MeshBuilder class instead.
  33071. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33072. * 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.
  33073. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33074. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33075. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33076. */
  33077. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33078. if (scene === void 0) { scene = null; }
  33079. var options = {
  33080. radius: radius,
  33081. tessellation: tessellation,
  33082. sideOrientation: sideOrientation,
  33083. updatable: updatable
  33084. };
  33085. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33086. };
  33087. /**
  33088. * Creates a box mesh.
  33089. * Please consider using the same method from the MeshBuilder class instead.
  33090. * The parameter `size` sets the size (float) of each box side (default 1).
  33091. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33092. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33093. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33094. */
  33095. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33096. if (scene === void 0) { scene = null; }
  33097. var options = {
  33098. size: size,
  33099. sideOrientation: sideOrientation,
  33100. updatable: updatable
  33101. };
  33102. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33103. };
  33104. /**
  33105. * Creates a sphere mesh.
  33106. * Please consider using the same method from the MeshBuilder class instead.
  33107. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33108. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33109. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33110. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33111. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33112. */
  33113. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33114. var options = {
  33115. segments: segments,
  33116. diameterX: diameter,
  33117. diameterY: diameter,
  33118. diameterZ: diameter,
  33119. sideOrientation: sideOrientation,
  33120. updatable: updatable
  33121. };
  33122. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33123. };
  33124. /**
  33125. * Creates a cylinder or a cone mesh.
  33126. * Please consider using the same method from the MeshBuilder class instead.
  33127. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33128. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33129. * 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.
  33130. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33131. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33132. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33133. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33134. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33135. */
  33136. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33137. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33138. if (scene !== undefined) {
  33139. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33140. updatable = scene;
  33141. }
  33142. scene = subdivisions;
  33143. subdivisions = 1;
  33144. }
  33145. var options = {
  33146. height: height,
  33147. diameterTop: diameterTop,
  33148. diameterBottom: diameterBottom,
  33149. tessellation: tessellation,
  33150. subdivisions: subdivisions,
  33151. sideOrientation: sideOrientation,
  33152. updatable: updatable
  33153. };
  33154. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33155. };
  33156. // Torus (Code from SharpDX.org)
  33157. /**
  33158. * Creates a torus mesh.
  33159. * Please consider using the same method from the MeshBuilder class instead.
  33160. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33161. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33162. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33163. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33164. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33165. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33166. */
  33167. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33168. var options = {
  33169. diameter: diameter,
  33170. thickness: thickness,
  33171. tessellation: tessellation,
  33172. sideOrientation: sideOrientation,
  33173. updatable: updatable
  33174. };
  33175. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33176. };
  33177. /**
  33178. * Creates a torus knot mesh.
  33179. * Please consider using the same method from the MeshBuilder class instead.
  33180. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33181. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33182. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33183. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33184. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33185. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33186. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33187. */
  33188. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33189. var options = {
  33190. radius: radius,
  33191. tube: tube,
  33192. radialSegments: radialSegments,
  33193. tubularSegments: tubularSegments,
  33194. p: p,
  33195. q: q,
  33196. sideOrientation: sideOrientation,
  33197. updatable: updatable
  33198. };
  33199. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33200. };
  33201. /**
  33202. * Creates a line mesh.
  33203. * Please consider using the same method from the MeshBuilder class instead.
  33204. * 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.
  33205. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33206. * The parameter `points` is an array successive Vector3.
  33207. * 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
  33208. * When updating an instance, remember that only point positions can change, not the number of points.
  33209. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33210. */
  33211. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33212. if (scene === void 0) { scene = null; }
  33213. if (updatable === void 0) { updatable = false; }
  33214. if (instance === void 0) { instance = null; }
  33215. var options = {
  33216. points: points,
  33217. updatable: updatable,
  33218. instance: instance
  33219. };
  33220. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33221. };
  33222. /**
  33223. * Creates a dashed line mesh.
  33224. * Please consider using the same method from the MeshBuilder class instead.
  33225. * 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.
  33226. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33227. * The parameter `points` is an array successive Vector3.
  33228. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33229. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33230. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33231. * 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
  33232. * When updating an instance, remember that only point positions can change, not the number of points.
  33233. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33234. */
  33235. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33236. if (scene === void 0) { scene = null; }
  33237. var options = {
  33238. points: points,
  33239. dashSize: dashSize,
  33240. gapSize: gapSize,
  33241. dashNb: dashNb,
  33242. updatable: updatable,
  33243. instance: instance
  33244. };
  33245. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33246. };
  33247. /**
  33248. * Creates a polygon mesh.
  33249. * Please consider using the same method from the MeshBuilder class instead.
  33250. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33251. * 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.
  33252. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33253. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33254. * Remember you can only change the shape positions, not their number when updating a polygon.
  33255. */
  33256. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33257. var options = {
  33258. shape: shape,
  33259. holes: holes,
  33260. updatable: updatable,
  33261. sideOrientation: sideOrientation
  33262. };
  33263. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33264. };
  33265. /**
  33266. * Creates an extruded polygon mesh, with depth in the Y direction.
  33267. * Please consider using the same method from the MeshBuilder class instead.
  33268. */
  33269. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33270. var options = {
  33271. shape: shape,
  33272. holes: holes,
  33273. depth: depth,
  33274. updatable: updatable,
  33275. sideOrientation: sideOrientation
  33276. };
  33277. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33278. };
  33279. /**
  33280. * Creates an extruded shape mesh.
  33281. * 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.
  33282. * Please consider using the same method from the MeshBuilder class instead.
  33283. *
  33284. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33285. * 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
  33286. * extruded along the Z axis.
  33287. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33288. * 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.
  33289. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33290. * 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
  33291. * 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
  33292. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33293. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33294. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33295. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33296. */
  33297. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33298. if (scene === void 0) { scene = null; }
  33299. var options = {
  33300. shape: shape,
  33301. path: path,
  33302. scale: scale,
  33303. rotation: rotation,
  33304. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33305. sideOrientation: sideOrientation,
  33306. instance: instance,
  33307. updatable: updatable
  33308. };
  33309. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33310. };
  33311. /**
  33312. * Creates an custom extruded shape mesh.
  33313. * 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.
  33314. * Please consider using the same method from the MeshBuilder class instead.
  33315. *
  33316. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33317. * 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
  33318. * extruded along the Z axis.
  33319. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33320. * 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
  33321. * and the distance of this point from the begining of the path :
  33322. * ```javascript
  33323. * var rotationFunction = function(i, distance) {
  33324. * // do things
  33325. * return rotationValue; }
  33326. * ```
  33327. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33328. * 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
  33329. * and the distance of this point from the begining of the path :
  33330. * ```javascript
  33331. * var scaleFunction = function(i, distance) {
  33332. * // do things
  33333. * return scaleValue;}
  33334. * ```
  33335. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33336. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33337. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33338. * 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
  33339. * 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
  33340. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33341. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33342. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33343. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33344. */
  33345. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33346. var options = {
  33347. shape: shape,
  33348. path: path,
  33349. scaleFunction: scaleFunction,
  33350. rotationFunction: rotationFunction,
  33351. ribbonCloseArray: ribbonCloseArray,
  33352. ribbonClosePath: ribbonClosePath,
  33353. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33354. sideOrientation: sideOrientation,
  33355. instance: instance,
  33356. updatable: updatable
  33357. };
  33358. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33359. };
  33360. /**
  33361. * Creates lathe mesh.
  33362. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33363. * Please consider using the same method from the MeshBuilder class instead.
  33364. * 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
  33365. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33366. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33367. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33368. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33369. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33370. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33371. */
  33372. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33373. var options = {
  33374. shape: shape,
  33375. radius: radius,
  33376. tessellation: tessellation,
  33377. sideOrientation: sideOrientation,
  33378. updatable: updatable
  33379. };
  33380. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33381. };
  33382. /**
  33383. * Creates a plane mesh.
  33384. * Please consider using the same method from the MeshBuilder class instead.
  33385. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33386. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33387. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33388. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33389. */
  33390. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33391. var options = {
  33392. size: size,
  33393. width: size,
  33394. height: size,
  33395. sideOrientation: sideOrientation,
  33396. updatable: updatable
  33397. };
  33398. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33399. };
  33400. /**
  33401. * Creates a ground mesh.
  33402. * Please consider using the same method from the MeshBuilder class instead.
  33403. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33404. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33405. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33406. */
  33407. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33408. var options = {
  33409. width: width,
  33410. height: height,
  33411. subdivisions: subdivisions,
  33412. updatable: updatable
  33413. };
  33414. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33415. };
  33416. /**
  33417. * Creates a tiled ground mesh.
  33418. * Please consider using the same method from the MeshBuilder class instead.
  33419. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33420. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33421. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33422. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33423. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33424. * numbers of subdivisions on the ground width and height of each tile.
  33425. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33426. */
  33427. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33428. var options = {
  33429. xmin: xmin,
  33430. zmin: zmin,
  33431. xmax: xmax,
  33432. zmax: zmax,
  33433. subdivisions: subdivisions,
  33434. precision: precision,
  33435. updatable: updatable
  33436. };
  33437. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33438. };
  33439. /**
  33440. * Creates a ground mesh from a height map.
  33441. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33442. * Please consider using the same method from the MeshBuilder class instead.
  33443. * The parameter `url` sets the URL of the height map image resource.
  33444. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33445. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33446. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33447. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33448. * 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).
  33449. * This function is passed the newly built mesh :
  33450. * ```javascript
  33451. * function(mesh) { // do things
  33452. * return; }
  33453. * ```
  33454. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33455. */
  33456. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33457. var options = {
  33458. width: width,
  33459. height: height,
  33460. subdivisions: subdivisions,
  33461. minHeight: minHeight,
  33462. maxHeight: maxHeight,
  33463. updatable: updatable,
  33464. onReady: onReady
  33465. };
  33466. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33467. };
  33468. /**
  33469. * Creates a tube mesh.
  33470. * 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.
  33471. * Please consider using the same method from the MeshBuilder class instead.
  33472. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33473. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33474. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33475. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33476. * 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.
  33477. * It must return a radius value (positive float) :
  33478. * ```javascript
  33479. * var radiusFunction = function(i, distance) {
  33480. * // do things
  33481. * return radius; }
  33482. * ```
  33483. * 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
  33484. * 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
  33485. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33486. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33487. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33488. */
  33489. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33490. var options = {
  33491. path: path,
  33492. radius: radius,
  33493. tessellation: tessellation,
  33494. radiusFunction: radiusFunction,
  33495. arc: 1,
  33496. cap: cap,
  33497. updatable: updatable,
  33498. sideOrientation: sideOrientation,
  33499. instance: instance
  33500. };
  33501. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33502. };
  33503. /**
  33504. * Creates a polyhedron mesh.
  33505. * Please consider using the same method from the MeshBuilder class instead.
  33506. * 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
  33507. * to choose the wanted type.
  33508. * The parameter `size` (positive float, default 1) sets the polygon size.
  33509. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33510. * 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`.
  33511. * 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
  33512. * 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)`).
  33513. * 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
  33514. * 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.
  33515. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33516. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33517. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33518. */
  33519. Mesh.CreatePolyhedron = function (name, options, scene) {
  33520. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33521. };
  33522. /**
  33523. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33524. * Please consider using the same method from the MeshBuilder class instead.
  33525. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33526. * 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`).
  33527. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33528. * 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.
  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.CreateIcoSphere = function (name, options, scene) {
  33534. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33535. };
  33536. /**
  33537. * Creates a decal mesh.
  33538. * Please consider using the same method from the MeshBuilder class instead.
  33539. * 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.
  33540. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33541. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33542. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33543. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33544. */
  33545. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33546. var options = {
  33547. position: position,
  33548. normal: normal,
  33549. size: size,
  33550. angle: angle
  33551. };
  33552. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33553. };
  33554. // Skeletons
  33555. /**
  33556. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33557. */
  33558. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33559. if (!this._sourcePositions) {
  33560. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33561. if (!source) {
  33562. return this._sourcePositions;
  33563. }
  33564. this._sourcePositions = new Float32Array(source);
  33565. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33566. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33567. }
  33568. }
  33569. return this._sourcePositions;
  33570. };
  33571. /**
  33572. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33573. */
  33574. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33575. if (!this._sourceNormals) {
  33576. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33577. if (!source) {
  33578. return this._sourceNormals;
  33579. }
  33580. this._sourceNormals = new Float32Array(source);
  33581. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33582. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33583. }
  33584. }
  33585. return this._sourceNormals;
  33586. };
  33587. /**
  33588. * Updates the vertex buffer by applying transformation from the bones.
  33589. * Returns the Mesh.
  33590. *
  33591. * @param {skeleton} skeleton to apply
  33592. */
  33593. Mesh.prototype.applySkeleton = function (skeleton) {
  33594. if (!this.geometry) {
  33595. return this;
  33596. }
  33597. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33598. return this;
  33599. }
  33600. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33601. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33602. return this;
  33603. }
  33604. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33605. return this;
  33606. }
  33607. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33608. return this;
  33609. }
  33610. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33611. return this;
  33612. }
  33613. if (!this._sourcePositions) {
  33614. var submeshes = this.subMeshes.slice();
  33615. this.setPositionsForCPUSkinning();
  33616. this.subMeshes = submeshes;
  33617. }
  33618. if (!this._sourceNormals) {
  33619. this.setNormalsForCPUSkinning();
  33620. }
  33621. // positionsData checks for not being Float32Array will only pass at most once
  33622. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33623. if (!positionsData) {
  33624. return this;
  33625. }
  33626. if (!(positionsData instanceof Float32Array)) {
  33627. positionsData = new Float32Array(positionsData);
  33628. }
  33629. // normalsData checks for not being Float32Array will only pass at most once
  33630. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33631. if (!normalsData) {
  33632. return this;
  33633. }
  33634. if (!(normalsData instanceof Float32Array)) {
  33635. normalsData = new Float32Array(normalsData);
  33636. }
  33637. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33638. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33639. if (!matricesWeightsData || !matricesIndicesData) {
  33640. return this;
  33641. }
  33642. var needExtras = this.numBoneInfluencers > 4;
  33643. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33644. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33645. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33646. var tempVector3 = BABYLON.Vector3.Zero();
  33647. var finalMatrix = new BABYLON.Matrix();
  33648. var tempMatrix = new BABYLON.Matrix();
  33649. var matWeightIdx = 0;
  33650. var inf;
  33651. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33652. var weight;
  33653. for (inf = 0; inf < 4; inf++) {
  33654. weight = matricesWeightsData[matWeightIdx + inf];
  33655. if (weight > 0) {
  33656. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33657. finalMatrix.addToSelf(tempMatrix);
  33658. }
  33659. else
  33660. break;
  33661. }
  33662. if (needExtras) {
  33663. for (inf = 0; inf < 4; inf++) {
  33664. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33665. if (weight > 0) {
  33666. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33667. finalMatrix.addToSelf(tempMatrix);
  33668. }
  33669. else
  33670. break;
  33671. }
  33672. }
  33673. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33674. tempVector3.toArray(positionsData, index);
  33675. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33676. tempVector3.toArray(normalsData, index);
  33677. finalMatrix.reset();
  33678. }
  33679. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33680. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33681. return this;
  33682. };
  33683. // Tools
  33684. /**
  33685. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33686. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33687. */
  33688. Mesh.MinMax = function (meshes) {
  33689. var minVector = null;
  33690. var maxVector = null;
  33691. meshes.forEach(function (mesh, index, array) {
  33692. var boundingInfo = mesh.getBoundingInfo();
  33693. var boundingBox = boundingInfo.boundingBox;
  33694. if (!minVector || !maxVector) {
  33695. minVector = boundingBox.minimumWorld;
  33696. maxVector = boundingBox.maximumWorld;
  33697. }
  33698. else {
  33699. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33700. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33701. }
  33702. });
  33703. if (!minVector || !maxVector) {
  33704. return {
  33705. min: BABYLON.Vector3.Zero(),
  33706. max: BABYLON.Vector3.Zero()
  33707. };
  33708. }
  33709. return {
  33710. min: minVector,
  33711. max: maxVector
  33712. };
  33713. };
  33714. /**
  33715. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33716. */
  33717. Mesh.Center = function (meshesOrMinMaxVector) {
  33718. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33719. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33720. };
  33721. /**
  33722. * Merge the array of meshes into a single mesh for performance reasons.
  33723. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33724. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33725. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33726. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33727. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33728. */
  33729. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33730. if (disposeSource === void 0) { disposeSource = true; }
  33731. var index;
  33732. if (!allow32BitsIndices) {
  33733. var totalVertices = 0;
  33734. // Counting vertices
  33735. for (index = 0; index < meshes.length; index++) {
  33736. if (meshes[index]) {
  33737. totalVertices += meshes[index].getTotalVertices();
  33738. if (totalVertices > 65536) {
  33739. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33740. return null;
  33741. }
  33742. }
  33743. }
  33744. }
  33745. // Merge
  33746. var vertexData = null;
  33747. var otherVertexData;
  33748. var indiceArray = new Array();
  33749. var source = null;
  33750. for (index = 0; index < meshes.length; index++) {
  33751. if (meshes[index]) {
  33752. meshes[index].computeWorldMatrix(true);
  33753. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33754. otherVertexData.transform(meshes[index].getWorldMatrix());
  33755. if (vertexData) {
  33756. vertexData.merge(otherVertexData);
  33757. }
  33758. else {
  33759. vertexData = otherVertexData;
  33760. source = meshes[index];
  33761. }
  33762. if (subdivideWithSubMeshes) {
  33763. indiceArray.push(meshes[index].getTotalIndices());
  33764. }
  33765. }
  33766. }
  33767. source = source;
  33768. if (!meshSubclass) {
  33769. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33770. }
  33771. vertexData.applyToMesh(meshSubclass);
  33772. // Setting properties
  33773. meshSubclass.material = source.material;
  33774. meshSubclass.checkCollisions = source.checkCollisions;
  33775. // Cleaning
  33776. if (disposeSource) {
  33777. for (index = 0; index < meshes.length; index++) {
  33778. if (meshes[index]) {
  33779. meshes[index].dispose();
  33780. }
  33781. }
  33782. }
  33783. // Subdivide
  33784. if (subdivideWithSubMeshes) {
  33785. //-- Suppresions du submesh global
  33786. meshSubclass.releaseSubMeshes();
  33787. index = 0;
  33788. var offset = 0;
  33789. //-- aplique la subdivision en fonction du tableau d'indices
  33790. while (index < indiceArray.length) {
  33791. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33792. offset += indiceArray[index];
  33793. index++;
  33794. }
  33795. }
  33796. return meshSubclass;
  33797. };
  33798. // Consts
  33799. Mesh._FRONTSIDE = 0;
  33800. Mesh._BACKSIDE = 1;
  33801. Mesh._DOUBLESIDE = 2;
  33802. Mesh._DEFAULTSIDE = 0;
  33803. Mesh._NO_CAP = 0;
  33804. Mesh._CAP_START = 1;
  33805. Mesh._CAP_END = 2;
  33806. Mesh._CAP_ALL = 3;
  33807. return Mesh;
  33808. }(BABYLON.AbstractMesh));
  33809. BABYLON.Mesh = Mesh;
  33810. })(BABYLON || (BABYLON = {}));
  33811. //# sourceMappingURL=babylon.mesh.js.map
  33812. var BABYLON;
  33813. (function (BABYLON) {
  33814. var BaseSubMesh = /** @class */ (function () {
  33815. function BaseSubMesh() {
  33816. }
  33817. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33818. get: function () {
  33819. return this._materialEffect;
  33820. },
  33821. enumerable: true,
  33822. configurable: true
  33823. });
  33824. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33825. if (defines === void 0) { defines = null; }
  33826. if (this._materialEffect === effect) {
  33827. if (!effect) {
  33828. this._materialDefines = null;
  33829. }
  33830. return;
  33831. }
  33832. this._materialDefines = defines;
  33833. this._materialEffect = effect;
  33834. };
  33835. return BaseSubMesh;
  33836. }());
  33837. BABYLON.BaseSubMesh = BaseSubMesh;
  33838. var SubMesh = /** @class */ (function (_super) {
  33839. __extends(SubMesh, _super);
  33840. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33841. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33842. var _this = _super.call(this) || this;
  33843. _this.materialIndex = materialIndex;
  33844. _this.verticesStart = verticesStart;
  33845. _this.verticesCount = verticesCount;
  33846. _this.indexStart = indexStart;
  33847. _this.indexCount = indexCount;
  33848. _this._renderId = 0;
  33849. _this._mesh = mesh;
  33850. _this._renderingMesh = renderingMesh || mesh;
  33851. mesh.subMeshes.push(_this);
  33852. _this._trianglePlanes = [];
  33853. _this._id = mesh.subMeshes.length - 1;
  33854. if (createBoundingBox) {
  33855. _this.refreshBoundingInfo();
  33856. mesh.computeWorldMatrix(true);
  33857. }
  33858. return _this;
  33859. }
  33860. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33861. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33862. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  33863. };
  33864. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  33865. get: function () {
  33866. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  33867. },
  33868. enumerable: true,
  33869. configurable: true
  33870. });
  33871. /**
  33872. * Returns the submesh BoudingInfo object.
  33873. */
  33874. SubMesh.prototype.getBoundingInfo = function () {
  33875. if (this.IsGlobal) {
  33876. return this._mesh.getBoundingInfo();
  33877. }
  33878. return this._boundingInfo;
  33879. };
  33880. /**
  33881. * Sets the submesh BoundingInfo.
  33882. * Return the SubMesh.
  33883. */
  33884. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  33885. this._boundingInfo = boundingInfo;
  33886. return this;
  33887. };
  33888. /**
  33889. * Returns the mesh of the current submesh.
  33890. */
  33891. SubMesh.prototype.getMesh = function () {
  33892. return this._mesh;
  33893. };
  33894. /**
  33895. * Returns the rendering mesh of the submesh.
  33896. */
  33897. SubMesh.prototype.getRenderingMesh = function () {
  33898. return this._renderingMesh;
  33899. };
  33900. /**
  33901. * Returns the submesh material.
  33902. */
  33903. SubMesh.prototype.getMaterial = function () {
  33904. var rootMaterial = this._renderingMesh.material;
  33905. if (rootMaterial === null || rootMaterial === undefined) {
  33906. return this._mesh.getScene().defaultMaterial;
  33907. }
  33908. else if (rootMaterial.getSubMaterial) {
  33909. var multiMaterial = rootMaterial;
  33910. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  33911. if (this._currentMaterial !== effectiveMaterial) {
  33912. this._currentMaterial = effectiveMaterial;
  33913. this._materialDefines = null;
  33914. }
  33915. return effectiveMaterial;
  33916. }
  33917. return rootMaterial;
  33918. };
  33919. // Methods
  33920. /**
  33921. * Sets a new updated BoundingInfo object to the submesh.
  33922. * Returns the SubMesh.
  33923. */
  33924. SubMesh.prototype.refreshBoundingInfo = function () {
  33925. this._lastColliderWorldVertices = null;
  33926. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  33927. return this;
  33928. }
  33929. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33930. if (!data) {
  33931. this._boundingInfo = this._mesh.getBoundingInfo();
  33932. return this;
  33933. }
  33934. var indices = this._renderingMesh.getIndices();
  33935. var extend;
  33936. //is this the only submesh?
  33937. if (this.indexStart === 0 && this.indexCount === indices.length) {
  33938. var boundingInfo = this._renderingMesh.getBoundingInfo();
  33939. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  33940. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  33941. }
  33942. else {
  33943. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  33944. }
  33945. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  33946. return this;
  33947. };
  33948. SubMesh.prototype._checkCollision = function (collider) {
  33949. var boundingInfo = this.getBoundingInfo();
  33950. return boundingInfo._checkCollision(collider);
  33951. };
  33952. /**
  33953. * Updates the submesh BoundingInfo.
  33954. * Returns the Submesh.
  33955. */
  33956. SubMesh.prototype.updateBoundingInfo = function (world) {
  33957. var boundingInfo = this.getBoundingInfo();
  33958. if (!boundingInfo) {
  33959. this.refreshBoundingInfo();
  33960. boundingInfo = this.getBoundingInfo();
  33961. }
  33962. boundingInfo.update(world);
  33963. return this;
  33964. };
  33965. /**
  33966. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  33967. * Boolean returned.
  33968. */
  33969. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  33970. var boundingInfo = this.getBoundingInfo();
  33971. if (!boundingInfo) {
  33972. return false;
  33973. }
  33974. return boundingInfo.isInFrustum(frustumPlanes);
  33975. };
  33976. /**
  33977. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  33978. * Boolean returned.
  33979. */
  33980. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  33981. var boundingInfo = this.getBoundingInfo();
  33982. if (!boundingInfo) {
  33983. return false;
  33984. }
  33985. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  33986. };
  33987. /**
  33988. * Renders the submesh.
  33989. * Returns it.
  33990. */
  33991. SubMesh.prototype.render = function (enableAlphaMode) {
  33992. this._renderingMesh.render(this, enableAlphaMode);
  33993. return this;
  33994. };
  33995. /**
  33996. * Returns a new Index Buffer.
  33997. * Type returned : WebGLBuffer.
  33998. */
  33999. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34000. if (!this._linesIndexBuffer) {
  34001. var linesIndices = [];
  34002. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34003. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34004. }
  34005. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34006. this.linesIndexCount = linesIndices.length;
  34007. }
  34008. return this._linesIndexBuffer;
  34009. };
  34010. /**
  34011. * True is the passed Ray intersects the submesh bounding box.
  34012. * Boolean returned.
  34013. */
  34014. SubMesh.prototype.canIntersects = function (ray) {
  34015. var boundingInfo = this.getBoundingInfo();
  34016. if (!boundingInfo) {
  34017. return false;
  34018. }
  34019. return ray.intersectsBox(boundingInfo.boundingBox);
  34020. };
  34021. /**
  34022. * Returns an object IntersectionInfo.
  34023. */
  34024. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34025. var intersectInfo = null;
  34026. var material = this.getMaterial();
  34027. if (!material) {
  34028. return null;
  34029. }
  34030. switch (material.fillMode) {
  34031. case BABYLON.Material.PointListDrawMode:
  34032. case BABYLON.Material.LineListDrawMode:
  34033. case BABYLON.Material.LineLoopDrawMode:
  34034. case BABYLON.Material.LineStripDrawMode:
  34035. case BABYLON.Material.TriangleFanDrawMode:
  34036. case BABYLON.Material.TriangleStripDrawMode:
  34037. return null;
  34038. }
  34039. // LineMesh first as it's also a Mesh...
  34040. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34041. var lineMesh = this._mesh;
  34042. // Line test
  34043. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34044. var p0 = positions[indices[index]];
  34045. var p1 = positions[indices[index + 1]];
  34046. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34047. if (length < 0) {
  34048. continue;
  34049. }
  34050. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34051. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34052. if (fastCheck) {
  34053. break;
  34054. }
  34055. }
  34056. }
  34057. }
  34058. else {
  34059. // Triangles test
  34060. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34061. var p0 = positions[indices[index]];
  34062. var p1 = positions[indices[index + 1]];
  34063. var p2 = positions[indices[index + 2]];
  34064. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34065. if (currentIntersectInfo) {
  34066. if (currentIntersectInfo.distance < 0) {
  34067. continue;
  34068. }
  34069. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34070. intersectInfo = currentIntersectInfo;
  34071. intersectInfo.faceId = index / 3;
  34072. if (fastCheck) {
  34073. break;
  34074. }
  34075. }
  34076. }
  34077. }
  34078. }
  34079. return intersectInfo;
  34080. };
  34081. SubMesh.prototype._rebuild = function () {
  34082. if (this._linesIndexBuffer) {
  34083. this._linesIndexBuffer = null;
  34084. }
  34085. };
  34086. // Clone
  34087. /**
  34088. * Creates a new Submesh from the passed Mesh.
  34089. */
  34090. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34091. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34092. if (!this.IsGlobal) {
  34093. var boundingInfo = this.getBoundingInfo();
  34094. if (!boundingInfo) {
  34095. return result;
  34096. }
  34097. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34098. }
  34099. return result;
  34100. };
  34101. // Dispose
  34102. /**
  34103. * Disposes the Submesh.
  34104. * Returns nothing.
  34105. */
  34106. SubMesh.prototype.dispose = function () {
  34107. if (this._linesIndexBuffer) {
  34108. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34109. this._linesIndexBuffer = null;
  34110. }
  34111. // Remove from mesh
  34112. var index = this._mesh.subMeshes.indexOf(this);
  34113. this._mesh.subMeshes.splice(index, 1);
  34114. };
  34115. // Statics
  34116. /**
  34117. * Creates a new Submesh from the passed parameters :
  34118. * - materialIndex (integer) : the index of the main mesh material.
  34119. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34120. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34121. * - mesh (Mesh) : the main mesh to create the submesh from.
  34122. * - renderingMesh (optional Mesh) : rendering mesh.
  34123. */
  34124. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34125. var minVertexIndex = Number.MAX_VALUE;
  34126. var maxVertexIndex = -Number.MAX_VALUE;
  34127. renderingMesh = (renderingMesh || mesh);
  34128. var indices = renderingMesh.getIndices();
  34129. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34130. var vertexIndex = indices[index];
  34131. if (vertexIndex < minVertexIndex)
  34132. minVertexIndex = vertexIndex;
  34133. if (vertexIndex > maxVertexIndex)
  34134. maxVertexIndex = vertexIndex;
  34135. }
  34136. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34137. };
  34138. return SubMesh;
  34139. }(BaseSubMesh));
  34140. BABYLON.SubMesh = SubMesh;
  34141. })(BABYLON || (BABYLON = {}));
  34142. //# sourceMappingURL=babylon.subMesh.js.map
  34143. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34144. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34145. s = arguments[i];
  34146. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34147. t[p] = s[p];
  34148. }
  34149. return t;
  34150. };
  34151. var BABYLON;
  34152. (function (BABYLON) {
  34153. /**
  34154. * Manages the defines for the Material
  34155. */
  34156. var MaterialDefines = /** @class */ (function () {
  34157. function MaterialDefines() {
  34158. this._isDirty = true;
  34159. /** @hidden */
  34160. this._areLightsDirty = true;
  34161. /** @hidden */
  34162. this._areAttributesDirty = true;
  34163. /** @hidden */
  34164. this._areTexturesDirty = true;
  34165. /** @hidden */
  34166. this._areFresnelDirty = true;
  34167. /** @hidden */
  34168. this._areMiscDirty = true;
  34169. /** @hidden */
  34170. this._areImageProcessingDirty = true;
  34171. /** @hidden */
  34172. this._normals = false;
  34173. /** @hidden */
  34174. this._uvs = false;
  34175. /** @hidden */
  34176. this._needNormals = false;
  34177. /** @hidden */
  34178. this._needUVs = false;
  34179. }
  34180. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34181. /**
  34182. * Specifies if the material needs to be re-calculated
  34183. */
  34184. get: function () {
  34185. return this._isDirty;
  34186. },
  34187. enumerable: true,
  34188. configurable: true
  34189. });
  34190. /**
  34191. * Marks the material to indicate that it has been re-calculated
  34192. */
  34193. MaterialDefines.prototype.markAsProcessed = function () {
  34194. this._isDirty = false;
  34195. this._areAttributesDirty = false;
  34196. this._areTexturesDirty = false;
  34197. this._areFresnelDirty = false;
  34198. this._areLightsDirty = false;
  34199. this._areMiscDirty = false;
  34200. this._areImageProcessingDirty = false;
  34201. };
  34202. /**
  34203. * Marks the material to indicate that it needs to be re-calculated
  34204. */
  34205. MaterialDefines.prototype.markAsUnprocessed = function () {
  34206. this._isDirty = true;
  34207. };
  34208. /**
  34209. * Marks the material to indicate all of its defines need to be re-calculated
  34210. */
  34211. MaterialDefines.prototype.markAllAsDirty = function () {
  34212. this._areTexturesDirty = true;
  34213. this._areAttributesDirty = true;
  34214. this._areLightsDirty = true;
  34215. this._areFresnelDirty = true;
  34216. this._areMiscDirty = true;
  34217. this._areImageProcessingDirty = true;
  34218. this._isDirty = true;
  34219. };
  34220. /**
  34221. * Marks the material to indicate that image processing needs to be re-calculated
  34222. */
  34223. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34224. this._areImageProcessingDirty = true;
  34225. this._isDirty = true;
  34226. };
  34227. /**
  34228. * Marks the material to indicate the lights need to be re-calculated
  34229. */
  34230. MaterialDefines.prototype.markAsLightDirty = function () {
  34231. this._areLightsDirty = true;
  34232. this._isDirty = true;
  34233. };
  34234. /**
  34235. * Marks the attribute state as changed
  34236. */
  34237. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34238. this._areAttributesDirty = true;
  34239. this._isDirty = true;
  34240. };
  34241. /**
  34242. * Marks the texture state as changed
  34243. */
  34244. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34245. this._areTexturesDirty = true;
  34246. this._isDirty = true;
  34247. };
  34248. /**
  34249. * Marks the fresnel state as changed
  34250. */
  34251. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34252. this._areFresnelDirty = true;
  34253. this._isDirty = true;
  34254. };
  34255. /**
  34256. * Marks the misc state as changed
  34257. */
  34258. MaterialDefines.prototype.markAsMiscDirty = function () {
  34259. this._areMiscDirty = true;
  34260. this._isDirty = true;
  34261. };
  34262. /**
  34263. * Rebuilds the material defines
  34264. */
  34265. MaterialDefines.prototype.rebuild = function () {
  34266. if (this._keys) {
  34267. delete this._keys;
  34268. }
  34269. this._keys = [];
  34270. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34271. var key = _a[_i];
  34272. if (key[0] === "_") {
  34273. continue;
  34274. }
  34275. this._keys.push(key);
  34276. }
  34277. };
  34278. /**
  34279. * Specifies if two material defines are equal
  34280. * @param other - A material define instance to compare to
  34281. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34282. */
  34283. MaterialDefines.prototype.isEqual = function (other) {
  34284. if (this._keys.length !== other._keys.length) {
  34285. return false;
  34286. }
  34287. for (var index = 0; index < this._keys.length; index++) {
  34288. var prop = this._keys[index];
  34289. if (this[prop] !== other[prop]) {
  34290. return false;
  34291. }
  34292. }
  34293. return true;
  34294. };
  34295. /**
  34296. * Clones this instance's defines to another instance
  34297. * @param other - material defines to clone values to
  34298. */
  34299. MaterialDefines.prototype.cloneTo = function (other) {
  34300. if (this._keys.length !== other._keys.length) {
  34301. other._keys = this._keys.slice(0);
  34302. }
  34303. for (var index = 0; index < this._keys.length; index++) {
  34304. var prop = this._keys[index];
  34305. other[prop] = this[prop];
  34306. }
  34307. };
  34308. /**
  34309. * Resets the material define values
  34310. */
  34311. MaterialDefines.prototype.reset = function () {
  34312. for (var index = 0; index < this._keys.length; index++) {
  34313. var prop = this._keys[index];
  34314. var type = typeof this[prop];
  34315. switch (type) {
  34316. case "number":
  34317. this[prop] = 0;
  34318. break;
  34319. case "string":
  34320. this[prop] = "";
  34321. break;
  34322. default:
  34323. this[prop] = false;
  34324. break;
  34325. }
  34326. }
  34327. };
  34328. /**
  34329. * Converts the material define values to a string
  34330. * @returns - String of material define information
  34331. */
  34332. MaterialDefines.prototype.toString = function () {
  34333. var result = "";
  34334. for (var index = 0; index < this._keys.length; index++) {
  34335. var prop = this._keys[index];
  34336. var value = this[prop];
  34337. var type = typeof value;
  34338. switch (type) {
  34339. case "number":
  34340. case "string":
  34341. result += "#define " + prop + " " + value + "\n";
  34342. break;
  34343. default:
  34344. if (value) {
  34345. result += "#define " + prop + "\n";
  34346. }
  34347. break;
  34348. }
  34349. }
  34350. return result;
  34351. };
  34352. return MaterialDefines;
  34353. }());
  34354. BABYLON.MaterialDefines = MaterialDefines;
  34355. /**
  34356. * Base class for the main features of a material in Babylon.js
  34357. */
  34358. var Material = /** @class */ (function () {
  34359. /**
  34360. * Creates a material instance
  34361. * @param name defines the name of the material
  34362. * @param scene defines the scene to reference
  34363. * @param doNotAdd specifies if the material should be added to the scene
  34364. */
  34365. function Material(name, scene, doNotAdd) {
  34366. /**
  34367. * Specifies if the ready state should be checked on each call
  34368. */
  34369. this.checkReadyOnEveryCall = false;
  34370. /**
  34371. * Specifies if the ready state should be checked once
  34372. */
  34373. this.checkReadyOnlyOnce = false;
  34374. /**
  34375. * The state of the material
  34376. */
  34377. this.state = "";
  34378. /**
  34379. * The alpha value of the material
  34380. */
  34381. this._alpha = 1.0;
  34382. /**
  34383. * Specifies if back face culling is enabled
  34384. */
  34385. this._backFaceCulling = true;
  34386. /**
  34387. * Specifies if the material should be serialized
  34388. */
  34389. this.doNotSerialize = false;
  34390. /**
  34391. * Specifies if the effect should be stored on sub meshes
  34392. */
  34393. this.storeEffectOnSubMeshes = false;
  34394. /**
  34395. * An event triggered when the material is disposed
  34396. */
  34397. this.onDisposeObservable = new BABYLON.Observable();
  34398. /**
  34399. * An event triggered when the material is bound
  34400. */
  34401. this.onBindObservable = new BABYLON.Observable();
  34402. /**
  34403. * An event triggered when the material is unbound
  34404. */
  34405. this.onUnBindObservable = new BABYLON.Observable();
  34406. /**
  34407. * Stores the value of the alpha mode
  34408. */
  34409. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34410. /**
  34411. * Stores the state of the need depth pre-pass value
  34412. */
  34413. this._needDepthPrePass = false;
  34414. /**
  34415. * Specifies if depth writing should be disabled
  34416. */
  34417. this.disableDepthWrite = false;
  34418. /**
  34419. * Specifies if depth writing should be forced
  34420. */
  34421. this.forceDepthWrite = false;
  34422. /**
  34423. * Specifies if there should be a separate pass for culling
  34424. */
  34425. this.separateCullingPass = false;
  34426. /**
  34427. * Stores the state specifing if fog should be enabled
  34428. */
  34429. this._fogEnabled = true;
  34430. /**
  34431. * Stores the size of points
  34432. */
  34433. this.pointSize = 1.0;
  34434. /**
  34435. * Stores the z offset value
  34436. */
  34437. this.zOffset = 0;
  34438. /**
  34439. * Specifies if the material was previously ready
  34440. */
  34441. this._wasPreviouslyReady = false;
  34442. /**
  34443. * Stores the fill mode state
  34444. */
  34445. this._fillMode = Material.TriangleFillMode;
  34446. this.name = name;
  34447. this.id = name || BABYLON.Tools.RandomId();
  34448. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34449. if (this._scene.useRightHandedSystem) {
  34450. this.sideOrientation = Material.ClockWiseSideOrientation;
  34451. }
  34452. else {
  34453. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34454. }
  34455. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34456. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34457. if (!doNotAdd) {
  34458. this._scene.materials.push(this);
  34459. }
  34460. }
  34461. Object.defineProperty(Material, "TriangleFillMode", {
  34462. /**
  34463. * Returns the triangle fill mode
  34464. */
  34465. get: function () {
  34466. return Material._TriangleFillMode;
  34467. },
  34468. enumerable: true,
  34469. configurable: true
  34470. });
  34471. Object.defineProperty(Material, "WireFrameFillMode", {
  34472. /**
  34473. * Returns the wireframe mode
  34474. */
  34475. get: function () {
  34476. return Material._WireFrameFillMode;
  34477. },
  34478. enumerable: true,
  34479. configurable: true
  34480. });
  34481. Object.defineProperty(Material, "PointFillMode", {
  34482. /**
  34483. * Returns the point fill mode
  34484. */
  34485. get: function () {
  34486. return Material._PointFillMode;
  34487. },
  34488. enumerable: true,
  34489. configurable: true
  34490. });
  34491. Object.defineProperty(Material, "PointListDrawMode", {
  34492. /**
  34493. * Returns the point list draw mode
  34494. */
  34495. get: function () {
  34496. return Material._PointListDrawMode;
  34497. },
  34498. enumerable: true,
  34499. configurable: true
  34500. });
  34501. Object.defineProperty(Material, "LineListDrawMode", {
  34502. /**
  34503. * Returns the line list draw mode
  34504. */
  34505. get: function () {
  34506. return Material._LineListDrawMode;
  34507. },
  34508. enumerable: true,
  34509. configurable: true
  34510. });
  34511. Object.defineProperty(Material, "LineLoopDrawMode", {
  34512. /**
  34513. * Returns the line loop draw mode
  34514. */
  34515. get: function () {
  34516. return Material._LineLoopDrawMode;
  34517. },
  34518. enumerable: true,
  34519. configurable: true
  34520. });
  34521. Object.defineProperty(Material, "LineStripDrawMode", {
  34522. /**
  34523. * Returns the line strip draw mode
  34524. */
  34525. get: function () {
  34526. return Material._LineStripDrawMode;
  34527. },
  34528. enumerable: true,
  34529. configurable: true
  34530. });
  34531. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34532. /**
  34533. * Returns the triangle strip draw mode
  34534. */
  34535. get: function () {
  34536. return Material._TriangleStripDrawMode;
  34537. },
  34538. enumerable: true,
  34539. configurable: true
  34540. });
  34541. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34542. /**
  34543. * Returns the triangle fan draw mode
  34544. */
  34545. get: function () {
  34546. return Material._TriangleFanDrawMode;
  34547. },
  34548. enumerable: true,
  34549. configurable: true
  34550. });
  34551. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34552. /**
  34553. * Returns the clock-wise side orientation
  34554. */
  34555. get: function () {
  34556. return Material._ClockWiseSideOrientation;
  34557. },
  34558. enumerable: true,
  34559. configurable: true
  34560. });
  34561. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34562. /**
  34563. * Returns the counter clock-wise side orientation
  34564. */
  34565. get: function () {
  34566. return Material._CounterClockWiseSideOrientation;
  34567. },
  34568. enumerable: true,
  34569. configurable: true
  34570. });
  34571. Object.defineProperty(Material, "TextureDirtyFlag", {
  34572. /**
  34573. * Returns the dirty texture flag value
  34574. */
  34575. get: function () {
  34576. return Material._TextureDirtyFlag;
  34577. },
  34578. enumerable: true,
  34579. configurable: true
  34580. });
  34581. Object.defineProperty(Material, "LightDirtyFlag", {
  34582. /**
  34583. * Returns the dirty light flag value
  34584. */
  34585. get: function () {
  34586. return Material._LightDirtyFlag;
  34587. },
  34588. enumerable: true,
  34589. configurable: true
  34590. });
  34591. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34592. /**
  34593. * Returns the dirty fresnel flag value
  34594. */
  34595. get: function () {
  34596. return Material._FresnelDirtyFlag;
  34597. },
  34598. enumerable: true,
  34599. configurable: true
  34600. });
  34601. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34602. /**
  34603. * Returns the dirty attributes flag value
  34604. */
  34605. get: function () {
  34606. return Material._AttributesDirtyFlag;
  34607. },
  34608. enumerable: true,
  34609. configurable: true
  34610. });
  34611. Object.defineProperty(Material, "MiscDirtyFlag", {
  34612. /**
  34613. * Returns the dirty misc flag value
  34614. */
  34615. get: function () {
  34616. return Material._MiscDirtyFlag;
  34617. },
  34618. enumerable: true,
  34619. configurable: true
  34620. });
  34621. Object.defineProperty(Material.prototype, "alpha", {
  34622. /**
  34623. * Gets the alpha value of the material
  34624. */
  34625. get: function () {
  34626. return this._alpha;
  34627. },
  34628. /**
  34629. * Sets the alpha value of the material
  34630. */
  34631. set: function (value) {
  34632. if (this._alpha === value) {
  34633. return;
  34634. }
  34635. this._alpha = value;
  34636. this.markAsDirty(Material.MiscDirtyFlag);
  34637. },
  34638. enumerable: true,
  34639. configurable: true
  34640. });
  34641. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34642. /**
  34643. * Gets the back-face culling state
  34644. */
  34645. get: function () {
  34646. return this._backFaceCulling;
  34647. },
  34648. /**
  34649. * Sets the back-face culling state
  34650. */
  34651. set: function (value) {
  34652. if (this._backFaceCulling === value) {
  34653. return;
  34654. }
  34655. this._backFaceCulling = value;
  34656. this.markAsDirty(Material.TextureDirtyFlag);
  34657. },
  34658. enumerable: true,
  34659. configurable: true
  34660. });
  34661. Object.defineProperty(Material.prototype, "onDispose", {
  34662. /**
  34663. * Called during a dispose event
  34664. */
  34665. set: function (callback) {
  34666. if (this._onDisposeObserver) {
  34667. this.onDisposeObservable.remove(this._onDisposeObserver);
  34668. }
  34669. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34670. },
  34671. enumerable: true,
  34672. configurable: true
  34673. });
  34674. Object.defineProperty(Material.prototype, "onBind", {
  34675. /**
  34676. * Called during a bind event
  34677. */
  34678. set: function (callback) {
  34679. if (this._onBindObserver) {
  34680. this.onBindObservable.remove(this._onBindObserver);
  34681. }
  34682. this._onBindObserver = this.onBindObservable.add(callback);
  34683. },
  34684. enumerable: true,
  34685. configurable: true
  34686. });
  34687. Object.defineProperty(Material.prototype, "alphaMode", {
  34688. /**
  34689. * Gets the value of the alpha mode
  34690. */
  34691. get: function () {
  34692. return this._alphaMode;
  34693. },
  34694. /**
  34695. * Sets the value of the alpha mode.
  34696. *
  34697. * | Value | Type | Description |
  34698. * | --- | --- | --- |
  34699. * | 0 | ALPHA_DISABLE | |
  34700. * | 1 | ALPHA_ADD | |
  34701. * | 2 | ALPHA_COMBINE | |
  34702. * | 3 | ALPHA_SUBTRACT | |
  34703. * | 4 | ALPHA_MULTIPLY | |
  34704. * | 5 | ALPHA_MAXIMIZED | |
  34705. * | 6 | ALPHA_ONEONE | |
  34706. * | 7 | ALPHA_PREMULTIPLIED | |
  34707. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34708. * | 9 | ALPHA_INTERPOLATE | |
  34709. * | 10 | ALPHA_SCREENMODE | |
  34710. *
  34711. */
  34712. set: function (value) {
  34713. if (this._alphaMode === value) {
  34714. return;
  34715. }
  34716. this._alphaMode = value;
  34717. this.markAsDirty(Material.TextureDirtyFlag);
  34718. },
  34719. enumerable: true,
  34720. configurable: true
  34721. });
  34722. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34723. /**
  34724. * Gets the depth pre-pass value
  34725. */
  34726. get: function () {
  34727. return this._needDepthPrePass;
  34728. },
  34729. /**
  34730. * Sets the need depth pre-pass value
  34731. */
  34732. set: function (value) {
  34733. if (this._needDepthPrePass === value) {
  34734. return;
  34735. }
  34736. this._needDepthPrePass = value;
  34737. if (this._needDepthPrePass) {
  34738. this.checkReadyOnEveryCall = true;
  34739. }
  34740. },
  34741. enumerable: true,
  34742. configurable: true
  34743. });
  34744. Object.defineProperty(Material.prototype, "fogEnabled", {
  34745. /**
  34746. * Gets the value of the fog enabled state
  34747. */
  34748. get: function () {
  34749. return this._fogEnabled;
  34750. },
  34751. /**
  34752. * Sets the state for enabling fog
  34753. */
  34754. set: function (value) {
  34755. if (this._fogEnabled === value) {
  34756. return;
  34757. }
  34758. this._fogEnabled = value;
  34759. this.markAsDirty(Material.MiscDirtyFlag);
  34760. },
  34761. enumerable: true,
  34762. configurable: true
  34763. });
  34764. Object.defineProperty(Material.prototype, "wireframe", {
  34765. /**
  34766. * Gets a value specifying if wireframe mode is enabled
  34767. */
  34768. get: function () {
  34769. switch (this._fillMode) {
  34770. case Material.WireFrameFillMode:
  34771. case Material.LineListDrawMode:
  34772. case Material.LineLoopDrawMode:
  34773. case Material.LineStripDrawMode:
  34774. return true;
  34775. }
  34776. return this._scene.forceWireframe;
  34777. },
  34778. /**
  34779. * Sets the state of wireframe mode
  34780. */
  34781. set: function (value) {
  34782. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34783. },
  34784. enumerable: true,
  34785. configurable: true
  34786. });
  34787. Object.defineProperty(Material.prototype, "pointsCloud", {
  34788. /**
  34789. * Gets the value specifying if point clouds are enabled
  34790. */
  34791. get: function () {
  34792. switch (this._fillMode) {
  34793. case Material.PointFillMode:
  34794. case Material.PointListDrawMode:
  34795. return true;
  34796. }
  34797. return this._scene.forcePointsCloud;
  34798. },
  34799. /**
  34800. * Sets the state of point cloud mode
  34801. */
  34802. set: function (value) {
  34803. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34804. },
  34805. enumerable: true,
  34806. configurable: true
  34807. });
  34808. Object.defineProperty(Material.prototype, "fillMode", {
  34809. /**
  34810. * Gets the material fill mode
  34811. */
  34812. get: function () {
  34813. return this._fillMode;
  34814. },
  34815. /**
  34816. * Sets the material fill mode
  34817. */
  34818. set: function (value) {
  34819. if (this._fillMode === value) {
  34820. return;
  34821. }
  34822. this._fillMode = value;
  34823. this.markAsDirty(Material.MiscDirtyFlag);
  34824. },
  34825. enumerable: true,
  34826. configurable: true
  34827. });
  34828. /**
  34829. * Returns a string representation of the current material
  34830. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34831. * @returns a string with material information
  34832. */
  34833. Material.prototype.toString = function (fullDetails) {
  34834. var ret = "Name: " + this.name;
  34835. if (fullDetails) {
  34836. }
  34837. return ret;
  34838. };
  34839. /**
  34840. * Gets the class name of the material
  34841. * @returns a string with the class name of the material
  34842. */
  34843. Material.prototype.getClassName = function () {
  34844. return "Material";
  34845. };
  34846. Object.defineProperty(Material.prototype, "isFrozen", {
  34847. /**
  34848. * Specifies if updates for the material been locked
  34849. */
  34850. get: function () {
  34851. return this.checkReadyOnlyOnce;
  34852. },
  34853. enumerable: true,
  34854. configurable: true
  34855. });
  34856. /**
  34857. * Locks updates for the material
  34858. */
  34859. Material.prototype.freeze = function () {
  34860. this.checkReadyOnlyOnce = true;
  34861. };
  34862. /**
  34863. * Unlocks updates for the material
  34864. */
  34865. Material.prototype.unfreeze = function () {
  34866. this.checkReadyOnlyOnce = false;
  34867. };
  34868. /**
  34869. * Specifies if the material is ready to be used
  34870. * @param mesh defines the mesh to check
  34871. * @param useInstances specifies if instances should be used
  34872. * @returns a boolean indicating if the material is ready to be used
  34873. */
  34874. Material.prototype.isReady = function (mesh, useInstances) {
  34875. return true;
  34876. };
  34877. /**
  34878. * Specifies that the submesh is ready to be used
  34879. * @param mesh defines the mesh to check
  34880. * @param subMesh defines which submesh to check
  34881. * @param useInstances specifies that instances should be used
  34882. * @returns a boolean indicating that the submesh is ready or not
  34883. */
  34884. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  34885. return false;
  34886. };
  34887. /**
  34888. * Returns the material effect
  34889. * @returns the effect associated with the material
  34890. */
  34891. Material.prototype.getEffect = function () {
  34892. return this._effect;
  34893. };
  34894. /**
  34895. * Returns the current scene
  34896. * @returns a Scene
  34897. */
  34898. Material.prototype.getScene = function () {
  34899. return this._scene;
  34900. };
  34901. /**
  34902. * Specifies if the material will require alpha blending
  34903. * @returns a boolean specifying if alpha blending is needed
  34904. */
  34905. Material.prototype.needAlphaBlending = function () {
  34906. return (this.alpha < 1.0);
  34907. };
  34908. /**
  34909. * Specifies if the mesh will require alpha blending
  34910. * @param mesh defines the mesh to check
  34911. * @returns a boolean specifying if alpha blending is needed for the mesh
  34912. */
  34913. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  34914. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  34915. };
  34916. /**
  34917. * Specifies if this material should be rendered in alpha test mode
  34918. * @returns a boolean specifying if an alpha test is needed.
  34919. */
  34920. Material.prototype.needAlphaTesting = function () {
  34921. return false;
  34922. };
  34923. /**
  34924. * Gets the texture used for the alpha test
  34925. * @returns the texture to use for alpha testing
  34926. */
  34927. Material.prototype.getAlphaTestTexture = function () {
  34928. return null;
  34929. };
  34930. /**
  34931. * Marks the material to indicate that it needs to be re-calculated
  34932. */
  34933. Material.prototype.markDirty = function () {
  34934. this._wasPreviouslyReady = false;
  34935. };
  34936. /** @hidden */
  34937. Material.prototype._preBind = function (effect, overrideOrientation) {
  34938. if (overrideOrientation === void 0) { overrideOrientation = null; }
  34939. var engine = this._scene.getEngine();
  34940. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  34941. var reverse = orientation === Material.ClockWiseSideOrientation;
  34942. engine.enableEffect(effect ? effect : this._effect);
  34943. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  34944. return reverse;
  34945. };
  34946. /**
  34947. * Binds the material to the mesh
  34948. * @param world defines the world transformation matrix
  34949. * @param mesh defines the mesh to bind the material to
  34950. */
  34951. Material.prototype.bind = function (world, mesh) {
  34952. };
  34953. /**
  34954. * Binds the submesh to the material
  34955. * @param world defines the world transformation matrix
  34956. * @param mesh defines the mesh containing the submesh
  34957. * @param subMesh defines the submesh to bind the material to
  34958. */
  34959. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  34960. };
  34961. /**
  34962. * Binds the world matrix to the material
  34963. * @param world defines the world transformation matrix
  34964. */
  34965. Material.prototype.bindOnlyWorldMatrix = function (world) {
  34966. };
  34967. /**
  34968. * Binds the scene's uniform buffer to the effect.
  34969. * @param effect defines the effect to bind to the scene uniform buffer
  34970. * @param sceneUbo defines the uniform buffer storing scene data
  34971. */
  34972. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  34973. sceneUbo.bindToEffect(effect, "Scene");
  34974. };
  34975. /**
  34976. * Binds the view matrix to the effect
  34977. * @param effect defines the effect to bind the view matrix to
  34978. */
  34979. Material.prototype.bindView = function (effect) {
  34980. if (!this._useUBO) {
  34981. effect.setMatrix("view", this.getScene().getViewMatrix());
  34982. }
  34983. else {
  34984. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34985. }
  34986. };
  34987. /**
  34988. * Binds the view projection matrix to the effect
  34989. * @param effect defines the effect to bind the view projection matrix to
  34990. */
  34991. Material.prototype.bindViewProjection = function (effect) {
  34992. if (!this._useUBO) {
  34993. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  34994. }
  34995. else {
  34996. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  34997. }
  34998. };
  34999. /**
  35000. * Specifies if material alpha testing should be turned on for the mesh
  35001. * @param mesh defines the mesh to check
  35002. */
  35003. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35004. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35005. };
  35006. /**
  35007. * Processes to execute after binding the material to a mesh
  35008. * @param mesh defines the rendered mesh
  35009. */
  35010. Material.prototype._afterBind = function (mesh) {
  35011. this._scene._cachedMaterial = this;
  35012. if (mesh) {
  35013. this._scene._cachedVisibility = mesh.visibility;
  35014. }
  35015. else {
  35016. this._scene._cachedVisibility = 1;
  35017. }
  35018. if (mesh) {
  35019. this.onBindObservable.notifyObservers(mesh);
  35020. }
  35021. if (this.disableDepthWrite) {
  35022. var engine = this._scene.getEngine();
  35023. this._cachedDepthWriteState = engine.getDepthWrite();
  35024. engine.setDepthWrite(false);
  35025. }
  35026. };
  35027. /**
  35028. * Unbinds the material from the mesh
  35029. */
  35030. Material.prototype.unbind = function () {
  35031. this.onUnBindObservable.notifyObservers(this);
  35032. if (this.disableDepthWrite) {
  35033. var engine = this._scene.getEngine();
  35034. engine.setDepthWrite(this._cachedDepthWriteState);
  35035. }
  35036. };
  35037. /**
  35038. * Gets the active textures from the material
  35039. * @returns an array of textures
  35040. */
  35041. Material.prototype.getActiveTextures = function () {
  35042. return [];
  35043. };
  35044. /**
  35045. * Specifies if the material uses a texture
  35046. * @param texture defines the texture to check against the material
  35047. * @returns a boolean specifying if the material uses the texture
  35048. */
  35049. Material.prototype.hasTexture = function (texture) {
  35050. return false;
  35051. };
  35052. /**
  35053. * Makes a duplicate of the material, and gives it a new name
  35054. * @param name defines the new name for the duplicated material
  35055. * @returns the cloned material
  35056. */
  35057. Material.prototype.clone = function (name) {
  35058. return null;
  35059. };
  35060. /**
  35061. * Gets the meshes bound to the material
  35062. * @returns an array of meshes bound to the material
  35063. */
  35064. Material.prototype.getBindedMeshes = function () {
  35065. var result = new Array();
  35066. for (var index = 0; index < this._scene.meshes.length; index++) {
  35067. var mesh = this._scene.meshes[index];
  35068. if (mesh.material === this) {
  35069. result.push(mesh);
  35070. }
  35071. }
  35072. return result;
  35073. };
  35074. /**
  35075. * Force shader compilation
  35076. * @param mesh defines the mesh associated with this material
  35077. * @param onCompiled defines a function to execute once the material is compiled
  35078. * @param options defines the options to configure the compilation
  35079. */
  35080. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35081. var _this = this;
  35082. var localOptions = __assign({ clipPlane: false }, options);
  35083. var subMesh = new BABYLON.BaseSubMesh();
  35084. var scene = this.getScene();
  35085. var checkReady = function () {
  35086. if (!_this._scene || !_this._scene.getEngine()) {
  35087. return;
  35088. }
  35089. if (subMesh._materialDefines) {
  35090. subMesh._materialDefines._renderId = -1;
  35091. }
  35092. var clipPlaneState = scene.clipPlane;
  35093. if (localOptions.clipPlane) {
  35094. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35095. }
  35096. if (_this.storeEffectOnSubMeshes) {
  35097. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35098. if (onCompiled) {
  35099. onCompiled(_this);
  35100. }
  35101. }
  35102. else {
  35103. setTimeout(checkReady, 16);
  35104. }
  35105. }
  35106. else {
  35107. if (_this.isReady(mesh)) {
  35108. if (onCompiled) {
  35109. onCompiled(_this);
  35110. }
  35111. }
  35112. else {
  35113. setTimeout(checkReady, 16);
  35114. }
  35115. }
  35116. if (localOptions.clipPlane) {
  35117. scene.clipPlane = clipPlaneState;
  35118. }
  35119. };
  35120. checkReady();
  35121. };
  35122. /**
  35123. * Force shader compilation
  35124. * @param mesh defines the mesh that will use this material
  35125. * @param options defines additional options for compiling the shaders
  35126. * @returns a promise that resolves when the compilation completes
  35127. */
  35128. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35129. var _this = this;
  35130. return new Promise(function (resolve) {
  35131. _this.forceCompilation(mesh, function () {
  35132. resolve();
  35133. }, options);
  35134. });
  35135. };
  35136. /**
  35137. * Marks a define in the material to indicate that it needs to be re-computed
  35138. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35139. */
  35140. Material.prototype.markAsDirty = function (flag) {
  35141. if (flag & Material.TextureDirtyFlag) {
  35142. this._markAllSubMeshesAsTexturesDirty();
  35143. }
  35144. if (flag & Material.LightDirtyFlag) {
  35145. this._markAllSubMeshesAsLightsDirty();
  35146. }
  35147. if (flag & Material.FresnelDirtyFlag) {
  35148. this._markAllSubMeshesAsFresnelDirty();
  35149. }
  35150. if (flag & Material.AttributesDirtyFlag) {
  35151. this._markAllSubMeshesAsAttributesDirty();
  35152. }
  35153. if (flag & Material.MiscDirtyFlag) {
  35154. this._markAllSubMeshesAsMiscDirty();
  35155. }
  35156. this.getScene().resetCachedMaterial();
  35157. };
  35158. /**
  35159. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35160. * @param func defines a function which checks material defines against the submeshes
  35161. */
  35162. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35163. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35164. var mesh = _a[_i];
  35165. if (!mesh.subMeshes) {
  35166. continue;
  35167. }
  35168. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35169. var subMesh = _c[_b];
  35170. if (subMesh.getMaterial() !== this) {
  35171. continue;
  35172. }
  35173. if (!subMesh._materialDefines) {
  35174. continue;
  35175. }
  35176. func(subMesh._materialDefines);
  35177. }
  35178. }
  35179. };
  35180. /**
  35181. * Indicates that image processing needs to be re-calculated for all submeshes
  35182. */
  35183. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35184. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35185. };
  35186. /**
  35187. * Indicates that textures need to be re-calculated for all submeshes
  35188. */
  35189. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35190. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35191. };
  35192. /**
  35193. * Indicates that fresnel needs to be re-calculated for all submeshes
  35194. */
  35195. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35196. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35197. };
  35198. /**
  35199. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35200. */
  35201. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35202. this._markAllSubMeshesAsDirty(function (defines) {
  35203. defines.markAsFresnelDirty();
  35204. defines.markAsMiscDirty();
  35205. });
  35206. };
  35207. /**
  35208. * Indicates that lights need to be re-calculated for all submeshes
  35209. */
  35210. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35211. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35212. };
  35213. /**
  35214. * Indicates that attributes need to be re-calculated for all submeshes
  35215. */
  35216. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35217. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35218. };
  35219. /**
  35220. * Indicates that misc needs to be re-calculated for all submeshes
  35221. */
  35222. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35223. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35224. };
  35225. /**
  35226. * Indicates that textures and misc need to be re-calculated for all submeshes
  35227. */
  35228. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35229. this._markAllSubMeshesAsDirty(function (defines) {
  35230. defines.markAsTexturesDirty();
  35231. defines.markAsMiscDirty();
  35232. });
  35233. };
  35234. /**
  35235. * Disposes the material
  35236. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35237. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35238. */
  35239. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35240. // Animations
  35241. this.getScene().stopAnimation(this);
  35242. this.getScene().freeProcessedMaterials();
  35243. // Remove from scene
  35244. var index = this._scene.materials.indexOf(this);
  35245. if (index >= 0) {
  35246. this._scene.materials.splice(index, 1);
  35247. }
  35248. // Remove from meshes
  35249. for (index = 0; index < this._scene.meshes.length; index++) {
  35250. var mesh = this._scene.meshes[index];
  35251. if (mesh.material === this) {
  35252. mesh.material = null;
  35253. if (mesh.geometry) {
  35254. var geometry = (mesh.geometry);
  35255. if (this.storeEffectOnSubMeshes) {
  35256. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35257. var subMesh = _a[_i];
  35258. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35259. if (forceDisposeEffect && subMesh._materialEffect) {
  35260. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35261. }
  35262. }
  35263. }
  35264. else {
  35265. geometry._releaseVertexArrayObject(this._effect);
  35266. }
  35267. }
  35268. }
  35269. }
  35270. this._uniformBuffer.dispose();
  35271. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35272. if (forceDisposeEffect && this._effect) {
  35273. if (!this.storeEffectOnSubMeshes) {
  35274. this._scene.getEngine()._releaseEffect(this._effect);
  35275. }
  35276. this._effect = null;
  35277. }
  35278. // Callback
  35279. this.onDisposeObservable.notifyObservers(this);
  35280. this.onDisposeObservable.clear();
  35281. this.onBindObservable.clear();
  35282. this.onUnBindObservable.clear();
  35283. };
  35284. /**
  35285. * Serializes this material
  35286. * @returns the serialized material object
  35287. */
  35288. Material.prototype.serialize = function () {
  35289. return BABYLON.SerializationHelper.Serialize(this);
  35290. };
  35291. /**
  35292. * Creates a MultiMaterial from parsed MultiMaterial data.
  35293. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35294. * @param scene defines the hosting scene
  35295. * @returns a new MultiMaterial
  35296. */
  35297. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35298. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35299. multiMaterial.id = parsedMultiMaterial.id;
  35300. if (BABYLON.Tags) {
  35301. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35302. }
  35303. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35304. var subMatId = parsedMultiMaterial.materials[matIndex];
  35305. if (subMatId) {
  35306. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35307. }
  35308. else {
  35309. multiMaterial.subMaterials.push(null);
  35310. }
  35311. }
  35312. return multiMaterial;
  35313. };
  35314. /**
  35315. * Creates a material from parsed material data
  35316. * @param parsedMaterial defines parsed material data
  35317. * @param scene defines the hosting scene
  35318. * @param rootUrl defines the root URL to use to load textures
  35319. * @returns a new material
  35320. */
  35321. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35322. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35323. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35324. }
  35325. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35326. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35327. if (!BABYLON.LegacyPBRMaterial) {
  35328. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35329. return;
  35330. }
  35331. }
  35332. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35333. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35334. ;
  35335. };
  35336. // Triangle views
  35337. Material._TriangleFillMode = 0;
  35338. Material._WireFrameFillMode = 1;
  35339. Material._PointFillMode = 2;
  35340. // Draw modes
  35341. Material._PointListDrawMode = 3;
  35342. Material._LineListDrawMode = 4;
  35343. Material._LineLoopDrawMode = 5;
  35344. Material._LineStripDrawMode = 6;
  35345. Material._TriangleStripDrawMode = 7;
  35346. Material._TriangleFanDrawMode = 8;
  35347. /**
  35348. * Stores the clock-wise side orientation
  35349. */
  35350. Material._ClockWiseSideOrientation = 0;
  35351. /**
  35352. * Stores the counter clock-wise side orientation
  35353. */
  35354. Material._CounterClockWiseSideOrientation = 1;
  35355. /**
  35356. * The dirty texture flag value
  35357. */
  35358. Material._TextureDirtyFlag = 1;
  35359. /**
  35360. * The dirty light flag value
  35361. */
  35362. Material._LightDirtyFlag = 2;
  35363. /**
  35364. * The dirty fresnel flag value
  35365. */
  35366. Material._FresnelDirtyFlag = 4;
  35367. /**
  35368. * The dirty attribute flag value
  35369. */
  35370. Material._AttributesDirtyFlag = 8;
  35371. /**
  35372. * The dirty misc flag value
  35373. */
  35374. Material._MiscDirtyFlag = 16;
  35375. __decorate([
  35376. BABYLON.serialize()
  35377. ], Material.prototype, "id", void 0);
  35378. __decorate([
  35379. BABYLON.serialize()
  35380. ], Material.prototype, "name", void 0);
  35381. __decorate([
  35382. BABYLON.serialize()
  35383. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35384. __decorate([
  35385. BABYLON.serialize()
  35386. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35387. __decorate([
  35388. BABYLON.serialize()
  35389. ], Material.prototype, "state", void 0);
  35390. __decorate([
  35391. BABYLON.serialize("alpha")
  35392. ], Material.prototype, "_alpha", void 0);
  35393. __decorate([
  35394. BABYLON.serialize("backFaceCulling")
  35395. ], Material.prototype, "_backFaceCulling", void 0);
  35396. __decorate([
  35397. BABYLON.serialize()
  35398. ], Material.prototype, "sideOrientation", void 0);
  35399. __decorate([
  35400. BABYLON.serialize("alphaMode")
  35401. ], Material.prototype, "_alphaMode", void 0);
  35402. __decorate([
  35403. BABYLON.serialize()
  35404. ], Material.prototype, "_needDepthPrePass", void 0);
  35405. __decorate([
  35406. BABYLON.serialize()
  35407. ], Material.prototype, "disableDepthWrite", void 0);
  35408. __decorate([
  35409. BABYLON.serialize()
  35410. ], Material.prototype, "forceDepthWrite", void 0);
  35411. __decorate([
  35412. BABYLON.serialize()
  35413. ], Material.prototype, "separateCullingPass", void 0);
  35414. __decorate([
  35415. BABYLON.serialize("fogEnabled")
  35416. ], Material.prototype, "_fogEnabled", void 0);
  35417. __decorate([
  35418. BABYLON.serialize()
  35419. ], Material.prototype, "pointSize", void 0);
  35420. __decorate([
  35421. BABYLON.serialize()
  35422. ], Material.prototype, "zOffset", void 0);
  35423. __decorate([
  35424. BABYLON.serialize()
  35425. ], Material.prototype, "wireframe", null);
  35426. __decorate([
  35427. BABYLON.serialize()
  35428. ], Material.prototype, "pointsCloud", null);
  35429. __decorate([
  35430. BABYLON.serialize()
  35431. ], Material.prototype, "fillMode", null);
  35432. return Material;
  35433. }());
  35434. BABYLON.Material = Material;
  35435. })(BABYLON || (BABYLON = {}));
  35436. //# sourceMappingURL=babylon.material.js.map
  35437. var BABYLON;
  35438. (function (BABYLON) {
  35439. var UniformBuffer = /** @class */ (function () {
  35440. /**
  35441. * Uniform buffer objects.
  35442. *
  35443. * Handles blocks of uniform on the GPU.
  35444. *
  35445. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35446. *
  35447. * For more information, please refer to :
  35448. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35449. */
  35450. function UniformBuffer(engine, data, dynamic) {
  35451. this._engine = engine;
  35452. this._noUBO = !engine.supportsUniformBuffers;
  35453. this._dynamic = dynamic;
  35454. this._data = data || [];
  35455. this._uniformLocations = {};
  35456. this._uniformSizes = {};
  35457. this._uniformLocationPointer = 0;
  35458. this._needSync = false;
  35459. if (this._noUBO) {
  35460. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35461. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35462. this.updateFloat = this._updateFloatForEffect;
  35463. this.updateFloat2 = this._updateFloat2ForEffect;
  35464. this.updateFloat3 = this._updateFloat3ForEffect;
  35465. this.updateFloat4 = this._updateFloat4ForEffect;
  35466. this.updateMatrix = this._updateMatrixForEffect;
  35467. this.updateVector3 = this._updateVector3ForEffect;
  35468. this.updateVector4 = this._updateVector4ForEffect;
  35469. this.updateColor3 = this._updateColor3ForEffect;
  35470. this.updateColor4 = this._updateColor4ForEffect;
  35471. }
  35472. else {
  35473. this._engine._uniformBuffers.push(this);
  35474. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35475. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35476. this.updateFloat = this._updateFloatForUniform;
  35477. this.updateFloat2 = this._updateFloat2ForUniform;
  35478. this.updateFloat3 = this._updateFloat3ForUniform;
  35479. this.updateFloat4 = this._updateFloat4ForUniform;
  35480. this.updateMatrix = this._updateMatrixForUniform;
  35481. this.updateVector3 = this._updateVector3ForUniform;
  35482. this.updateVector4 = this._updateVector4ForUniform;
  35483. this.updateColor3 = this._updateColor3ForUniform;
  35484. this.updateColor4 = this._updateColor4ForUniform;
  35485. }
  35486. }
  35487. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35488. // Properties
  35489. /**
  35490. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35491. * or just falling back on setUniformXXX calls.
  35492. */
  35493. get: function () {
  35494. return !this._noUBO;
  35495. },
  35496. enumerable: true,
  35497. configurable: true
  35498. });
  35499. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35500. /**
  35501. * Indicates if the WebGL underlying uniform buffer is in sync
  35502. * with the javascript cache data.
  35503. */
  35504. get: function () {
  35505. return !this._needSync;
  35506. },
  35507. enumerable: true,
  35508. configurable: true
  35509. });
  35510. /**
  35511. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35512. * Also, a dynamic UniformBuffer will disable cache verification and always
  35513. * update the underlying WebGL uniform buffer to the GPU.
  35514. */
  35515. UniformBuffer.prototype.isDynamic = function () {
  35516. return this._dynamic !== undefined;
  35517. };
  35518. /**
  35519. * The data cache on JS side.
  35520. */
  35521. UniformBuffer.prototype.getData = function () {
  35522. return this._bufferData;
  35523. };
  35524. /**
  35525. * The underlying WebGL Uniform buffer.
  35526. */
  35527. UniformBuffer.prototype.getBuffer = function () {
  35528. return this._buffer;
  35529. };
  35530. /**
  35531. * std140 layout specifies how to align data within an UBO structure.
  35532. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35533. * for specs.
  35534. */
  35535. UniformBuffer.prototype._fillAlignment = function (size) {
  35536. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35537. // and 4x4 matrices
  35538. // TODO : change if other types are used
  35539. var alignment;
  35540. if (size <= 2) {
  35541. alignment = size;
  35542. }
  35543. else {
  35544. alignment = 4;
  35545. }
  35546. if ((this._uniformLocationPointer % alignment) !== 0) {
  35547. var oldPointer = this._uniformLocationPointer;
  35548. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35549. var diff = this._uniformLocationPointer - oldPointer;
  35550. for (var i = 0; i < diff; i++) {
  35551. this._data.push(0);
  35552. }
  35553. }
  35554. };
  35555. /**
  35556. * Adds an uniform in the buffer.
  35557. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35558. * for the layout to be correct !
  35559. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35560. * @param {number|number[]} size Data size, or data directly.
  35561. */
  35562. UniformBuffer.prototype.addUniform = function (name, size) {
  35563. if (this._noUBO) {
  35564. return;
  35565. }
  35566. if (this._uniformLocations[name] !== undefined) {
  35567. // Already existing uniform
  35568. return;
  35569. }
  35570. // This function must be called in the order of the shader layout !
  35571. // size can be the size of the uniform, or data directly
  35572. var data;
  35573. if (size instanceof Array) {
  35574. data = size;
  35575. size = data.length;
  35576. }
  35577. else {
  35578. size = size;
  35579. data = [];
  35580. // Fill with zeros
  35581. for (var i = 0; i < size; i++) {
  35582. data.push(0);
  35583. }
  35584. }
  35585. this._fillAlignment(size);
  35586. this._uniformSizes[name] = size;
  35587. this._uniformLocations[name] = this._uniformLocationPointer;
  35588. this._uniformLocationPointer += size;
  35589. for (var i = 0; i < size; i++) {
  35590. this._data.push(data[i]);
  35591. }
  35592. this._needSync = true;
  35593. };
  35594. /**
  35595. * Wrapper for addUniform.
  35596. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35597. * @param {Matrix} mat A 4x4 matrix.
  35598. */
  35599. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35600. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35601. };
  35602. /**
  35603. * Wrapper for addUniform.
  35604. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35605. * @param {number} x
  35606. * @param {number} y
  35607. */
  35608. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35609. var temp = [x, y];
  35610. this.addUniform(name, temp);
  35611. };
  35612. /**
  35613. * Wrapper for addUniform.
  35614. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35615. * @param {number} x
  35616. * @param {number} y
  35617. * @param {number} z
  35618. */
  35619. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35620. var temp = [x, y, z];
  35621. this.addUniform(name, temp);
  35622. };
  35623. /**
  35624. * Wrapper for addUniform.
  35625. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35626. * @param {Color3} color
  35627. */
  35628. UniformBuffer.prototype.addColor3 = function (name, color) {
  35629. var temp = new Array();
  35630. color.toArray(temp);
  35631. this.addUniform(name, temp);
  35632. };
  35633. /**
  35634. * Wrapper for addUniform.
  35635. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35636. * @param {Color3} color
  35637. * @param {number} alpha
  35638. */
  35639. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35640. var temp = new Array();
  35641. color.toArray(temp);
  35642. temp.push(alpha);
  35643. this.addUniform(name, temp);
  35644. };
  35645. /**
  35646. * Wrapper for addUniform.
  35647. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35648. * @param {Vector3} vector
  35649. */
  35650. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35651. var temp = new Array();
  35652. vector.toArray(temp);
  35653. this.addUniform(name, temp);
  35654. };
  35655. /**
  35656. * Wrapper for addUniform.
  35657. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35658. */
  35659. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35660. this.addUniform(name, 12);
  35661. };
  35662. /**
  35663. * Wrapper for addUniform.
  35664. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35665. */
  35666. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35667. this.addUniform(name, 8);
  35668. };
  35669. /**
  35670. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35671. */
  35672. UniformBuffer.prototype.create = function () {
  35673. if (this._noUBO) {
  35674. return;
  35675. }
  35676. if (this._buffer) {
  35677. return; // nothing to do
  35678. }
  35679. // See spec, alignment must be filled as a vec4
  35680. this._fillAlignment(4);
  35681. this._bufferData = new Float32Array(this._data);
  35682. this._rebuild();
  35683. this._needSync = true;
  35684. };
  35685. UniformBuffer.prototype._rebuild = function () {
  35686. if (this._noUBO) {
  35687. return;
  35688. }
  35689. if (this._dynamic) {
  35690. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35691. }
  35692. else {
  35693. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35694. }
  35695. };
  35696. /**
  35697. * Updates the WebGL Uniform Buffer on the GPU.
  35698. * If the `dynamic` flag is set to true, no cache comparison is done.
  35699. * Otherwise, the buffer will be updated only if the cache differs.
  35700. */
  35701. UniformBuffer.prototype.update = function () {
  35702. if (!this._buffer) {
  35703. this.create();
  35704. return;
  35705. }
  35706. if (!this._dynamic && !this._needSync) {
  35707. return;
  35708. }
  35709. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35710. this._needSync = false;
  35711. };
  35712. /**
  35713. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35714. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35715. * @param {number[]|Float32Array} data Flattened data
  35716. * @param {number} size Size of the data.
  35717. */
  35718. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35719. var location = this._uniformLocations[uniformName];
  35720. if (location === undefined) {
  35721. if (this._buffer) {
  35722. // Cannot add an uniform if the buffer is already created
  35723. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35724. return;
  35725. }
  35726. this.addUniform(uniformName, size);
  35727. location = this._uniformLocations[uniformName];
  35728. }
  35729. if (!this._buffer) {
  35730. this.create();
  35731. }
  35732. if (!this._dynamic) {
  35733. // Cache for static uniform buffers
  35734. var changed = false;
  35735. for (var i = 0; i < size; i++) {
  35736. if (this._bufferData[location + i] !== data[i]) {
  35737. changed = true;
  35738. this._bufferData[location + i] = data[i];
  35739. }
  35740. }
  35741. this._needSync = this._needSync || changed;
  35742. }
  35743. else {
  35744. // No cache for dynamic
  35745. for (var i = 0; i < size; i++) {
  35746. this._bufferData[location + i] = data[i];
  35747. }
  35748. }
  35749. };
  35750. // Update methods
  35751. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35752. // To match std140, matrix must be realigned
  35753. for (var i = 0; i < 3; i++) {
  35754. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35755. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35756. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35757. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35758. }
  35759. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35760. };
  35761. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35762. this._currentEffect.setMatrix3x3(name, matrix);
  35763. };
  35764. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35765. this._currentEffect.setMatrix2x2(name, matrix);
  35766. };
  35767. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35768. // To match std140, matrix must be realigned
  35769. for (var i = 0; i < 2; i++) {
  35770. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35771. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35772. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35773. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35774. }
  35775. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35776. };
  35777. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35778. this._currentEffect.setFloat(name, x);
  35779. };
  35780. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35781. UniformBuffer._tempBuffer[0] = x;
  35782. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35783. };
  35784. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35785. if (suffix === void 0) { suffix = ""; }
  35786. this._currentEffect.setFloat2(name + suffix, x, y);
  35787. };
  35788. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35789. if (suffix === void 0) { suffix = ""; }
  35790. UniformBuffer._tempBuffer[0] = x;
  35791. UniformBuffer._tempBuffer[1] = y;
  35792. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35793. };
  35794. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35795. if (suffix === void 0) { suffix = ""; }
  35796. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35797. };
  35798. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35799. if (suffix === void 0) { suffix = ""; }
  35800. UniformBuffer._tempBuffer[0] = x;
  35801. UniformBuffer._tempBuffer[1] = y;
  35802. UniformBuffer._tempBuffer[2] = z;
  35803. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35804. };
  35805. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35806. if (suffix === void 0) { suffix = ""; }
  35807. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35808. };
  35809. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35810. if (suffix === void 0) { suffix = ""; }
  35811. UniformBuffer._tempBuffer[0] = x;
  35812. UniformBuffer._tempBuffer[1] = y;
  35813. UniformBuffer._tempBuffer[2] = z;
  35814. UniformBuffer._tempBuffer[3] = w;
  35815. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35816. };
  35817. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35818. this._currentEffect.setMatrix(name, mat);
  35819. };
  35820. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35821. this.updateUniform(name, mat.toArray(), 16);
  35822. };
  35823. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35824. this._currentEffect.setVector3(name, vector);
  35825. };
  35826. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35827. vector.toArray(UniformBuffer._tempBuffer);
  35828. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35829. };
  35830. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35831. this._currentEffect.setVector4(name, vector);
  35832. };
  35833. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35834. vector.toArray(UniformBuffer._tempBuffer);
  35835. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35836. };
  35837. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35838. if (suffix === void 0) { suffix = ""; }
  35839. this._currentEffect.setColor3(name + suffix, color);
  35840. };
  35841. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35842. if (suffix === void 0) { suffix = ""; }
  35843. color.toArray(UniformBuffer._tempBuffer);
  35844. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35845. };
  35846. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35847. if (suffix === void 0) { suffix = ""; }
  35848. this._currentEffect.setColor4(name + suffix, color, alpha);
  35849. };
  35850. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35851. if (suffix === void 0) { suffix = ""; }
  35852. color.toArray(UniformBuffer._tempBuffer);
  35853. UniformBuffer._tempBuffer[3] = alpha;
  35854. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35855. };
  35856. /**
  35857. * Sets a sampler uniform on the effect.
  35858. * @param {string} name Name of the sampler.
  35859. * @param {Texture} texture
  35860. */
  35861. UniformBuffer.prototype.setTexture = function (name, texture) {
  35862. this._currentEffect.setTexture(name, texture);
  35863. };
  35864. /**
  35865. * Directly updates the value of the uniform in the cache AND on the GPU.
  35866. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35867. * @param {number[]|Float32Array} data Flattened data
  35868. */
  35869. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  35870. this.updateUniform(uniformName, data, data.length);
  35871. this.update();
  35872. };
  35873. /**
  35874. * Binds this uniform buffer to an effect.
  35875. * @param {Effect} effect
  35876. * @param {string} name Name of the uniform block in the shader.
  35877. */
  35878. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  35879. this._currentEffect = effect;
  35880. if (this._noUBO || !this._buffer) {
  35881. return;
  35882. }
  35883. effect.bindUniformBuffer(this._buffer, name);
  35884. };
  35885. /**
  35886. * Disposes the uniform buffer.
  35887. */
  35888. UniformBuffer.prototype.dispose = function () {
  35889. if (this._noUBO) {
  35890. return;
  35891. }
  35892. var index = this._engine._uniformBuffers.indexOf(this);
  35893. if (index !== -1) {
  35894. this._engine._uniformBuffers.splice(index, 1);
  35895. }
  35896. if (!this._buffer) {
  35897. return;
  35898. }
  35899. if (this._engine._releaseBuffer(this._buffer)) {
  35900. this._buffer = null;
  35901. }
  35902. };
  35903. // Pool for avoiding memory leaks
  35904. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  35905. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  35906. return UniformBuffer;
  35907. }());
  35908. BABYLON.UniformBuffer = UniformBuffer;
  35909. })(BABYLON || (BABYLON = {}));
  35910. //# sourceMappingURL=babylon.uniformBuffer.js.map
  35911. var BABYLON;
  35912. (function (BABYLON) {
  35913. /**
  35914. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  35915. */
  35916. var VertexData = /** @class */ (function () {
  35917. function VertexData() {
  35918. }
  35919. /**
  35920. * Uses the passed data array to set the set the values for the specified kind of data
  35921. * @param data a linear array of floating numbers
  35922. * @param kind the type of data that is being set, eg positions, colors etc
  35923. */
  35924. VertexData.prototype.set = function (data, kind) {
  35925. switch (kind) {
  35926. case BABYLON.VertexBuffer.PositionKind:
  35927. this.positions = data;
  35928. break;
  35929. case BABYLON.VertexBuffer.NormalKind:
  35930. this.normals = data;
  35931. break;
  35932. case BABYLON.VertexBuffer.TangentKind:
  35933. this.tangents = data;
  35934. break;
  35935. case BABYLON.VertexBuffer.UVKind:
  35936. this.uvs = data;
  35937. break;
  35938. case BABYLON.VertexBuffer.UV2Kind:
  35939. this.uvs2 = data;
  35940. break;
  35941. case BABYLON.VertexBuffer.UV3Kind:
  35942. this.uvs3 = data;
  35943. break;
  35944. case BABYLON.VertexBuffer.UV4Kind:
  35945. this.uvs4 = data;
  35946. break;
  35947. case BABYLON.VertexBuffer.UV5Kind:
  35948. this.uvs5 = data;
  35949. break;
  35950. case BABYLON.VertexBuffer.UV6Kind:
  35951. this.uvs6 = data;
  35952. break;
  35953. case BABYLON.VertexBuffer.ColorKind:
  35954. this.colors = data;
  35955. break;
  35956. case BABYLON.VertexBuffer.MatricesIndicesKind:
  35957. this.matricesIndices = data;
  35958. break;
  35959. case BABYLON.VertexBuffer.MatricesWeightsKind:
  35960. this.matricesWeights = data;
  35961. break;
  35962. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  35963. this.matricesIndicesExtra = data;
  35964. break;
  35965. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  35966. this.matricesWeightsExtra = data;
  35967. break;
  35968. }
  35969. };
  35970. /**
  35971. * Associates the vertexData to the passed Mesh.
  35972. * Sets it as updatable or not (default `false`)
  35973. * @param mesh the mesh the vertexData is applied to
  35974. * @param updatable when used and having the value true allows new data to update the vertexData
  35975. * @returns the VertexData
  35976. */
  35977. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  35978. this._applyTo(mesh, updatable);
  35979. return this;
  35980. };
  35981. /**
  35982. * Associates the vertexData to the passed Geometry.
  35983. * Sets it as updatable or not (default `false`)
  35984. * @param geometry the geometry the vertexData is applied to
  35985. * @param updatable when used and having the value true allows new data to update the vertexData
  35986. * @returns VertexData
  35987. */
  35988. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  35989. this._applyTo(geometry, updatable);
  35990. return this;
  35991. };
  35992. /**
  35993. * Updates the associated mesh
  35994. * @param mesh the mesh to be updated
  35995. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  35996. * @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
  35997. * @returns VertexData
  35998. */
  35999. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36000. this._update(mesh);
  36001. return this;
  36002. };
  36003. /**
  36004. * Updates the associated geometry
  36005. * @param geometry the geometry to be updated
  36006. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36007. * @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
  36008. * @returns VertexData.
  36009. */
  36010. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36011. this._update(geometry);
  36012. return this;
  36013. };
  36014. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36015. if (updatable === void 0) { updatable = false; }
  36016. if (this.positions) {
  36017. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36018. }
  36019. if (this.normals) {
  36020. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36021. }
  36022. if (this.tangents) {
  36023. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36024. }
  36025. if (this.uvs) {
  36026. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36027. }
  36028. if (this.uvs2) {
  36029. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36030. }
  36031. if (this.uvs3) {
  36032. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36033. }
  36034. if (this.uvs4) {
  36035. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36036. }
  36037. if (this.uvs5) {
  36038. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36039. }
  36040. if (this.uvs6) {
  36041. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36042. }
  36043. if (this.colors) {
  36044. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36045. }
  36046. if (this.matricesIndices) {
  36047. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36048. }
  36049. if (this.matricesWeights) {
  36050. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36051. }
  36052. if (this.matricesIndicesExtra) {
  36053. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36054. }
  36055. if (this.matricesWeightsExtra) {
  36056. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36057. }
  36058. if (this.indices) {
  36059. meshOrGeometry.setIndices(this.indices, null, updatable);
  36060. }
  36061. return this;
  36062. };
  36063. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36064. if (this.positions) {
  36065. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36066. }
  36067. if (this.normals) {
  36068. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36069. }
  36070. if (this.tangents) {
  36071. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36072. }
  36073. if (this.uvs) {
  36074. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36075. }
  36076. if (this.uvs2) {
  36077. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36078. }
  36079. if (this.uvs3) {
  36080. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36081. }
  36082. if (this.uvs4) {
  36083. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36084. }
  36085. if (this.uvs5) {
  36086. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36087. }
  36088. if (this.uvs6) {
  36089. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36090. }
  36091. if (this.colors) {
  36092. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36093. }
  36094. if (this.matricesIndices) {
  36095. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36096. }
  36097. if (this.matricesWeights) {
  36098. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36099. }
  36100. if (this.matricesIndicesExtra) {
  36101. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36102. }
  36103. if (this.matricesWeightsExtra) {
  36104. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36105. }
  36106. if (this.indices) {
  36107. meshOrGeometry.setIndices(this.indices, null);
  36108. }
  36109. return this;
  36110. };
  36111. /**
  36112. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36113. * @param matrix the transforming matrix
  36114. * @returns the VertexData
  36115. */
  36116. VertexData.prototype.transform = function (matrix) {
  36117. var transformed = BABYLON.Vector3.Zero();
  36118. var index;
  36119. if (this.positions) {
  36120. var position = BABYLON.Vector3.Zero();
  36121. for (index = 0; index < this.positions.length; index += 3) {
  36122. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36123. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36124. this.positions[index] = transformed.x;
  36125. this.positions[index + 1] = transformed.y;
  36126. this.positions[index + 2] = transformed.z;
  36127. }
  36128. }
  36129. if (this.normals) {
  36130. var normal = BABYLON.Vector3.Zero();
  36131. for (index = 0; index < this.normals.length; index += 3) {
  36132. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36133. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36134. this.normals[index] = transformed.x;
  36135. this.normals[index + 1] = transformed.y;
  36136. this.normals[index + 2] = transformed.z;
  36137. }
  36138. }
  36139. if (this.tangents) {
  36140. var tangent = BABYLON.Vector4.Zero();
  36141. var tangentTransformed = BABYLON.Vector4.Zero();
  36142. for (index = 0; index < this.tangents.length; index += 4) {
  36143. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36144. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36145. this.tangents[index] = tangentTransformed.x;
  36146. this.tangents[index + 1] = tangentTransformed.y;
  36147. this.tangents[index + 2] = tangentTransformed.z;
  36148. this.tangents[index + 3] = tangentTransformed.w;
  36149. }
  36150. }
  36151. return this;
  36152. };
  36153. /**
  36154. * Merges the passed VertexData into the current one
  36155. * @param other the VertexData to be merged into the current one
  36156. * @returns the modified VertexData
  36157. */
  36158. VertexData.prototype.merge = function (other) {
  36159. this._validate();
  36160. other._validate();
  36161. if (!this.normals !== !other.normals ||
  36162. !this.tangents !== !other.tangents ||
  36163. !this.uvs !== !other.uvs ||
  36164. !this.uvs2 !== !other.uvs2 ||
  36165. !this.uvs3 !== !other.uvs3 ||
  36166. !this.uvs4 !== !other.uvs4 ||
  36167. !this.uvs5 !== !other.uvs5 ||
  36168. !this.uvs6 !== !other.uvs6 ||
  36169. !this.colors !== !other.colors ||
  36170. !this.matricesIndices !== !other.matricesIndices ||
  36171. !this.matricesWeights !== !other.matricesWeights ||
  36172. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36173. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36174. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36175. }
  36176. if (other.indices) {
  36177. if (!this.indices) {
  36178. this.indices = [];
  36179. }
  36180. var offset = this.positions ? this.positions.length / 3 : 0;
  36181. for (var index = 0; index < other.indices.length; index++) {
  36182. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36183. this.indices.push(other.indices[index] + offset);
  36184. }
  36185. }
  36186. this.positions = this._mergeElement(this.positions, other.positions);
  36187. this.normals = this._mergeElement(this.normals, other.normals);
  36188. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36189. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36190. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36191. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36192. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36193. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36194. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36195. this.colors = this._mergeElement(this.colors, other.colors);
  36196. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36197. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36198. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36199. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36200. return this;
  36201. };
  36202. VertexData.prototype._mergeElement = function (source, other) {
  36203. if (!source) {
  36204. return other;
  36205. }
  36206. if (!other) {
  36207. return source;
  36208. }
  36209. var len = other.length + source.length;
  36210. var isSrcTypedArray = source instanceof Float32Array;
  36211. var isOthTypedArray = other instanceof Float32Array;
  36212. // use non-loop method when the source is Float32Array
  36213. if (isSrcTypedArray) {
  36214. var ret32 = new Float32Array(len);
  36215. ret32.set(source);
  36216. ret32.set(other, source.length);
  36217. return ret32;
  36218. // source is number[], when other is also use concat
  36219. }
  36220. else if (!isOthTypedArray) {
  36221. return source.concat(other);
  36222. // source is a number[], but other is a Float32Array, loop required
  36223. }
  36224. else {
  36225. var ret = source.slice(0); // copy source to a separate array
  36226. for (var i = 0, len = other.length; i < len; i++) {
  36227. ret.push(other[i]);
  36228. }
  36229. return ret;
  36230. }
  36231. };
  36232. VertexData.prototype._validate = function () {
  36233. if (!this.positions) {
  36234. throw new Error("Positions are required");
  36235. }
  36236. var getElementCount = function (kind, values) {
  36237. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36238. if ((values.length % stride) !== 0) {
  36239. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36240. }
  36241. return values.length / stride;
  36242. };
  36243. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36244. var validateElementCount = function (kind, values) {
  36245. var elementCount = getElementCount(kind, values);
  36246. if (elementCount !== positionsElementCount) {
  36247. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36248. }
  36249. };
  36250. if (this.normals)
  36251. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36252. if (this.tangents)
  36253. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36254. if (this.uvs)
  36255. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36256. if (this.uvs2)
  36257. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36258. if (this.uvs3)
  36259. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36260. if (this.uvs4)
  36261. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36262. if (this.uvs5)
  36263. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36264. if (this.uvs6)
  36265. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36266. if (this.colors)
  36267. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36268. if (this.matricesIndices)
  36269. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36270. if (this.matricesWeights)
  36271. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36272. if (this.matricesIndicesExtra)
  36273. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36274. if (this.matricesWeightsExtra)
  36275. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36276. };
  36277. /**
  36278. * Serializes the VertexData
  36279. * @returns a serialized object
  36280. */
  36281. VertexData.prototype.serialize = function () {
  36282. var serializationObject = this.serialize();
  36283. if (this.positions) {
  36284. serializationObject.positions = this.positions;
  36285. }
  36286. if (this.normals) {
  36287. serializationObject.normals = this.normals;
  36288. }
  36289. if (this.tangents) {
  36290. serializationObject.tangents = this.tangents;
  36291. }
  36292. if (this.uvs) {
  36293. serializationObject.uvs = this.uvs;
  36294. }
  36295. if (this.uvs2) {
  36296. serializationObject.uvs2 = this.uvs2;
  36297. }
  36298. if (this.uvs3) {
  36299. serializationObject.uvs3 = this.uvs3;
  36300. }
  36301. if (this.uvs4) {
  36302. serializationObject.uvs4 = this.uvs4;
  36303. }
  36304. if (this.uvs5) {
  36305. serializationObject.uvs5 = this.uvs5;
  36306. }
  36307. if (this.uvs6) {
  36308. serializationObject.uvs6 = this.uvs6;
  36309. }
  36310. if (this.colors) {
  36311. serializationObject.colors = this.colors;
  36312. }
  36313. if (this.matricesIndices) {
  36314. serializationObject.matricesIndices = this.matricesIndices;
  36315. serializationObject.matricesIndices._isExpanded = true;
  36316. }
  36317. if (this.matricesWeights) {
  36318. serializationObject.matricesWeights = this.matricesWeights;
  36319. }
  36320. if (this.matricesIndicesExtra) {
  36321. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36322. serializationObject.matricesIndicesExtra._isExpanded = true;
  36323. }
  36324. if (this.matricesWeightsExtra) {
  36325. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36326. }
  36327. serializationObject.indices = this.indices;
  36328. return serializationObject;
  36329. };
  36330. // Statics
  36331. /**
  36332. * Extracts the vertexData from a mesh
  36333. * @param mesh the mesh from which to extract the VertexData
  36334. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36335. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36336. * @returns the object VertexData associated to the passed mesh
  36337. */
  36338. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36339. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36340. };
  36341. /**
  36342. * Extracts the vertexData from the geometry
  36343. * @param geometry the geometry from which to extract the VertexData
  36344. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36345. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36346. * @returns the object VertexData associated to the passed mesh
  36347. */
  36348. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36349. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36350. };
  36351. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36352. var result = new VertexData();
  36353. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36354. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36355. }
  36356. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36357. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36358. }
  36359. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36360. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36361. }
  36362. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36363. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36364. }
  36365. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36366. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36367. }
  36368. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36369. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36370. }
  36371. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36372. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36373. }
  36374. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36375. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36376. }
  36377. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36378. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36379. }
  36380. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36381. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36382. }
  36383. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36384. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36385. }
  36386. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36387. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36388. }
  36389. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36390. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36391. }
  36392. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36393. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36394. }
  36395. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36396. return result;
  36397. };
  36398. /**
  36399. * Creates the VertexData for a Ribbon
  36400. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36401. * * pathArray array of paths, each of which an array of successive Vector3
  36402. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36403. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36404. * * 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
  36405. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36406. * * 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)
  36407. * * 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)
  36408. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36409. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36410. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36411. * @returns the VertexData of the ribbon
  36412. */
  36413. VertexData.CreateRibbon = function (options) {
  36414. var pathArray = options.pathArray;
  36415. var closeArray = options.closeArray || false;
  36416. var closePath = options.closePath || false;
  36417. var invertUV = options.invertUV || false;
  36418. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36419. var offset = options.offset || defaultOffset;
  36420. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36421. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36422. var customUV = options.uvs;
  36423. var customColors = options.colors;
  36424. var positions = [];
  36425. var indices = [];
  36426. var normals = [];
  36427. var uvs = [];
  36428. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36429. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36430. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36431. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36432. var minlg; // minimal length among all paths from pathArray
  36433. var lg = []; // array of path lengths : nb of vertex per path
  36434. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36435. var p; // path iterator
  36436. var i; // point iterator
  36437. var j; // point iterator
  36438. // if single path in pathArray
  36439. if (pathArray.length < 2) {
  36440. var ar1 = [];
  36441. var ar2 = [];
  36442. for (i = 0; i < pathArray[0].length - offset; i++) {
  36443. ar1.push(pathArray[0][i]);
  36444. ar2.push(pathArray[0][i + offset]);
  36445. }
  36446. pathArray = [ar1, ar2];
  36447. }
  36448. // positions and horizontal distances (u)
  36449. var idc = 0;
  36450. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36451. var path;
  36452. var l;
  36453. minlg = pathArray[0].length;
  36454. var vectlg;
  36455. var dist;
  36456. for (p = 0; p < pathArray.length; p++) {
  36457. uTotalDistance[p] = 0;
  36458. us[p] = [0];
  36459. path = pathArray[p];
  36460. l = path.length;
  36461. minlg = (minlg < l) ? minlg : l;
  36462. j = 0;
  36463. while (j < l) {
  36464. positions.push(path[j].x, path[j].y, path[j].z);
  36465. if (j > 0) {
  36466. vectlg = path[j].subtract(path[j - 1]).length();
  36467. dist = vectlg + uTotalDistance[p];
  36468. us[p].push(dist);
  36469. uTotalDistance[p] = dist;
  36470. }
  36471. j++;
  36472. }
  36473. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36474. j--;
  36475. positions.push(path[0].x, path[0].y, path[0].z);
  36476. vectlg = path[j].subtract(path[0]).length();
  36477. dist = vectlg + uTotalDistance[p];
  36478. us[p].push(dist);
  36479. uTotalDistance[p] = dist;
  36480. }
  36481. lg[p] = l + closePathCorr;
  36482. idx[p] = idc;
  36483. idc += (l + closePathCorr);
  36484. }
  36485. // vertical distances (v)
  36486. var path1;
  36487. var path2;
  36488. var vertex1 = null;
  36489. var vertex2 = null;
  36490. for (i = 0; i < minlg + closePathCorr; i++) {
  36491. vTotalDistance[i] = 0;
  36492. vs[i] = [0];
  36493. for (p = 0; p < pathArray.length - 1; p++) {
  36494. path1 = pathArray[p];
  36495. path2 = pathArray[p + 1];
  36496. if (i === minlg) { // closePath
  36497. vertex1 = path1[0];
  36498. vertex2 = path2[0];
  36499. }
  36500. else {
  36501. vertex1 = path1[i];
  36502. vertex2 = path2[i];
  36503. }
  36504. vectlg = vertex2.subtract(vertex1).length();
  36505. dist = vectlg + vTotalDistance[i];
  36506. vs[i].push(dist);
  36507. vTotalDistance[i] = dist;
  36508. }
  36509. if (closeArray && vertex2 && vertex1) {
  36510. path1 = pathArray[p];
  36511. path2 = pathArray[0];
  36512. if (i === minlg) { // closePath
  36513. vertex2 = path2[0];
  36514. }
  36515. vectlg = vertex2.subtract(vertex1).length();
  36516. dist = vectlg + vTotalDistance[i];
  36517. vTotalDistance[i] = dist;
  36518. }
  36519. }
  36520. // uvs
  36521. var u;
  36522. var v;
  36523. if (customUV) {
  36524. for (p = 0; p < customUV.length; p++) {
  36525. uvs.push(customUV[p].x, customUV[p].y);
  36526. }
  36527. }
  36528. else {
  36529. for (p = 0; p < pathArray.length; p++) {
  36530. for (i = 0; i < minlg + closePathCorr; i++) {
  36531. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36532. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36533. if (invertUV) {
  36534. uvs.push(v, u);
  36535. }
  36536. else {
  36537. uvs.push(u, v);
  36538. }
  36539. }
  36540. }
  36541. }
  36542. // indices
  36543. p = 0; // path index
  36544. var pi = 0; // positions array index
  36545. var l1 = lg[p] - 1; // path1 length
  36546. var l2 = lg[p + 1] - 1; // path2 length
  36547. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36548. var shft = idx[1] - idx[0]; // shift
  36549. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36550. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36551. // 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
  36552. indices.push(pi, pi + shft, pi + 1);
  36553. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36554. pi += 1;
  36555. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36556. p++;
  36557. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36558. shft = idx[0] - idx[p];
  36559. l1 = lg[p] - 1;
  36560. l2 = lg[0] - 1;
  36561. }
  36562. else {
  36563. shft = idx[p + 1] - idx[p];
  36564. l1 = lg[p] - 1;
  36565. l2 = lg[p + 1] - 1;
  36566. }
  36567. pi = idx[p];
  36568. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36569. }
  36570. }
  36571. // normals
  36572. VertexData.ComputeNormals(positions, indices, normals);
  36573. if (closePath) { // update both the first and last vertex normals to their average value
  36574. var indexFirst = 0;
  36575. var indexLast = 0;
  36576. for (p = 0; p < pathArray.length; p++) {
  36577. indexFirst = idx[p] * 3;
  36578. if (p + 1 < pathArray.length) {
  36579. indexLast = (idx[p + 1] - 1) * 3;
  36580. }
  36581. else {
  36582. indexLast = normals.length - 3;
  36583. }
  36584. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36585. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36586. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36587. normals[indexLast] = normals[indexFirst];
  36588. normals[indexLast + 1] = normals[indexFirst + 1];
  36589. normals[indexLast + 2] = normals[indexFirst + 2];
  36590. }
  36591. }
  36592. // sides
  36593. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36594. // Colors
  36595. var colors = null;
  36596. if (customColors) {
  36597. colors = new Float32Array(customColors.length * 4);
  36598. for (var c = 0; c < customColors.length; c++) {
  36599. colors[c * 4] = customColors[c].r;
  36600. colors[c * 4 + 1] = customColors[c].g;
  36601. colors[c * 4 + 2] = customColors[c].b;
  36602. colors[c * 4 + 3] = customColors[c].a;
  36603. }
  36604. }
  36605. // Result
  36606. var vertexData = new VertexData();
  36607. var positions32 = new Float32Array(positions);
  36608. var normals32 = new Float32Array(normals);
  36609. var uvs32 = new Float32Array(uvs);
  36610. vertexData.indices = indices;
  36611. vertexData.positions = positions32;
  36612. vertexData.normals = normals32;
  36613. vertexData.uvs = uvs32;
  36614. if (colors) {
  36615. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36616. }
  36617. if (closePath) {
  36618. vertexData._idx = idx;
  36619. }
  36620. return vertexData;
  36621. };
  36622. /**
  36623. * Creates the VertexData for a box
  36624. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36625. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36626. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36627. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36628. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36629. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36630. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36631. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36632. * * 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)
  36633. * * 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)
  36634. * @returns the VertexData of the box
  36635. */
  36636. VertexData.CreateBox = function (options) {
  36637. var normalsSource = [
  36638. new BABYLON.Vector3(0, 0, 1),
  36639. new BABYLON.Vector3(0, 0, -1),
  36640. new BABYLON.Vector3(1, 0, 0),
  36641. new BABYLON.Vector3(-1, 0, 0),
  36642. new BABYLON.Vector3(0, 1, 0),
  36643. new BABYLON.Vector3(0, -1, 0)
  36644. ];
  36645. var indices = [];
  36646. var positions = [];
  36647. var normals = [];
  36648. var uvs = [];
  36649. var width = options.width || options.size || 1;
  36650. var height = options.height || options.size || 1;
  36651. var depth = options.depth || options.size || 1;
  36652. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36653. var faceUV = options.faceUV || new Array(6);
  36654. var faceColors = options.faceColors;
  36655. var colors = [];
  36656. // default face colors and UV if undefined
  36657. for (var f = 0; f < 6; f++) {
  36658. if (faceUV[f] === undefined) {
  36659. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36660. }
  36661. if (faceColors && faceColors[f] === undefined) {
  36662. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36663. }
  36664. }
  36665. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36666. // Create each face in turn.
  36667. for (var index = 0; index < normalsSource.length; index++) {
  36668. var normal = normalsSource[index];
  36669. // Get two vectors perpendicular to the face normal and to each other.
  36670. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36671. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36672. // Six indices (two triangles) per face.
  36673. var verticesLength = positions.length / 3;
  36674. indices.push(verticesLength);
  36675. indices.push(verticesLength + 1);
  36676. indices.push(verticesLength + 2);
  36677. indices.push(verticesLength);
  36678. indices.push(verticesLength + 2);
  36679. indices.push(verticesLength + 3);
  36680. // Four vertices per face.
  36681. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36682. positions.push(vertex.x, vertex.y, vertex.z);
  36683. normals.push(normal.x, normal.y, normal.z);
  36684. uvs.push(faceUV[index].z, faceUV[index].w);
  36685. if (faceColors) {
  36686. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36687. }
  36688. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36689. positions.push(vertex.x, vertex.y, vertex.z);
  36690. normals.push(normal.x, normal.y, normal.z);
  36691. uvs.push(faceUV[index].x, faceUV[index].w);
  36692. if (faceColors) {
  36693. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36694. }
  36695. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36696. positions.push(vertex.x, vertex.y, vertex.z);
  36697. normals.push(normal.x, normal.y, normal.z);
  36698. uvs.push(faceUV[index].x, faceUV[index].y);
  36699. if (faceColors) {
  36700. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36701. }
  36702. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36703. positions.push(vertex.x, vertex.y, vertex.z);
  36704. normals.push(normal.x, normal.y, normal.z);
  36705. uvs.push(faceUV[index].z, faceUV[index].y);
  36706. if (faceColors) {
  36707. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36708. }
  36709. }
  36710. // sides
  36711. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36712. // Result
  36713. var vertexData = new VertexData();
  36714. vertexData.indices = indices;
  36715. vertexData.positions = positions;
  36716. vertexData.normals = normals;
  36717. vertexData.uvs = uvs;
  36718. if (faceColors) {
  36719. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36720. vertexData.colors = totalColors;
  36721. }
  36722. return vertexData;
  36723. };
  36724. /**
  36725. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36726. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36727. * * segments sets the number of horizontal strips optional, default 32
  36728. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36729. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36730. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36731. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36732. * * 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
  36733. * * 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
  36734. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36735. * * 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)
  36736. * * 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)
  36737. * @returns the VertexData of the ellipsoid
  36738. */
  36739. VertexData.CreateSphere = function (options) {
  36740. var segments = options.segments || 32;
  36741. var diameterX = options.diameterX || options.diameter || 1;
  36742. var diameterY = options.diameterY || options.diameter || 1;
  36743. var diameterZ = options.diameterZ || options.diameter || 1;
  36744. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36745. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36746. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36747. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36748. var totalZRotationSteps = 2 + segments;
  36749. var totalYRotationSteps = 2 * totalZRotationSteps;
  36750. var indices = [];
  36751. var positions = [];
  36752. var normals = [];
  36753. var uvs = [];
  36754. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36755. var normalizedZ = zRotationStep / totalZRotationSteps;
  36756. var angleZ = normalizedZ * Math.PI * slice;
  36757. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36758. var normalizedY = yRotationStep / totalYRotationSteps;
  36759. var angleY = normalizedY * Math.PI * 2 * arc;
  36760. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36761. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36762. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36763. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36764. var vertex = complete.multiply(radius);
  36765. var normal = complete.divide(radius).normalize();
  36766. positions.push(vertex.x, vertex.y, vertex.z);
  36767. normals.push(normal.x, normal.y, normal.z);
  36768. uvs.push(normalizedY, normalizedZ);
  36769. }
  36770. if (zRotationStep > 0) {
  36771. var verticesCount = positions.length / 3;
  36772. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36773. indices.push((firstIndex));
  36774. indices.push((firstIndex + 1));
  36775. indices.push(firstIndex + totalYRotationSteps + 1);
  36776. indices.push((firstIndex + totalYRotationSteps + 1));
  36777. indices.push((firstIndex + 1));
  36778. indices.push((firstIndex + totalYRotationSteps + 2));
  36779. }
  36780. }
  36781. }
  36782. // Sides
  36783. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36784. // Result
  36785. var vertexData = new VertexData();
  36786. vertexData.indices = indices;
  36787. vertexData.positions = positions;
  36788. vertexData.normals = normals;
  36789. vertexData.uvs = uvs;
  36790. return vertexData;
  36791. };
  36792. /**
  36793. * Creates the VertexData for a cylinder, cone or prism
  36794. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36795. * * height sets the height (y direction) of the cylinder, optional, default 2
  36796. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36797. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36798. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36799. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36800. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36801. * * 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
  36802. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36803. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36804. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36805. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36806. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36807. * * 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)
  36808. * * 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)
  36809. * @returns the VertexData of the cylinder, cone or prism
  36810. */
  36811. VertexData.CreateCylinder = function (options) {
  36812. var height = options.height || 2;
  36813. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36814. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36815. var tessellation = options.tessellation || 24;
  36816. var subdivisions = options.subdivisions || 1;
  36817. var hasRings = options.hasRings ? true : false;
  36818. var enclose = options.enclose ? true : false;
  36819. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36820. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36821. var faceUV = options.faceUV || new Array(3);
  36822. var faceColors = options.faceColors;
  36823. // default face colors and UV if undefined
  36824. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36825. var ringNb = (hasRings) ? subdivisions : 1;
  36826. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36827. var f;
  36828. for (f = 0; f < surfaceNb; f++) {
  36829. if (faceColors && faceColors[f] === undefined) {
  36830. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36831. }
  36832. }
  36833. for (f = 0; f < surfaceNb; f++) {
  36834. if (faceUV && faceUV[f] === undefined) {
  36835. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36836. }
  36837. }
  36838. var indices = new Array();
  36839. var positions = new Array();
  36840. var normals = new Array();
  36841. var uvs = new Array();
  36842. var colors = new Array();
  36843. var angle_step = Math.PI * 2 * arc / tessellation;
  36844. var angle;
  36845. var h;
  36846. var radius;
  36847. var tan = (diameterBottom - diameterTop) / 2 / height;
  36848. var ringVertex = BABYLON.Vector3.Zero();
  36849. var ringNormal = BABYLON.Vector3.Zero();
  36850. var ringFirstVertex = BABYLON.Vector3.Zero();
  36851. var ringFirstNormal = BABYLON.Vector3.Zero();
  36852. var quadNormal = BABYLON.Vector3.Zero();
  36853. var Y = BABYLON.Axis.Y;
  36854. // positions, normals, uvs
  36855. var i;
  36856. var j;
  36857. var r;
  36858. var ringIdx = 1;
  36859. var s = 1; // surface index
  36860. var cs = 0;
  36861. var v = 0;
  36862. for (i = 0; i <= subdivisions; i++) {
  36863. h = i / subdivisions;
  36864. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  36865. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  36866. for (r = 0; r < ringIdx; r++) {
  36867. if (hasRings) {
  36868. s += r;
  36869. }
  36870. if (enclose) {
  36871. s += 2 * r;
  36872. }
  36873. for (j = 0; j <= tessellation; j++) {
  36874. angle = j * angle_step;
  36875. // position
  36876. ringVertex.x = Math.cos(-angle) * radius;
  36877. ringVertex.y = -height / 2 + h * height;
  36878. ringVertex.z = Math.sin(-angle) * radius;
  36879. // normal
  36880. if (diameterTop === 0 && i === subdivisions) {
  36881. // if no top cap, reuse former normals
  36882. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  36883. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  36884. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  36885. }
  36886. else {
  36887. ringNormal.x = ringVertex.x;
  36888. ringNormal.z = ringVertex.z;
  36889. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  36890. ringNormal.normalize();
  36891. }
  36892. // keep first ring vertex values for enclose
  36893. if (j === 0) {
  36894. ringFirstVertex.copyFrom(ringVertex);
  36895. ringFirstNormal.copyFrom(ringNormal);
  36896. }
  36897. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36898. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  36899. if (hasRings) {
  36900. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  36901. }
  36902. else {
  36903. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  36904. }
  36905. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  36906. if (faceColors) {
  36907. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  36908. }
  36909. }
  36910. // if enclose, add four vertices and their dedicated normals
  36911. if (arc !== 1 && enclose) {
  36912. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  36913. positions.push(0, ringVertex.y, 0);
  36914. positions.push(0, ringVertex.y, 0);
  36915. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  36916. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  36917. quadNormal.normalize();
  36918. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36919. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  36920. quadNormal.normalize();
  36921. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  36922. if (hasRings) {
  36923. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  36924. }
  36925. else {
  36926. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  36927. }
  36928. uvs.push(faceUV[s + 1].x, v);
  36929. uvs.push(faceUV[s + 1].z, v);
  36930. if (hasRings) {
  36931. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  36932. }
  36933. else {
  36934. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  36935. }
  36936. uvs.push(faceUV[s + 2].x, v);
  36937. uvs.push(faceUV[s + 2].z, v);
  36938. if (faceColors) {
  36939. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36940. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  36941. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36942. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  36943. }
  36944. }
  36945. if (cs !== s) {
  36946. cs = s;
  36947. }
  36948. }
  36949. }
  36950. // indices
  36951. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  36952. var s;
  36953. i = 0;
  36954. for (s = 0; s < subdivisions; s++) {
  36955. var i0 = 0;
  36956. var i1 = 0;
  36957. var i2 = 0;
  36958. var i3 = 0;
  36959. for (j = 0; j < tessellation; j++) {
  36960. i0 = i * (e + 1) + j;
  36961. i1 = (i + 1) * (e + 1) + j;
  36962. i2 = i * (e + 1) + (j + 1);
  36963. i3 = (i + 1) * (e + 1) + (j + 1);
  36964. indices.push(i0, i1, i2);
  36965. indices.push(i3, i2, i1);
  36966. }
  36967. if (arc !== 1 && enclose) { // if enclose, add two quads
  36968. indices.push(i0 + 2, i1 + 2, i2 + 2);
  36969. indices.push(i3 + 2, i2 + 2, i1 + 2);
  36970. indices.push(i0 + 4, i1 + 4, i2 + 4);
  36971. indices.push(i3 + 4, i2 + 4, i1 + 4);
  36972. }
  36973. i = (hasRings) ? (i + 2) : (i + 1);
  36974. }
  36975. // Caps
  36976. var createCylinderCap = function (isTop) {
  36977. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  36978. if (radius === 0) {
  36979. return;
  36980. }
  36981. // Cap positions, normals & uvs
  36982. var angle;
  36983. var circleVector;
  36984. var i;
  36985. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  36986. var c = null;
  36987. if (faceColors) {
  36988. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  36989. }
  36990. // cap center
  36991. var vbase = positions.length / 3;
  36992. var offset = isTop ? height / 2 : -height / 2;
  36993. var center = new BABYLON.Vector3(0, offset, 0);
  36994. positions.push(center.x, center.y, center.z);
  36995. normals.push(0, isTop ? 1 : -1, 0);
  36996. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  36997. if (c) {
  36998. colors.push(c.r, c.g, c.b, c.a);
  36999. }
  37000. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37001. for (i = 0; i <= tessellation; i++) {
  37002. angle = Math.PI * 2 * i * arc / tessellation;
  37003. var cos = Math.cos(-angle);
  37004. var sin = Math.sin(-angle);
  37005. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37006. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37007. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37008. normals.push(0, isTop ? 1 : -1, 0);
  37009. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37010. if (c) {
  37011. colors.push(c.r, c.g, c.b, c.a);
  37012. }
  37013. }
  37014. // Cap indices
  37015. for (i = 0; i < tessellation; i++) {
  37016. if (!isTop) {
  37017. indices.push(vbase);
  37018. indices.push(vbase + (i + 1));
  37019. indices.push(vbase + (i + 2));
  37020. }
  37021. else {
  37022. indices.push(vbase);
  37023. indices.push(vbase + (i + 2));
  37024. indices.push(vbase + (i + 1));
  37025. }
  37026. }
  37027. };
  37028. // add caps to geometry
  37029. createCylinderCap(false);
  37030. createCylinderCap(true);
  37031. // Sides
  37032. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37033. var vertexData = new VertexData();
  37034. vertexData.indices = indices;
  37035. vertexData.positions = positions;
  37036. vertexData.normals = normals;
  37037. vertexData.uvs = uvs;
  37038. if (faceColors) {
  37039. vertexData.colors = colors;
  37040. }
  37041. return vertexData;
  37042. };
  37043. /**
  37044. * Creates the VertexData for a torus
  37045. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37046. * * diameter the diameter of the torus, optional default 1
  37047. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37048. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37049. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37050. * * 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)
  37051. * * 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)
  37052. * @returns the VertexData of the torus
  37053. */
  37054. VertexData.CreateTorus = function (options) {
  37055. var indices = [];
  37056. var positions = [];
  37057. var normals = [];
  37058. var uvs = [];
  37059. var diameter = options.diameter || 1;
  37060. var thickness = options.thickness || 0.5;
  37061. var tessellation = options.tessellation || 16;
  37062. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37063. var stride = tessellation + 1;
  37064. for (var i = 0; i <= tessellation; i++) {
  37065. var u = i / tessellation;
  37066. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37067. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37068. for (var j = 0; j <= tessellation; j++) {
  37069. var v = 1 - j / tessellation;
  37070. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37071. var dx = Math.cos(innerAngle);
  37072. var dy = Math.sin(innerAngle);
  37073. // Create a vertex.
  37074. var normal = new BABYLON.Vector3(dx, dy, 0);
  37075. var position = normal.scale(thickness / 2);
  37076. var textureCoordinate = new BABYLON.Vector2(u, v);
  37077. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37078. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37079. positions.push(position.x, position.y, position.z);
  37080. normals.push(normal.x, normal.y, normal.z);
  37081. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37082. // And create indices for two triangles.
  37083. var nextI = (i + 1) % stride;
  37084. var nextJ = (j + 1) % stride;
  37085. indices.push(i * stride + j);
  37086. indices.push(i * stride + nextJ);
  37087. indices.push(nextI * stride + j);
  37088. indices.push(i * stride + nextJ);
  37089. indices.push(nextI * stride + nextJ);
  37090. indices.push(nextI * stride + j);
  37091. }
  37092. }
  37093. // Sides
  37094. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37095. // Result
  37096. var vertexData = new VertexData();
  37097. vertexData.indices = indices;
  37098. vertexData.positions = positions;
  37099. vertexData.normals = normals;
  37100. vertexData.uvs = uvs;
  37101. return vertexData;
  37102. };
  37103. /**
  37104. * Creates the VertexData of the LineSystem
  37105. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37106. * - lines an array of lines, each line being an array of successive Vector3
  37107. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37108. * @returns the VertexData of the LineSystem
  37109. */
  37110. VertexData.CreateLineSystem = function (options) {
  37111. var indices = [];
  37112. var positions = [];
  37113. var lines = options.lines;
  37114. var colors = options.colors;
  37115. var vertexColors = [];
  37116. var idx = 0;
  37117. for (var l = 0; l < lines.length; l++) {
  37118. var points = lines[l];
  37119. for (var index = 0; index < points.length; index++) {
  37120. positions.push(points[index].x, points[index].y, points[index].z);
  37121. if (colors) {
  37122. var color = colors[l];
  37123. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37124. }
  37125. if (index > 0) {
  37126. indices.push(idx - 1);
  37127. indices.push(idx);
  37128. }
  37129. idx++;
  37130. }
  37131. }
  37132. var vertexData = new VertexData();
  37133. vertexData.indices = indices;
  37134. vertexData.positions = positions;
  37135. if (colors) {
  37136. vertexData.colors = vertexColors;
  37137. }
  37138. return vertexData;
  37139. };
  37140. /**
  37141. * Create the VertexData for a DashedLines
  37142. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37143. * - points an array successive Vector3
  37144. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37145. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37146. * - dashNb the intended total number of dashes, optional, default 200
  37147. * @returns the VertexData for the DashedLines
  37148. */
  37149. VertexData.CreateDashedLines = function (options) {
  37150. var dashSize = options.dashSize || 3;
  37151. var gapSize = options.gapSize || 1;
  37152. var dashNb = options.dashNb || 200;
  37153. var points = options.points;
  37154. var positions = new Array();
  37155. var indices = new Array();
  37156. var curvect = BABYLON.Vector3.Zero();
  37157. var lg = 0;
  37158. var nb = 0;
  37159. var shft = 0;
  37160. var dashshft = 0;
  37161. var curshft = 0;
  37162. var idx = 0;
  37163. var i = 0;
  37164. for (i = 0; i < points.length - 1; i++) {
  37165. points[i + 1].subtractToRef(points[i], curvect);
  37166. lg += curvect.length();
  37167. }
  37168. shft = lg / dashNb;
  37169. dashshft = dashSize * shft / (dashSize + gapSize);
  37170. for (i = 0; i < points.length - 1; i++) {
  37171. points[i + 1].subtractToRef(points[i], curvect);
  37172. nb = Math.floor(curvect.length() / shft);
  37173. curvect.normalize();
  37174. for (var j = 0; j < nb; j++) {
  37175. curshft = shft * j;
  37176. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37177. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37178. indices.push(idx, idx + 1);
  37179. idx += 2;
  37180. }
  37181. }
  37182. // Result
  37183. var vertexData = new VertexData();
  37184. vertexData.positions = positions;
  37185. vertexData.indices = indices;
  37186. return vertexData;
  37187. };
  37188. /**
  37189. * Creates the VertexData for a Ground
  37190. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37191. * - width the width (x direction) of the ground, optional, default 1
  37192. * - height the height (z direction) of the ground, optional, default 1
  37193. * - subdivisions the number of subdivisions per side, optional, default 1
  37194. * @returns the VertexData of the Ground
  37195. */
  37196. VertexData.CreateGround = function (options) {
  37197. var indices = [];
  37198. var positions = [];
  37199. var normals = [];
  37200. var uvs = [];
  37201. var row, col;
  37202. var width = options.width || 1;
  37203. var height = options.height || 1;
  37204. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37205. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37206. for (row = 0; row <= subdivisionsY; row++) {
  37207. for (col = 0; col <= subdivisionsX; col++) {
  37208. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37209. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37210. positions.push(position.x, position.y, position.z);
  37211. normals.push(normal.x, normal.y, normal.z);
  37212. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37213. }
  37214. }
  37215. for (row = 0; row < subdivisionsY; row++) {
  37216. for (col = 0; col < subdivisionsX; col++) {
  37217. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37218. indices.push(col + 1 + row * (subdivisionsX + 1));
  37219. indices.push(col + row * (subdivisionsX + 1));
  37220. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37221. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37222. indices.push(col + row * (subdivisionsX + 1));
  37223. }
  37224. }
  37225. // Result
  37226. var vertexData = new VertexData();
  37227. vertexData.indices = indices;
  37228. vertexData.positions = positions;
  37229. vertexData.normals = normals;
  37230. vertexData.uvs = uvs;
  37231. return vertexData;
  37232. };
  37233. /**
  37234. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37235. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37236. * * xmin the ground minimum X coordinate, optional, default -1
  37237. * * zmin the ground minimum Z coordinate, optional, default -1
  37238. * * xmax the ground maximum X coordinate, optional, default 1
  37239. * * zmax the ground maximum Z coordinate, optional, default 1
  37240. * * 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}
  37241. * * 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}
  37242. * @returns the VertexData of the TiledGround
  37243. */
  37244. VertexData.CreateTiledGround = function (options) {
  37245. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37246. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37247. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37248. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37249. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37250. var precision = options.precision || { w: 1, h: 1 };
  37251. var indices = new Array();
  37252. var positions = new Array();
  37253. var normals = new Array();
  37254. var uvs = new Array();
  37255. var row, col, tileRow, tileCol;
  37256. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37257. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37258. precision.w = (precision.w < 1) ? 1 : precision.w;
  37259. precision.h = (precision.h < 1) ? 1 : precision.h;
  37260. var tileSize = {
  37261. 'w': (xmax - xmin) / subdivisions.w,
  37262. 'h': (zmax - zmin) / subdivisions.h
  37263. };
  37264. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37265. // Indices
  37266. var base = positions.length / 3;
  37267. var rowLength = precision.w + 1;
  37268. for (row = 0; row < precision.h; row++) {
  37269. for (col = 0; col < precision.w; col++) {
  37270. var square = [
  37271. base + col + row * rowLength,
  37272. base + (col + 1) + row * rowLength,
  37273. base + (col + 1) + (row + 1) * rowLength,
  37274. base + col + (row + 1) * rowLength
  37275. ];
  37276. indices.push(square[1]);
  37277. indices.push(square[2]);
  37278. indices.push(square[3]);
  37279. indices.push(square[0]);
  37280. indices.push(square[1]);
  37281. indices.push(square[3]);
  37282. }
  37283. }
  37284. // Position, normals and uvs
  37285. var position = BABYLON.Vector3.Zero();
  37286. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37287. for (row = 0; row <= precision.h; row++) {
  37288. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37289. for (col = 0; col <= precision.w; col++) {
  37290. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37291. position.y = 0;
  37292. positions.push(position.x, position.y, position.z);
  37293. normals.push(normal.x, normal.y, normal.z);
  37294. uvs.push(col / precision.w, row / precision.h);
  37295. }
  37296. }
  37297. }
  37298. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37299. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37300. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37301. }
  37302. }
  37303. // Result
  37304. var vertexData = new VertexData();
  37305. vertexData.indices = indices;
  37306. vertexData.positions = positions;
  37307. vertexData.normals = normals;
  37308. vertexData.uvs = uvs;
  37309. return vertexData;
  37310. };
  37311. /**
  37312. * Creates the VertexData of the Ground designed from a heightmap
  37313. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37314. * * width the width (x direction) of the ground
  37315. * * height the height (z direction) of the ground
  37316. * * subdivisions the number of subdivisions per side
  37317. * * minHeight the minimum altitude on the ground, optional, default 0
  37318. * * maxHeight the maximum altitude on the ground, optional default 1
  37319. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37320. * * buffer the array holding the image color data
  37321. * * bufferWidth the width of image
  37322. * * bufferHeight the height of image
  37323. * @returns the VertexData of the Ground designed from a heightmap
  37324. */
  37325. VertexData.CreateGroundFromHeightMap = function (options) {
  37326. var indices = [];
  37327. var positions = [];
  37328. var normals = [];
  37329. var uvs = [];
  37330. var row, col;
  37331. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37332. // Vertices
  37333. for (row = 0; row <= options.subdivisions; row++) {
  37334. for (col = 0; col <= options.subdivisions; col++) {
  37335. 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));
  37336. // Compute height
  37337. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37338. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37339. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37340. var r = options.buffer[pos] / 255.0;
  37341. var g = options.buffer[pos + 1] / 255.0;
  37342. var b = options.buffer[pos + 2] / 255.0;
  37343. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37344. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37345. // Add vertex
  37346. positions.push(position.x, position.y, position.z);
  37347. normals.push(0, 0, 0);
  37348. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37349. }
  37350. }
  37351. // Indices
  37352. for (row = 0; row < options.subdivisions; row++) {
  37353. for (col = 0; col < options.subdivisions; col++) {
  37354. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37355. indices.push(col + 1 + row * (options.subdivisions + 1));
  37356. indices.push(col + row * (options.subdivisions + 1));
  37357. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37358. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37359. indices.push(col + row * (options.subdivisions + 1));
  37360. }
  37361. }
  37362. // Normals
  37363. VertexData.ComputeNormals(positions, indices, normals);
  37364. // Result
  37365. var vertexData = new VertexData();
  37366. vertexData.indices = indices;
  37367. vertexData.positions = positions;
  37368. vertexData.normals = normals;
  37369. vertexData.uvs = uvs;
  37370. return vertexData;
  37371. };
  37372. /**
  37373. * Creates the VertexData for a Plane
  37374. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37375. * * size sets the width and height of the plane to the value of size, optional default 1
  37376. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37377. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37378. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37379. * * 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)
  37380. * * 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)
  37381. * @returns the VertexData of the box
  37382. */
  37383. VertexData.CreatePlane = function (options) {
  37384. var indices = [];
  37385. var positions = [];
  37386. var normals = [];
  37387. var uvs = [];
  37388. var width = options.width || options.size || 1;
  37389. var height = options.height || options.size || 1;
  37390. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37391. // Vertices
  37392. var halfWidth = width / 2.0;
  37393. var halfHeight = height / 2.0;
  37394. positions.push(-halfWidth, -halfHeight, 0);
  37395. normals.push(0, 0, -1.0);
  37396. uvs.push(0.0, 0.0);
  37397. positions.push(halfWidth, -halfHeight, 0);
  37398. normals.push(0, 0, -1.0);
  37399. uvs.push(1.0, 0.0);
  37400. positions.push(halfWidth, halfHeight, 0);
  37401. normals.push(0, 0, -1.0);
  37402. uvs.push(1.0, 1.0);
  37403. positions.push(-halfWidth, halfHeight, 0);
  37404. normals.push(0, 0, -1.0);
  37405. uvs.push(0.0, 1.0);
  37406. // Indices
  37407. indices.push(0);
  37408. indices.push(1);
  37409. indices.push(2);
  37410. indices.push(0);
  37411. indices.push(2);
  37412. indices.push(3);
  37413. // Sides
  37414. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37415. // Result
  37416. var vertexData = new VertexData();
  37417. vertexData.indices = indices;
  37418. vertexData.positions = positions;
  37419. vertexData.normals = normals;
  37420. vertexData.uvs = uvs;
  37421. return vertexData;
  37422. };
  37423. /**
  37424. * Creates the VertexData of the Disc or regular Polygon
  37425. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37426. * * radius the radius of the disc, optional default 0.5
  37427. * * tessellation the number of polygon sides, optional, default 64
  37428. * * 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
  37429. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37430. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37431. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37432. * @returns the VertexData of the box
  37433. */
  37434. VertexData.CreateDisc = function (options) {
  37435. var positions = new Array();
  37436. var indices = new Array();
  37437. var normals = new Array();
  37438. var uvs = new Array();
  37439. var radius = options.radius || 0.5;
  37440. var tessellation = options.tessellation || 64;
  37441. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37442. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37443. // positions and uvs
  37444. positions.push(0, 0, 0); // disc center first
  37445. uvs.push(0.5, 0.5);
  37446. var theta = Math.PI * 2 * arc;
  37447. var step = theta / tessellation;
  37448. for (var a = 0; a < theta; a += step) {
  37449. var x = Math.cos(a);
  37450. var y = Math.sin(a);
  37451. var u = (x + 1) / 2;
  37452. var v = (1 - y) / 2;
  37453. positions.push(radius * x, radius * y, 0);
  37454. uvs.push(u, v);
  37455. }
  37456. if (arc === 1) {
  37457. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37458. uvs.push(uvs[2], uvs[3]);
  37459. }
  37460. //indices
  37461. var vertexNb = positions.length / 3;
  37462. for (var i = 1; i < vertexNb - 1; i++) {
  37463. indices.push(i + 1, 0, i);
  37464. }
  37465. // result
  37466. VertexData.ComputeNormals(positions, indices, normals);
  37467. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37468. var vertexData = new VertexData();
  37469. vertexData.indices = indices;
  37470. vertexData.positions = positions;
  37471. vertexData.normals = normals;
  37472. vertexData.uvs = uvs;
  37473. return vertexData;
  37474. };
  37475. /**
  37476. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37477. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37478. * @param polygon a mesh built from polygonTriangulation.build()
  37479. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37480. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37481. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37482. * @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)
  37483. * @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)
  37484. * @returns the VertexData of the Polygon
  37485. */
  37486. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37487. var faceUV = fUV || new Array(3);
  37488. var faceColors = fColors;
  37489. var colors = [];
  37490. // default face colors and UV if undefined
  37491. for (var f = 0; f < 3; f++) {
  37492. if (faceUV[f] === undefined) {
  37493. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37494. }
  37495. if (faceColors && faceColors[f] === undefined) {
  37496. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37497. }
  37498. }
  37499. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37500. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37501. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37502. var indices = polygon.getIndices();
  37503. // set face colours and textures
  37504. var idx = 0;
  37505. var face = 0;
  37506. for (var index = 0; index < normals.length; index += 3) {
  37507. //Edge Face no. 1
  37508. if (Math.abs(normals[index + 1]) < 0.001) {
  37509. face = 1;
  37510. }
  37511. //Top Face no. 0
  37512. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37513. face = 0;
  37514. }
  37515. //Bottom Face no. 2
  37516. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37517. face = 2;
  37518. }
  37519. idx = index / 3;
  37520. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37521. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37522. if (faceColors) {
  37523. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37524. }
  37525. }
  37526. // sides
  37527. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37528. // Result
  37529. var vertexData = new VertexData();
  37530. vertexData.indices = indices;
  37531. vertexData.positions = positions;
  37532. vertexData.normals = normals;
  37533. vertexData.uvs = uvs;
  37534. if (faceColors) {
  37535. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37536. vertexData.colors = totalColors;
  37537. }
  37538. return vertexData;
  37539. };
  37540. /**
  37541. * Creates the VertexData of the IcoSphere
  37542. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37543. * * radius the radius of the IcoSphere, optional default 1
  37544. * * radiusX allows stretching in the x direction, optional, default radius
  37545. * * radiusY allows stretching in the y direction, optional, default radius
  37546. * * radiusZ allows stretching in the z direction, optional, default radius
  37547. * * flat when true creates a flat shaded mesh, optional, default true
  37548. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37549. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37550. * * 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)
  37551. * * 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)
  37552. * @returns the VertexData of the IcoSphere
  37553. */
  37554. VertexData.CreateIcoSphere = function (options) {
  37555. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37556. var radius = options.radius || 1;
  37557. var flat = (options.flat === undefined) ? true : options.flat;
  37558. var subdivisions = options.subdivisions || 4;
  37559. var radiusX = options.radiusX || radius;
  37560. var radiusY = options.radiusY || radius;
  37561. var radiusZ = options.radiusZ || radius;
  37562. var t = (1 + Math.sqrt(5)) / 2;
  37563. // 12 vertex x,y,z
  37564. var ico_vertices = [
  37565. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37566. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37567. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37568. ];
  37569. // index of 3 vertex makes a face of icopshere
  37570. var ico_indices = [
  37571. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37572. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37573. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37574. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37575. ];
  37576. // vertex for uv have aliased position, not for UV
  37577. var vertices_unalias_id = [
  37578. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37579. // vertex alias
  37580. 0,
  37581. 2,
  37582. 3,
  37583. 3,
  37584. 3,
  37585. 4,
  37586. 7,
  37587. 8,
  37588. 9,
  37589. 9,
  37590. 10,
  37591. 11 // 23: B + 12
  37592. ];
  37593. // uv as integer step (not pixels !)
  37594. var ico_vertexuv = [
  37595. 5, 1, 3, 1, 6, 4, 0, 0,
  37596. 5, 3, 4, 2, 2, 2, 4, 0,
  37597. 2, 0, 1, 1, 6, 0, 6, 2,
  37598. // vertex alias (for same vertex on different faces)
  37599. 0, 4,
  37600. 3, 3,
  37601. 4, 4,
  37602. 3, 1,
  37603. 4, 2,
  37604. 4, 4,
  37605. 0, 2,
  37606. 1, 1,
  37607. 2, 2,
  37608. 3, 3,
  37609. 1, 3,
  37610. 2, 4 // 23: B + 12
  37611. ];
  37612. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37613. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37614. // First island of uv mapping
  37615. // v = 4h 3+ 2
  37616. // v = 3h 9+ 4
  37617. // v = 2h 9+ 5 B
  37618. // v = 1h 9 1 0
  37619. // v = 0h 3 8 7 A
  37620. // u = 0 1 2 3 4 5 6 *a
  37621. // Second island of uv mapping
  37622. // v = 4h 0+ B+ 4+
  37623. // v = 3h A+ 2+
  37624. // v = 2h 7+ 6 3+
  37625. // v = 1h 8+ 3+
  37626. // v = 0h
  37627. // u = 0 1 2 3 4 5 6 *a
  37628. // Face layout on texture UV mapping
  37629. // ============
  37630. // \ 4 /\ 16 / ======
  37631. // \ / \ / /\ 11 /
  37632. // \/ 7 \/ / \ /
  37633. // ======= / 10 \/
  37634. // /\ 17 /\ =======
  37635. // / \ / \ \ 15 /\
  37636. // / 8 \/ 12 \ \ / \
  37637. // ============ \/ 6 \
  37638. // \ 18 /\ ============
  37639. // \ / \ \ 5 /\ 0 /
  37640. // \/ 13 \ \ / \ /
  37641. // ======= \/ 1 \/
  37642. // =============
  37643. // /\ 19 /\ 2 /\
  37644. // / \ / \ / \
  37645. // / 14 \/ 9 \/ 3 \
  37646. // ===================
  37647. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37648. var ustep = 138 / 1024;
  37649. var vstep = 239 / 1024;
  37650. var uoffset = 60 / 1024;
  37651. var voffset = 26 / 1024;
  37652. // Second island should have margin, not to touch the first island
  37653. // avoid any borderline artefact in pixel rounding
  37654. var island_u_offset = -40 / 1024;
  37655. var island_v_offset = +20 / 1024;
  37656. // face is either island 0 or 1 :
  37657. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37658. var island = [
  37659. 0, 0, 0, 0, 1,
  37660. 0, 0, 1, 1, 0,
  37661. 0, 0, 1, 1, 0,
  37662. 0, 1, 1, 1, 0 // 15 - 19
  37663. ];
  37664. var indices = new Array();
  37665. var positions = new Array();
  37666. var normals = new Array();
  37667. var uvs = new Array();
  37668. var current_indice = 0;
  37669. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37670. var face_vertex_pos = new Array(3);
  37671. var face_vertex_uv = new Array(3);
  37672. var v012;
  37673. for (v012 = 0; v012 < 3; v012++) {
  37674. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37675. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37676. }
  37677. // create all with normals
  37678. for (var face = 0; face < 20; face++) {
  37679. // 3 vertex per face
  37680. for (v012 = 0; v012 < 3; v012++) {
  37681. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37682. var v_id = ico_indices[3 * face + v012];
  37683. // vertex have 3D position (x,y,z)
  37684. 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]);
  37685. // Normalize to get normal, then scale to radius
  37686. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37687. // uv Coordinates from vertex ID
  37688. 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);
  37689. }
  37690. // Subdivide the face (interpolate pos, norm, uv)
  37691. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37692. // - norm is linear interpolation of vertex corner normal
  37693. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37694. // - uv is linear interpolation
  37695. //
  37696. // Topology is as below for sub-divide by 2
  37697. // vertex shown as v0,v1,v2
  37698. // interp index is i1 to progress in range [v0,v1[
  37699. // interp index is i2 to progress in range [v0,v2[
  37700. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37701. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37702. //
  37703. //
  37704. // i2 v2
  37705. // ^ ^
  37706. // / / \
  37707. // / / \
  37708. // / / \
  37709. // / / (0,1) \
  37710. // / #---------\
  37711. // / / \ (0,0)'/ \
  37712. // / / \ / \
  37713. // / / \ / \
  37714. // / / (0,0) \ / (1,0) \
  37715. // / #---------#---------\
  37716. // v0 v1
  37717. //
  37718. // --------------------> i1
  37719. //
  37720. // interp of (i1,i2):
  37721. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37722. // along i1 : lerp(x0,x1, i1/(S-i2))
  37723. //
  37724. // centroid of triangle is needed to get help normal computation
  37725. // (c1,c2) are used for centroid location
  37726. var interp_vertex = function (i1, i2, c1, c2) {
  37727. // vertex is interpolated from
  37728. // - face_vertex_pos[0..2]
  37729. // - face_vertex_uv[0..2]
  37730. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37731. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37732. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37733. pos_interp.normalize();
  37734. var vertex_normal;
  37735. if (flat) {
  37736. // in flat mode, recalculate normal as face centroid normal
  37737. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37738. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37739. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37740. }
  37741. else {
  37742. // in smooth mode, recalculate normal from each single vertex position
  37743. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37744. }
  37745. // Vertex normal need correction due to X,Y,Z radius scaling
  37746. vertex_normal.x /= radiusX;
  37747. vertex_normal.y /= radiusY;
  37748. vertex_normal.z /= radiusZ;
  37749. vertex_normal.normalize();
  37750. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37751. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37752. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37753. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37754. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37755. uvs.push(uv_interp.x, uv_interp.y);
  37756. // push each vertex has member of a face
  37757. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37758. indices.push(current_indice);
  37759. current_indice++;
  37760. };
  37761. for (var i2 = 0; i2 < subdivisions; i2++) {
  37762. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37763. // face : (i1,i2) for /\ :
  37764. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37765. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37766. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37767. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37768. if (i1 + i2 + 1 < subdivisions) {
  37769. // face : (i1,i2)' for \/ :
  37770. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37771. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37772. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37773. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37774. }
  37775. }
  37776. }
  37777. }
  37778. // Sides
  37779. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37780. // Result
  37781. var vertexData = new VertexData();
  37782. vertexData.indices = indices;
  37783. vertexData.positions = positions;
  37784. vertexData.normals = normals;
  37785. vertexData.uvs = uvs;
  37786. return vertexData;
  37787. };
  37788. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37789. /**
  37790. * Creates the VertexData for a Polyhedron
  37791. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37792. * * type provided types are:
  37793. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37794. * * 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)
  37795. * * size the size of the IcoSphere, optional default 1
  37796. * * sizeX allows stretching in the x direction, optional, default size
  37797. * * sizeY allows stretching in the y direction, optional, default size
  37798. * * sizeZ allows stretching in the z direction, optional, default size
  37799. * * 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
  37800. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37801. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37802. * * flat when true creates a flat shaded mesh, optional, default true
  37803. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37804. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37805. * * 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)
  37806. * * 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)
  37807. * @returns the VertexData of the Polyhedron
  37808. */
  37809. VertexData.CreatePolyhedron = function (options) {
  37810. // provided polyhedron types :
  37811. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37812. // 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)
  37813. var polyhedra = [];
  37814. 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]] };
  37815. 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]] };
  37816. polyhedra[2] = {
  37817. 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]],
  37818. 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]]
  37819. };
  37820. polyhedra[3] = {
  37821. 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]],
  37822. 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]]
  37823. };
  37824. polyhedra[4] = {
  37825. 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]],
  37826. 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]]
  37827. };
  37828. 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]] };
  37829. 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]] };
  37830. 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]] };
  37831. 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]] };
  37832. 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]] };
  37833. 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]] };
  37834. 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]] };
  37835. 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]] };
  37836. 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]] };
  37837. polyhedra[14] = {
  37838. 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]],
  37839. 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]]
  37840. };
  37841. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37842. var size = options.size;
  37843. var sizeX = options.sizeX || size || 1;
  37844. var sizeY = options.sizeY || size || 1;
  37845. var sizeZ = options.sizeZ || size || 1;
  37846. var data = options.custom || polyhedra[type];
  37847. var nbfaces = data.face.length;
  37848. var faceUV = options.faceUV || new Array(nbfaces);
  37849. var faceColors = options.faceColors;
  37850. var flat = (options.flat === undefined) ? true : options.flat;
  37851. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37852. var positions = new Array();
  37853. var indices = new Array();
  37854. var normals = new Array();
  37855. var uvs = new Array();
  37856. var colors = new Array();
  37857. var index = 0;
  37858. var faceIdx = 0; // face cursor in the array "indexes"
  37859. var indexes = new Array();
  37860. var i = 0;
  37861. var f = 0;
  37862. var u, v, ang, x, y, tmp;
  37863. // default face colors and UV if undefined
  37864. if (flat) {
  37865. for (f = 0; f < nbfaces; f++) {
  37866. if (faceColors && faceColors[f] === undefined) {
  37867. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37868. }
  37869. if (faceUV && faceUV[f] === undefined) {
  37870. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37871. }
  37872. }
  37873. }
  37874. if (!flat) {
  37875. for (i = 0; i < data.vertex.length; i++) {
  37876. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  37877. uvs.push(0, 0);
  37878. }
  37879. for (f = 0; f < nbfaces; f++) {
  37880. for (i = 0; i < data.face[f].length - 2; i++) {
  37881. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  37882. }
  37883. }
  37884. }
  37885. else {
  37886. for (f = 0; f < nbfaces; f++) {
  37887. var fl = data.face[f].length; // number of vertices of the current face
  37888. ang = 2 * Math.PI / fl;
  37889. x = 0.5 * Math.tan(ang / 2);
  37890. y = 0.5;
  37891. // positions, uvs, colors
  37892. for (i = 0; i < fl; i++) {
  37893. // positions
  37894. 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);
  37895. indexes.push(index);
  37896. index++;
  37897. // uvs
  37898. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  37899. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  37900. uvs.push(u, v);
  37901. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  37902. y = x * Math.sin(ang) + y * Math.cos(ang);
  37903. x = tmp;
  37904. // colors
  37905. if (faceColors) {
  37906. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  37907. }
  37908. }
  37909. // indices from indexes
  37910. for (i = 0; i < fl - 2; i++) {
  37911. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  37912. }
  37913. faceIdx += fl;
  37914. }
  37915. }
  37916. VertexData.ComputeNormals(positions, indices, normals);
  37917. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37918. var vertexData = new VertexData();
  37919. vertexData.positions = positions;
  37920. vertexData.indices = indices;
  37921. vertexData.normals = normals;
  37922. vertexData.uvs = uvs;
  37923. if (faceColors && flat) {
  37924. vertexData.colors = colors;
  37925. }
  37926. return vertexData;
  37927. };
  37928. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  37929. /**
  37930. * Creates the VertexData for a TorusKnot
  37931. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  37932. * * radius the radius of the torus knot, optional, default 2
  37933. * * tube the thickness of the tube, optional, default 0.5
  37934. * * radialSegments the number of sides on each tube segments, optional, default 32
  37935. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  37936. * * p the number of windings around the z axis, optional, default 2
  37937. * * q the number of windings around the x axis, optional, default 3
  37938. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37939. * * 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)
  37940. * * 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)
  37941. * @returns the VertexData of the Torus Knot
  37942. */
  37943. VertexData.CreateTorusKnot = function (options) {
  37944. var indices = new Array();
  37945. var positions = new Array();
  37946. var normals = new Array();
  37947. var uvs = new Array();
  37948. var radius = options.radius || 2;
  37949. var tube = options.tube || 0.5;
  37950. var radialSegments = options.radialSegments || 32;
  37951. var tubularSegments = options.tubularSegments || 32;
  37952. var p = options.p || 2;
  37953. var q = options.q || 3;
  37954. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37955. // Helper
  37956. var getPos = function (angle) {
  37957. var cu = Math.cos(angle);
  37958. var su = Math.sin(angle);
  37959. var quOverP = q / p * angle;
  37960. var cs = Math.cos(quOverP);
  37961. var tx = radius * (2 + cs) * 0.5 * cu;
  37962. var ty = radius * (2 + cs) * su * 0.5;
  37963. var tz = radius * Math.sin(quOverP) * 0.5;
  37964. return new BABYLON.Vector3(tx, ty, tz);
  37965. };
  37966. // Vertices
  37967. var i;
  37968. var j;
  37969. for (i = 0; i <= radialSegments; i++) {
  37970. var modI = i % radialSegments;
  37971. var u = modI / radialSegments * 2 * p * Math.PI;
  37972. var p1 = getPos(u);
  37973. var p2 = getPos(u + 0.01);
  37974. var tang = p2.subtract(p1);
  37975. var n = p2.add(p1);
  37976. var bitan = BABYLON.Vector3.Cross(tang, n);
  37977. n = BABYLON.Vector3.Cross(bitan, tang);
  37978. bitan.normalize();
  37979. n.normalize();
  37980. for (j = 0; j < tubularSegments; j++) {
  37981. var modJ = j % tubularSegments;
  37982. var v = modJ / tubularSegments * 2 * Math.PI;
  37983. var cx = -tube * Math.cos(v);
  37984. var cy = tube * Math.sin(v);
  37985. positions.push(p1.x + cx * n.x + cy * bitan.x);
  37986. positions.push(p1.y + cx * n.y + cy * bitan.y);
  37987. positions.push(p1.z + cx * n.z + cy * bitan.z);
  37988. uvs.push(i / radialSegments);
  37989. uvs.push(j / tubularSegments);
  37990. }
  37991. }
  37992. for (i = 0; i < radialSegments; i++) {
  37993. for (j = 0; j < tubularSegments; j++) {
  37994. var jNext = (j + 1) % tubularSegments;
  37995. var a = i * tubularSegments + j;
  37996. var b = (i + 1) * tubularSegments + j;
  37997. var c = (i + 1) * tubularSegments + jNext;
  37998. var d = i * tubularSegments + jNext;
  37999. indices.push(d);
  38000. indices.push(b);
  38001. indices.push(a);
  38002. indices.push(d);
  38003. indices.push(c);
  38004. indices.push(b);
  38005. }
  38006. }
  38007. // Normals
  38008. VertexData.ComputeNormals(positions, indices, normals);
  38009. // Sides
  38010. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38011. // Result
  38012. var vertexData = new VertexData();
  38013. vertexData.indices = indices;
  38014. vertexData.positions = positions;
  38015. vertexData.normals = normals;
  38016. vertexData.uvs = uvs;
  38017. return vertexData;
  38018. };
  38019. // Tools
  38020. /**
  38021. * Compute normals for given positions and indices
  38022. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38023. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38024. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38025. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38026. * * facetNormals : optional array of facet normals (vector3)
  38027. * * facetPositions : optional array of facet positions (vector3)
  38028. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38029. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38030. * * bInfo : optional bounding info, required for facetPartitioning computation
  38031. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38032. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38033. * * useRightHandedSystem: optional boolean to for right handed system computation
  38034. * * depthSort : optional boolean to enable the facet depth sort computation
  38035. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38036. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38037. */
  38038. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38039. // temporary scalar variables
  38040. var index = 0; // facet index
  38041. var p1p2x = 0.0; // p1p2 vector x coordinate
  38042. var p1p2y = 0.0; // p1p2 vector y coordinate
  38043. var p1p2z = 0.0; // p1p2 vector z coordinate
  38044. var p3p2x = 0.0; // p3p2 vector x coordinate
  38045. var p3p2y = 0.0; // p3p2 vector y coordinate
  38046. var p3p2z = 0.0; // p3p2 vector z coordinate
  38047. var faceNormalx = 0.0; // facet normal x coordinate
  38048. var faceNormaly = 0.0; // facet normal y coordinate
  38049. var faceNormalz = 0.0; // facet normal z coordinate
  38050. var length = 0.0; // facet normal length before normalization
  38051. var v1x = 0; // vector1 x index in the positions array
  38052. var v1y = 0; // vector1 y index in the positions array
  38053. var v1z = 0; // vector1 z index in the positions array
  38054. var v2x = 0; // vector2 x index in the positions array
  38055. var v2y = 0; // vector2 y index in the positions array
  38056. var v2z = 0; // vector2 z index in the positions array
  38057. var v3x = 0; // vector3 x index in the positions array
  38058. var v3y = 0; // vector3 y index in the positions array
  38059. var v3z = 0; // vector3 z index in the positions array
  38060. var computeFacetNormals = false;
  38061. var computeFacetPositions = false;
  38062. var computeFacetPartitioning = false;
  38063. var computeDepthSort = false;
  38064. var faceNormalSign = 1;
  38065. var ratio = 0;
  38066. var distanceTo = null;
  38067. if (options) {
  38068. computeFacetNormals = (options.facetNormals) ? true : false;
  38069. computeFacetPositions = (options.facetPositions) ? true : false;
  38070. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38071. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38072. ratio = options.ratio || 0;
  38073. computeDepthSort = (options.depthSort) ? true : false;
  38074. distanceTo = (options.distanceTo);
  38075. if (computeDepthSort) {
  38076. if (distanceTo === undefined) {
  38077. distanceTo = BABYLON.Vector3.Zero();
  38078. }
  38079. var depthSortedFacets = options.depthSortedFacets;
  38080. }
  38081. }
  38082. // facetPartitioning reinit if needed
  38083. var xSubRatio = 0;
  38084. var ySubRatio = 0;
  38085. var zSubRatio = 0;
  38086. var subSq = 0;
  38087. if (computeFacetPartitioning && options && options.bbSize) {
  38088. var ox = 0; // X partitioning index for facet position
  38089. var oy = 0; // Y partinioning index for facet position
  38090. var oz = 0; // Z partinioning index for facet position
  38091. var b1x = 0; // X partitioning index for facet v1 vertex
  38092. var b1y = 0; // Y partitioning index for facet v1 vertex
  38093. var b1z = 0; // z partitioning index for facet v1 vertex
  38094. var b2x = 0; // X partitioning index for facet v2 vertex
  38095. var b2y = 0; // Y partitioning index for facet v2 vertex
  38096. var b2z = 0; // Z partitioning index for facet v2 vertex
  38097. var b3x = 0; // X partitioning index for facet v3 vertex
  38098. var b3y = 0; // Y partitioning index for facet v3 vertex
  38099. var b3z = 0; // Z partitioning index for facet v3 vertex
  38100. var block_idx_o = 0; // facet barycenter block index
  38101. var block_idx_v1 = 0; // v1 vertex block index
  38102. var block_idx_v2 = 0; // v2 vertex block index
  38103. var block_idx_v3 = 0; // v3 vertex block index
  38104. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38105. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38106. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38107. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38108. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38109. subSq = options.subDiv.max * options.subDiv.max;
  38110. options.facetPartitioning.length = 0;
  38111. }
  38112. // reset the normals
  38113. for (index = 0; index < positions.length; index++) {
  38114. normals[index] = 0.0;
  38115. }
  38116. // Loop : 1 indice triplet = 1 facet
  38117. var nbFaces = (indices.length / 3) | 0;
  38118. for (index = 0; index < nbFaces; index++) {
  38119. // get the indexes of the coordinates of each vertex of the facet
  38120. v1x = indices[index * 3] * 3;
  38121. v1y = v1x + 1;
  38122. v1z = v1x + 2;
  38123. v2x = indices[index * 3 + 1] * 3;
  38124. v2y = v2x + 1;
  38125. v2z = v2x + 2;
  38126. v3x = indices[index * 3 + 2] * 3;
  38127. v3y = v3x + 1;
  38128. v3z = v3x + 2;
  38129. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38130. p1p2y = positions[v1y] - positions[v2y];
  38131. p1p2z = positions[v1z] - positions[v2z];
  38132. p3p2x = positions[v3x] - positions[v2x];
  38133. p3p2y = positions[v3y] - positions[v2y];
  38134. p3p2z = positions[v3z] - positions[v2z];
  38135. // compute the face normal with the cross product
  38136. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38137. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38138. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38139. // normalize this normal and store it in the array facetData
  38140. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38141. length = (length === 0) ? 1.0 : length;
  38142. faceNormalx /= length;
  38143. faceNormaly /= length;
  38144. faceNormalz /= length;
  38145. if (computeFacetNormals && options) {
  38146. options.facetNormals[index].x = faceNormalx;
  38147. options.facetNormals[index].y = faceNormaly;
  38148. options.facetNormals[index].z = faceNormalz;
  38149. }
  38150. if (computeFacetPositions && options) {
  38151. // compute and the facet barycenter coordinates in the array facetPositions
  38152. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38153. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38154. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38155. }
  38156. if (computeFacetPartitioning && options) {
  38157. // store the facet indexes in arrays in the main facetPartitioning array :
  38158. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38159. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38160. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38161. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38162. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38163. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38164. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38165. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38166. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38167. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38168. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38169. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38170. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38171. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38172. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38173. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38174. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38175. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38176. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38177. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38178. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38179. // push each facet index in each block containing the vertex
  38180. options.facetPartitioning[block_idx_v1].push(index);
  38181. if (block_idx_v2 != block_idx_v1) {
  38182. options.facetPartitioning[block_idx_v2].push(index);
  38183. }
  38184. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38185. options.facetPartitioning[block_idx_v3].push(index);
  38186. }
  38187. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38188. options.facetPartitioning[block_idx_o].push(index);
  38189. }
  38190. }
  38191. if (computeDepthSort && options && options.facetPositions) {
  38192. var dsf = depthSortedFacets[index];
  38193. dsf.ind = index * 3;
  38194. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38195. }
  38196. // compute the normals anyway
  38197. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38198. normals[v1y] += faceNormaly;
  38199. normals[v1z] += faceNormalz;
  38200. normals[v2x] += faceNormalx;
  38201. normals[v2y] += faceNormaly;
  38202. normals[v2z] += faceNormalz;
  38203. normals[v3x] += faceNormalx;
  38204. normals[v3y] += faceNormaly;
  38205. normals[v3z] += faceNormalz;
  38206. }
  38207. // last normalization of each normal
  38208. for (index = 0; index < normals.length / 3; index++) {
  38209. faceNormalx = normals[index * 3];
  38210. faceNormaly = normals[index * 3 + 1];
  38211. faceNormalz = normals[index * 3 + 2];
  38212. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38213. length = (length === 0) ? 1.0 : length;
  38214. faceNormalx /= length;
  38215. faceNormaly /= length;
  38216. faceNormalz /= length;
  38217. normals[index * 3] = faceNormalx;
  38218. normals[index * 3 + 1] = faceNormaly;
  38219. normals[index * 3 + 2] = faceNormalz;
  38220. }
  38221. };
  38222. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38223. var li = indices.length;
  38224. var ln = normals.length;
  38225. var i;
  38226. var n;
  38227. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38228. switch (sideOrientation) {
  38229. case BABYLON.Mesh.FRONTSIDE:
  38230. // nothing changed
  38231. break;
  38232. case BABYLON.Mesh.BACKSIDE:
  38233. var tmp;
  38234. // indices
  38235. for (i = 0; i < li; i += 3) {
  38236. tmp = indices[i];
  38237. indices[i] = indices[i + 2];
  38238. indices[i + 2] = tmp;
  38239. }
  38240. // normals
  38241. for (n = 0; n < ln; n++) {
  38242. normals[n] = -normals[n];
  38243. }
  38244. break;
  38245. case BABYLON.Mesh.DOUBLESIDE:
  38246. // positions
  38247. var lp = positions.length;
  38248. var l = lp / 3;
  38249. for (var p = 0; p < lp; p++) {
  38250. positions[lp + p] = positions[p];
  38251. }
  38252. // indices
  38253. for (i = 0; i < li; i += 3) {
  38254. indices[i + li] = indices[i + 2] + l;
  38255. indices[i + 1 + li] = indices[i + 1] + l;
  38256. indices[i + 2 + li] = indices[i] + l;
  38257. }
  38258. // normals
  38259. for (n = 0; n < ln; n++) {
  38260. normals[ln + n] = -normals[n];
  38261. }
  38262. // uvs
  38263. var lu = uvs.length;
  38264. var u = 0;
  38265. for (u = 0; u < lu; u++) {
  38266. uvs[u + lu] = uvs[u];
  38267. }
  38268. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38269. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38270. u = 0;
  38271. for (i = 0; i < lu / 2; i++) {
  38272. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38273. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38274. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38275. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38276. u += 2;
  38277. }
  38278. break;
  38279. }
  38280. };
  38281. /**
  38282. * Applies VertexData created from the imported parameters to the geometry
  38283. * @param parsedVertexData the parsed data from an imported file
  38284. * @param geometry the geometry to apply the VertexData to
  38285. */
  38286. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38287. var vertexData = new VertexData();
  38288. // positions
  38289. var positions = parsedVertexData.positions;
  38290. if (positions) {
  38291. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38292. }
  38293. // normals
  38294. var normals = parsedVertexData.normals;
  38295. if (normals) {
  38296. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38297. }
  38298. // tangents
  38299. var tangents = parsedVertexData.tangents;
  38300. if (tangents) {
  38301. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38302. }
  38303. // uvs
  38304. var uvs = parsedVertexData.uvs;
  38305. if (uvs) {
  38306. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38307. }
  38308. // uv2s
  38309. var uv2s = parsedVertexData.uv2s;
  38310. if (uv2s) {
  38311. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38312. }
  38313. // uv3s
  38314. var uv3s = parsedVertexData.uv3s;
  38315. if (uv3s) {
  38316. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38317. }
  38318. // uv4s
  38319. var uv4s = parsedVertexData.uv4s;
  38320. if (uv4s) {
  38321. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38322. }
  38323. // uv5s
  38324. var uv5s = parsedVertexData.uv5s;
  38325. if (uv5s) {
  38326. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38327. }
  38328. // uv6s
  38329. var uv6s = parsedVertexData.uv6s;
  38330. if (uv6s) {
  38331. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38332. }
  38333. // colors
  38334. var colors = parsedVertexData.colors;
  38335. if (colors) {
  38336. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38337. }
  38338. // matricesIndices
  38339. var matricesIndices = parsedVertexData.matricesIndices;
  38340. if (matricesIndices) {
  38341. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38342. }
  38343. // matricesWeights
  38344. var matricesWeights = parsedVertexData.matricesWeights;
  38345. if (matricesWeights) {
  38346. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38347. }
  38348. // indices
  38349. var indices = parsedVertexData.indices;
  38350. if (indices) {
  38351. vertexData.indices = indices;
  38352. }
  38353. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38354. };
  38355. return VertexData;
  38356. }());
  38357. BABYLON.VertexData = VertexData;
  38358. })(BABYLON || (BABYLON = {}));
  38359. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38360. var BABYLON;
  38361. (function (BABYLON) {
  38362. /**
  38363. * Class used to store geometry data (vertex buffers + index buffer)
  38364. */
  38365. var Geometry = /** @class */ (function () {
  38366. /**
  38367. * Creates a new geometry
  38368. * @param id defines the unique ID
  38369. * @param scene defines the hosting scene
  38370. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38371. * @param updatable defines if geometry must be updatable (false by default)
  38372. * @param mesh defines the mesh that will be associated with the geometry
  38373. */
  38374. function Geometry(id, scene, vertexData, updatable, mesh) {
  38375. if (updatable === void 0) { updatable = false; }
  38376. if (mesh === void 0) { mesh = null; }
  38377. /**
  38378. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38379. */
  38380. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38381. this._totalVertices = 0;
  38382. this._isDisposed = false;
  38383. this._indexBufferIsUpdatable = false;
  38384. this.id = id;
  38385. this._engine = scene.getEngine();
  38386. this._meshes = [];
  38387. this._scene = scene;
  38388. //Init vertex buffer cache
  38389. this._vertexBuffers = {};
  38390. this._indices = [];
  38391. this._updatable = updatable;
  38392. // vertexData
  38393. if (vertexData) {
  38394. this.setAllVerticesData(vertexData, updatable);
  38395. }
  38396. else {
  38397. this._totalVertices = 0;
  38398. this._indices = [];
  38399. }
  38400. if (this._engine.getCaps().vertexArrayObject) {
  38401. this._vertexArrayObjects = {};
  38402. }
  38403. // applyToMesh
  38404. if (mesh) {
  38405. if (mesh.getClassName() === "LinesMesh") {
  38406. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38407. this._updateExtend();
  38408. }
  38409. this.applyToMesh(mesh);
  38410. mesh.computeWorldMatrix(true);
  38411. }
  38412. }
  38413. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38414. /**
  38415. * 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
  38416. */
  38417. get: function () {
  38418. return this._boundingBias;
  38419. },
  38420. /**
  38421. * 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
  38422. */
  38423. set: function (value) {
  38424. if (this._boundingBias && this._boundingBias.equals(value)) {
  38425. return;
  38426. }
  38427. this._boundingBias = value.clone();
  38428. this._updateBoundingInfo(true, null);
  38429. },
  38430. enumerable: true,
  38431. configurable: true
  38432. });
  38433. /**
  38434. * Static function used to attach a new empty geometry to a mesh
  38435. * @param mesh defines the mesh to attach the geometry to
  38436. * @returns the new {BABYLON.Geometry}
  38437. */
  38438. Geometry.CreateGeometryForMesh = function (mesh) {
  38439. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38440. geometry.applyToMesh(mesh);
  38441. return geometry;
  38442. };
  38443. Object.defineProperty(Geometry.prototype, "extend", {
  38444. /**
  38445. * Gets the current extend of the geometry
  38446. */
  38447. get: function () {
  38448. return this._extend;
  38449. },
  38450. enumerable: true,
  38451. configurable: true
  38452. });
  38453. /**
  38454. * Gets the hosting scene
  38455. * @returns the hosting {BABYLON.Scene}
  38456. */
  38457. Geometry.prototype.getScene = function () {
  38458. return this._scene;
  38459. };
  38460. /**
  38461. * Gets the hosting engine
  38462. * @returns the hosting {BABYLON.Engine}
  38463. */
  38464. Geometry.prototype.getEngine = function () {
  38465. return this._engine;
  38466. };
  38467. /**
  38468. * Defines if the geometry is ready to use
  38469. * @returns true if the geometry is ready to be used
  38470. */
  38471. Geometry.prototype.isReady = function () {
  38472. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38473. };
  38474. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38475. /**
  38476. * Gets a value indicating that the geometry should not be serialized
  38477. */
  38478. get: function () {
  38479. for (var index = 0; index < this._meshes.length; index++) {
  38480. if (!this._meshes[index].doNotSerialize) {
  38481. return false;
  38482. }
  38483. }
  38484. return true;
  38485. },
  38486. enumerable: true,
  38487. configurable: true
  38488. });
  38489. /** @hidden */
  38490. Geometry.prototype._rebuild = function () {
  38491. if (this._vertexArrayObjects) {
  38492. this._vertexArrayObjects = {};
  38493. }
  38494. // Index buffer
  38495. if (this._meshes.length !== 0 && this._indices) {
  38496. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38497. }
  38498. // Vertex buffers
  38499. for (var key in this._vertexBuffers) {
  38500. var vertexBuffer = this._vertexBuffers[key];
  38501. vertexBuffer._rebuild();
  38502. }
  38503. };
  38504. /**
  38505. * Affects all gemetry data in one call
  38506. * @param vertexData defines the geometry data
  38507. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38508. */
  38509. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38510. vertexData.applyToGeometry(this, updatable);
  38511. this.notifyUpdate();
  38512. };
  38513. /**
  38514. * Set specific vertex data
  38515. * @param kind defines the data kind (Position, normal, etc...)
  38516. * @param data defines the vertex data to use
  38517. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38518. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38519. */
  38520. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38521. if (updatable === void 0) { updatable = false; }
  38522. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38523. this.setVerticesBuffer(buffer);
  38524. };
  38525. /**
  38526. * Removes a specific vertex data
  38527. * @param kind defines the data kind (Position, normal, etc...)
  38528. */
  38529. Geometry.prototype.removeVerticesData = function (kind) {
  38530. if (this._vertexBuffers[kind]) {
  38531. this._vertexBuffers[kind].dispose();
  38532. delete this._vertexBuffers[kind];
  38533. }
  38534. };
  38535. /**
  38536. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38537. * @param buffer defines the vertex buffer to use
  38538. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38539. */
  38540. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38541. if (totalVertices === void 0) { totalVertices = null; }
  38542. var kind = buffer.getKind();
  38543. if (this._vertexBuffers[kind]) {
  38544. this._vertexBuffers[kind].dispose();
  38545. }
  38546. this._vertexBuffers[kind] = buffer;
  38547. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38548. var data = buffer.getData();
  38549. if (totalVertices != null) {
  38550. this._totalVertices = totalVertices;
  38551. }
  38552. else {
  38553. if (data != null) {
  38554. this._totalVertices = data.length / (buffer.byteStride / 4);
  38555. }
  38556. }
  38557. this._updateExtend(data);
  38558. this._resetPointsArrayCache();
  38559. var meshes = this._meshes;
  38560. var numOfMeshes = meshes.length;
  38561. for (var index = 0; index < numOfMeshes; index++) {
  38562. var mesh = meshes[index];
  38563. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38564. mesh._createGlobalSubMesh(false);
  38565. mesh.computeWorldMatrix(true);
  38566. }
  38567. }
  38568. this.notifyUpdate(kind);
  38569. if (this._vertexArrayObjects) {
  38570. this._disposeVertexArrayObjects();
  38571. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38572. }
  38573. };
  38574. /**
  38575. * Update a specific vertex buffer
  38576. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38577. * It will do nothing if the buffer is not updatable
  38578. * @param kind defines the data kind (Position, normal, etc...)
  38579. * @param data defines the data to use
  38580. * @param offset defines the offset in the target buffer where to store the data
  38581. * @param useBytes set to true if the offset is in bytes
  38582. */
  38583. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38584. if (useBytes === void 0) { useBytes = false; }
  38585. var vertexBuffer = this.getVertexBuffer(kind);
  38586. if (!vertexBuffer) {
  38587. return;
  38588. }
  38589. vertexBuffer.updateDirectly(data, offset, useBytes);
  38590. this.notifyUpdate(kind);
  38591. };
  38592. /**
  38593. * Update a specific vertex buffer
  38594. * This function will create a new buffer if the current one is not updatable
  38595. * @param kind defines the data kind (Position, normal, etc...)
  38596. * @param data defines the data to use
  38597. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38598. */
  38599. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38600. if (updateExtends === void 0) { updateExtends = false; }
  38601. var vertexBuffer = this.getVertexBuffer(kind);
  38602. if (!vertexBuffer) {
  38603. return;
  38604. }
  38605. vertexBuffer.update(data);
  38606. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38607. this._updateBoundingInfo(updateExtends, data);
  38608. }
  38609. this.notifyUpdate(kind);
  38610. };
  38611. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38612. if (updateExtends) {
  38613. this._updateExtend(data);
  38614. }
  38615. var meshes = this._meshes;
  38616. var numOfMeshes = meshes.length;
  38617. this._resetPointsArrayCache();
  38618. for (var index = 0; index < numOfMeshes; index++) {
  38619. var mesh = meshes[index];
  38620. if (updateExtends) {
  38621. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38622. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38623. var subMesh = mesh.subMeshes[subIndex];
  38624. subMesh.refreshBoundingInfo();
  38625. }
  38626. }
  38627. }
  38628. };
  38629. /** @hidden */
  38630. Geometry.prototype._bind = function (effect, indexToBind) {
  38631. if (!effect) {
  38632. return;
  38633. }
  38634. if (indexToBind === undefined) {
  38635. indexToBind = this._indexBuffer;
  38636. }
  38637. var vbs = this.getVertexBuffers();
  38638. if (!vbs) {
  38639. return;
  38640. }
  38641. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38642. this._engine.bindBuffers(vbs, indexToBind, effect);
  38643. return;
  38644. }
  38645. // Using VAO
  38646. if (!this._vertexArrayObjects[effect.key]) {
  38647. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38648. }
  38649. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38650. };
  38651. /**
  38652. * Gets total number of vertices
  38653. * @returns the total number of vertices
  38654. */
  38655. Geometry.prototype.getTotalVertices = function () {
  38656. if (!this.isReady()) {
  38657. return 0;
  38658. }
  38659. return this._totalVertices;
  38660. };
  38661. /**
  38662. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38663. * @param kind defines the data kind (Position, normal, etc...)
  38664. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38665. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38666. * @returns a float array containing vertex data
  38667. */
  38668. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38669. var vertexBuffer = this.getVertexBuffer(kind);
  38670. if (!vertexBuffer) {
  38671. return null;
  38672. }
  38673. var data = vertexBuffer.getData();
  38674. if (!data) {
  38675. return null;
  38676. }
  38677. var defaultStride = BABYLON.VertexBuffer.DeduceStride(vertexBuffer.getKind());
  38678. var defaultByteStride = defaultStride * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38679. var count = this._totalVertices * defaultStride;
  38680. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== defaultByteStride) {
  38681. var copy_1 = new Array(count);
  38682. vertexBuffer.forEach(count, function (value, index) {
  38683. copy_1[index] = value;
  38684. });
  38685. return copy_1;
  38686. }
  38687. if (!(data instanceof Array || data instanceof Float32Array) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38688. if (data instanceof Array) {
  38689. var offset = vertexBuffer.byteOffset / 4;
  38690. return BABYLON.Tools.Slice(data, offset, offset + count);
  38691. }
  38692. else if (data instanceof ArrayBuffer) {
  38693. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38694. }
  38695. else {
  38696. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38697. }
  38698. }
  38699. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38700. return BABYLON.Tools.Slice(data);
  38701. }
  38702. return data;
  38703. };
  38704. /**
  38705. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38706. * @param kind defines the data kind (Position, normal, etc...)
  38707. * @returns true if the vertex buffer with the specified kind is updatable
  38708. */
  38709. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38710. var vb = this._vertexBuffers[kind];
  38711. if (!vb) {
  38712. return false;
  38713. }
  38714. return vb.isUpdatable();
  38715. };
  38716. /**
  38717. * Gets a specific vertex buffer
  38718. * @param kind defines the data kind (Position, normal, etc...)
  38719. * @returns a {BABYLON.VertexBuffer}
  38720. */
  38721. Geometry.prototype.getVertexBuffer = function (kind) {
  38722. if (!this.isReady()) {
  38723. return null;
  38724. }
  38725. return this._vertexBuffers[kind];
  38726. };
  38727. /**
  38728. * Returns all vertex buffers
  38729. * @return an object holding all vertex buffers indexed by kind
  38730. */
  38731. Geometry.prototype.getVertexBuffers = function () {
  38732. if (!this.isReady()) {
  38733. return null;
  38734. }
  38735. return this._vertexBuffers;
  38736. };
  38737. /**
  38738. * Gets a boolean indicating if specific vertex buffer is present
  38739. * @param kind defines the data kind (Position, normal, etc...)
  38740. * @returns true if data is present
  38741. */
  38742. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38743. if (!this._vertexBuffers) {
  38744. if (this._delayInfo) {
  38745. return this._delayInfo.indexOf(kind) !== -1;
  38746. }
  38747. return false;
  38748. }
  38749. return this._vertexBuffers[kind] !== undefined;
  38750. };
  38751. /**
  38752. * Gets a list of all attached data kinds (Position, normal, etc...)
  38753. * @returns a list of string containing all kinds
  38754. */
  38755. Geometry.prototype.getVerticesDataKinds = function () {
  38756. var result = [];
  38757. var kind;
  38758. if (!this._vertexBuffers && this._delayInfo) {
  38759. for (kind in this._delayInfo) {
  38760. result.push(kind);
  38761. }
  38762. }
  38763. else {
  38764. for (kind in this._vertexBuffers) {
  38765. result.push(kind);
  38766. }
  38767. }
  38768. return result;
  38769. };
  38770. /**
  38771. * Update index buffer
  38772. * @param indices defines the indices to store in the index buffer
  38773. * @param offset defines the offset in the target buffer where to store the data
  38774. */
  38775. Geometry.prototype.updateIndices = function (indices, offset) {
  38776. if (!this._indexBuffer) {
  38777. return;
  38778. }
  38779. if (!this._indexBufferIsUpdatable) {
  38780. this.setIndices(indices, null, true);
  38781. }
  38782. else {
  38783. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38784. }
  38785. };
  38786. /**
  38787. * Creates a new index buffer
  38788. * @param indices defines the indices to store in the index buffer
  38789. * @param totalVertices defines the total number of vertices (could be null)
  38790. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38791. */
  38792. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38793. if (totalVertices === void 0) { totalVertices = null; }
  38794. if (updatable === void 0) { updatable = false; }
  38795. if (this._indexBuffer) {
  38796. this._engine._releaseBuffer(this._indexBuffer);
  38797. }
  38798. this._disposeVertexArrayObjects();
  38799. this._indices = indices;
  38800. this._indexBufferIsUpdatable = updatable;
  38801. if (this._meshes.length !== 0 && this._indices) {
  38802. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38803. }
  38804. if (totalVertices != undefined) { // including null and undefined
  38805. this._totalVertices = totalVertices;
  38806. }
  38807. var meshes = this._meshes;
  38808. var numOfMeshes = meshes.length;
  38809. for (var index = 0; index < numOfMeshes; index++) {
  38810. meshes[index]._createGlobalSubMesh(true);
  38811. }
  38812. this.notifyUpdate();
  38813. };
  38814. /**
  38815. * Return the total number of indices
  38816. * @returns the total number of indices
  38817. */
  38818. Geometry.prototype.getTotalIndices = function () {
  38819. if (!this.isReady()) {
  38820. return 0;
  38821. }
  38822. return this._indices.length;
  38823. };
  38824. /**
  38825. * Gets the index buffer array
  38826. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38827. * @returns the index buffer array
  38828. */
  38829. Geometry.prototype.getIndices = function (copyWhenShared) {
  38830. if (!this.isReady()) {
  38831. return null;
  38832. }
  38833. var orig = this._indices;
  38834. if (!copyWhenShared || this._meshes.length === 1) {
  38835. return orig;
  38836. }
  38837. else {
  38838. var len = orig.length;
  38839. var copy = [];
  38840. for (var i = 0; i < len; i++) {
  38841. copy.push(orig[i]);
  38842. }
  38843. return copy;
  38844. }
  38845. };
  38846. /**
  38847. * Gets the index buffer
  38848. * @return the index buffer
  38849. */
  38850. Geometry.prototype.getIndexBuffer = function () {
  38851. if (!this.isReady()) {
  38852. return null;
  38853. }
  38854. return this._indexBuffer;
  38855. };
  38856. /** @hidden */
  38857. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  38858. if (effect === void 0) { effect = null; }
  38859. if (!effect || !this._vertexArrayObjects) {
  38860. return;
  38861. }
  38862. if (this._vertexArrayObjects[effect.key]) {
  38863. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  38864. delete this._vertexArrayObjects[effect.key];
  38865. }
  38866. };
  38867. /**
  38868. * Release the associated resources for a specific mesh
  38869. * @param mesh defines the source mesh
  38870. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  38871. */
  38872. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  38873. var meshes = this._meshes;
  38874. var index = meshes.indexOf(mesh);
  38875. if (index === -1) {
  38876. return;
  38877. }
  38878. meshes.splice(index, 1);
  38879. mesh._geometry = null;
  38880. if (meshes.length === 0 && shouldDispose) {
  38881. this.dispose();
  38882. }
  38883. };
  38884. /**
  38885. * Apply current geometry to a given mesh
  38886. * @param mesh defines the mesh to apply geometry to
  38887. */
  38888. Geometry.prototype.applyToMesh = function (mesh) {
  38889. if (mesh._geometry === this) {
  38890. return;
  38891. }
  38892. var previousGeometry = mesh._geometry;
  38893. if (previousGeometry) {
  38894. previousGeometry.releaseForMesh(mesh);
  38895. }
  38896. var meshes = this._meshes;
  38897. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  38898. mesh._geometry = this;
  38899. this._scene.pushGeometry(this);
  38900. meshes.push(mesh);
  38901. if (this.isReady()) {
  38902. this._applyToMesh(mesh);
  38903. }
  38904. else {
  38905. mesh._boundingInfo = this._boundingInfo;
  38906. }
  38907. };
  38908. Geometry.prototype._updateExtend = function (data) {
  38909. if (data === void 0) { data = null; }
  38910. if (!data) {
  38911. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38912. }
  38913. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  38914. };
  38915. Geometry.prototype._applyToMesh = function (mesh) {
  38916. var numOfMeshes = this._meshes.length;
  38917. // vertexBuffers
  38918. for (var kind in this._vertexBuffers) {
  38919. if (numOfMeshes === 1) {
  38920. this._vertexBuffers[kind].create();
  38921. }
  38922. var buffer = this._vertexBuffers[kind].getBuffer();
  38923. if (buffer)
  38924. buffer.references = numOfMeshes;
  38925. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38926. if (!this._extend) {
  38927. this._updateExtend();
  38928. }
  38929. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38930. mesh._createGlobalSubMesh(false);
  38931. //bounding info was just created again, world matrix should be applied again.
  38932. mesh._updateBoundingInfo();
  38933. }
  38934. }
  38935. // indexBuffer
  38936. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  38937. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38938. }
  38939. if (this._indexBuffer) {
  38940. this._indexBuffer.references = numOfMeshes;
  38941. }
  38942. };
  38943. Geometry.prototype.notifyUpdate = function (kind) {
  38944. if (this.onGeometryUpdated) {
  38945. this.onGeometryUpdated(this, kind);
  38946. }
  38947. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  38948. var mesh = _a[_i];
  38949. mesh._markSubMeshesAsAttributesDirty();
  38950. }
  38951. };
  38952. /**
  38953. * Load the geometry if it was flagged as delay loaded
  38954. * @param scene defines the hosting scene
  38955. * @param onLoaded defines a callback called when the geometry is loaded
  38956. */
  38957. Geometry.prototype.load = function (scene, onLoaded) {
  38958. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  38959. return;
  38960. }
  38961. if (this.isReady()) {
  38962. if (onLoaded) {
  38963. onLoaded();
  38964. }
  38965. return;
  38966. }
  38967. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  38968. this._queueLoad(scene, onLoaded);
  38969. };
  38970. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  38971. var _this = this;
  38972. if (!this.delayLoadingFile) {
  38973. return;
  38974. }
  38975. scene._addPendingData(this);
  38976. scene._loadFile(this.delayLoadingFile, function (data) {
  38977. if (!_this._delayLoadingFunction) {
  38978. return;
  38979. }
  38980. _this._delayLoadingFunction(JSON.parse(data), _this);
  38981. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38982. _this._delayInfo = [];
  38983. scene._removePendingData(_this);
  38984. var meshes = _this._meshes;
  38985. var numOfMeshes = meshes.length;
  38986. for (var index = 0; index < numOfMeshes; index++) {
  38987. _this._applyToMesh(meshes[index]);
  38988. }
  38989. if (onLoaded) {
  38990. onLoaded();
  38991. }
  38992. }, undefined, true);
  38993. };
  38994. /**
  38995. * Invert the geometry to move from a right handed system to a left handed one.
  38996. */
  38997. Geometry.prototype.toLeftHanded = function () {
  38998. // Flip faces
  38999. var tIndices = this.getIndices(false);
  39000. if (tIndices != null && tIndices.length > 0) {
  39001. for (var i = 0; i < tIndices.length; i += 3) {
  39002. var tTemp = tIndices[i + 0];
  39003. tIndices[i + 0] = tIndices[i + 2];
  39004. tIndices[i + 2] = tTemp;
  39005. }
  39006. this.setIndices(tIndices);
  39007. }
  39008. // Negate position.z
  39009. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39010. if (tPositions != null && tPositions.length > 0) {
  39011. for (var i = 0; i < tPositions.length; i += 3) {
  39012. tPositions[i + 2] = -tPositions[i + 2];
  39013. }
  39014. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39015. }
  39016. // Negate normal.z
  39017. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39018. if (tNormals != null && tNormals.length > 0) {
  39019. for (var i = 0; i < tNormals.length; i += 3) {
  39020. tNormals[i + 2] = -tNormals[i + 2];
  39021. }
  39022. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39023. }
  39024. };
  39025. // Cache
  39026. /** @hidden */
  39027. Geometry.prototype._resetPointsArrayCache = function () {
  39028. this._positions = null;
  39029. };
  39030. /** @hidden */
  39031. Geometry.prototype._generatePointsArray = function () {
  39032. if (this._positions)
  39033. return true;
  39034. this._positions = [];
  39035. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39036. if (!data) {
  39037. return false;
  39038. }
  39039. for (var index = 0; index < data.length; index += 3) {
  39040. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39041. }
  39042. return true;
  39043. };
  39044. /**
  39045. * Gets a value indicating if the geometry is disposed
  39046. * @returns true if the geometry was disposed
  39047. */
  39048. Geometry.prototype.isDisposed = function () {
  39049. return this._isDisposed;
  39050. };
  39051. Geometry.prototype._disposeVertexArrayObjects = function () {
  39052. if (this._vertexArrayObjects) {
  39053. for (var kind in this._vertexArrayObjects) {
  39054. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39055. }
  39056. this._vertexArrayObjects = {};
  39057. }
  39058. };
  39059. /**
  39060. * Free all associated resources
  39061. */
  39062. Geometry.prototype.dispose = function () {
  39063. var meshes = this._meshes;
  39064. var numOfMeshes = meshes.length;
  39065. var index;
  39066. for (index = 0; index < numOfMeshes; index++) {
  39067. this.releaseForMesh(meshes[index]);
  39068. }
  39069. this._meshes = [];
  39070. this._disposeVertexArrayObjects();
  39071. for (var kind in this._vertexBuffers) {
  39072. this._vertexBuffers[kind].dispose();
  39073. }
  39074. this._vertexBuffers = {};
  39075. this._totalVertices = 0;
  39076. if (this._indexBuffer) {
  39077. this._engine._releaseBuffer(this._indexBuffer);
  39078. }
  39079. this._indexBuffer = null;
  39080. this._indices = [];
  39081. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39082. this.delayLoadingFile = null;
  39083. this._delayLoadingFunction = null;
  39084. this._delayInfo = [];
  39085. this._boundingInfo = null;
  39086. this._scene.removeGeometry(this);
  39087. this._isDisposed = true;
  39088. };
  39089. /**
  39090. * Clone the current geometry into a new geometry
  39091. * @param id defines the unique ID of the new geometry
  39092. * @returns a new geometry object
  39093. */
  39094. Geometry.prototype.copy = function (id) {
  39095. var vertexData = new BABYLON.VertexData();
  39096. vertexData.indices = [];
  39097. var indices = this.getIndices();
  39098. if (indices) {
  39099. for (var index = 0; index < indices.length; index++) {
  39100. vertexData.indices.push(indices[index]);
  39101. }
  39102. }
  39103. var updatable = false;
  39104. var stopChecking = false;
  39105. var kind;
  39106. for (kind in this._vertexBuffers) {
  39107. // using slice() to make a copy of the array and not just reference it
  39108. var data = this.getVerticesData(kind);
  39109. if (data instanceof Float32Array) {
  39110. vertexData.set(new Float32Array(data), kind);
  39111. }
  39112. else {
  39113. vertexData.set(data.slice(0), kind);
  39114. }
  39115. if (!stopChecking) {
  39116. var vb = this.getVertexBuffer(kind);
  39117. if (vb) {
  39118. updatable = vb.isUpdatable();
  39119. stopChecking = !updatable;
  39120. }
  39121. }
  39122. }
  39123. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39124. geometry.delayLoadState = this.delayLoadState;
  39125. geometry.delayLoadingFile = this.delayLoadingFile;
  39126. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39127. for (kind in this._delayInfo) {
  39128. geometry._delayInfo = geometry._delayInfo || [];
  39129. geometry._delayInfo.push(kind);
  39130. }
  39131. // Bounding info
  39132. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39133. return geometry;
  39134. };
  39135. /**
  39136. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39137. * @return a JSON representation of the current geometry data (without the vertices data)
  39138. */
  39139. Geometry.prototype.serialize = function () {
  39140. var serializationObject = {};
  39141. serializationObject.id = this.id;
  39142. serializationObject.updatable = this._updatable;
  39143. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39144. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39145. }
  39146. return serializationObject;
  39147. };
  39148. Geometry.prototype.toNumberArray = function (origin) {
  39149. if (Array.isArray(origin)) {
  39150. return origin;
  39151. }
  39152. else {
  39153. return Array.prototype.slice.call(origin);
  39154. }
  39155. };
  39156. /**
  39157. * Serialize all vertices data into a JSON oject
  39158. * @returns a JSON representation of the current geometry data
  39159. */
  39160. Geometry.prototype.serializeVerticeData = function () {
  39161. var serializationObject = this.serialize();
  39162. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39163. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39164. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39165. serializationObject.positions._updatable = true;
  39166. }
  39167. }
  39168. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39169. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39170. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39171. serializationObject.normals._updatable = true;
  39172. }
  39173. }
  39174. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39175. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39176. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39177. serializationObject.tangets._updatable = true;
  39178. }
  39179. }
  39180. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39181. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39182. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39183. serializationObject.uvs._updatable = true;
  39184. }
  39185. }
  39186. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39187. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39188. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39189. serializationObject.uv2s._updatable = true;
  39190. }
  39191. }
  39192. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39193. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39194. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39195. serializationObject.uv3s._updatable = true;
  39196. }
  39197. }
  39198. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39199. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39200. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39201. serializationObject.uv4s._updatable = true;
  39202. }
  39203. }
  39204. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39205. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39206. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39207. serializationObject.uv5s._updatable = true;
  39208. }
  39209. }
  39210. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39211. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39212. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39213. serializationObject.uv6s._updatable = true;
  39214. }
  39215. }
  39216. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39217. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39218. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39219. serializationObject.colors._updatable = true;
  39220. }
  39221. }
  39222. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39223. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39224. serializationObject.matricesIndices._isExpanded = true;
  39225. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39226. serializationObject.matricesIndices._updatable = true;
  39227. }
  39228. }
  39229. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39230. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39231. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39232. serializationObject.matricesWeights._updatable = true;
  39233. }
  39234. }
  39235. serializationObject.indices = this.toNumberArray(this.getIndices());
  39236. return serializationObject;
  39237. };
  39238. // Statics
  39239. /**
  39240. * Extracts a clone of a mesh geometry
  39241. * @param mesh defines the source mesh
  39242. * @param id defines the unique ID of the new geometry object
  39243. * @returns the new geometry object
  39244. */
  39245. Geometry.ExtractFromMesh = function (mesh, id) {
  39246. var geometry = mesh._geometry;
  39247. if (!geometry) {
  39248. return null;
  39249. }
  39250. return geometry.copy(id);
  39251. };
  39252. /**
  39253. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39254. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39255. * Be aware Math.random() could cause collisions, but:
  39256. * "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"
  39257. * @returns a string containing a new GUID
  39258. */
  39259. Geometry.RandomId = function () {
  39260. return BABYLON.Tools.RandomId();
  39261. };
  39262. /** @hidden */
  39263. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39264. var scene = mesh.getScene();
  39265. // Geometry
  39266. var geometryId = parsedGeometry.geometryId;
  39267. if (geometryId) {
  39268. var geometry = scene.getGeometryByID(geometryId);
  39269. if (geometry) {
  39270. geometry.applyToMesh(mesh);
  39271. }
  39272. }
  39273. else if (parsedGeometry instanceof ArrayBuffer) {
  39274. var binaryInfo = mesh._binaryInfo;
  39275. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39276. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39277. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39278. }
  39279. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39280. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39281. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39282. }
  39283. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39284. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39285. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39286. }
  39287. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39288. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39289. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39290. }
  39291. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39292. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39293. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39294. }
  39295. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39296. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39297. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39298. }
  39299. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39300. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39301. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39302. }
  39303. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39304. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39305. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39306. }
  39307. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39308. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39309. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39310. }
  39311. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39312. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39313. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39314. }
  39315. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39316. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39317. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39318. }
  39319. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39320. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39321. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39322. }
  39323. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39324. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39325. mesh.setIndices(indicesData, null);
  39326. }
  39327. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39328. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39329. mesh.subMeshes = [];
  39330. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39331. var materialIndex = subMeshesData[(i * 5) + 0];
  39332. var verticesStart = subMeshesData[(i * 5) + 1];
  39333. var verticesCount = subMeshesData[(i * 5) + 2];
  39334. var indexStart = subMeshesData[(i * 5) + 3];
  39335. var indexCount = subMeshesData[(i * 5) + 4];
  39336. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39337. }
  39338. }
  39339. }
  39340. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39341. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39342. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39343. if (parsedGeometry.tangents) {
  39344. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39345. }
  39346. if (parsedGeometry.uvs) {
  39347. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39348. }
  39349. if (parsedGeometry.uvs2) {
  39350. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39351. }
  39352. if (parsedGeometry.uvs3) {
  39353. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39354. }
  39355. if (parsedGeometry.uvs4) {
  39356. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39357. }
  39358. if (parsedGeometry.uvs5) {
  39359. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39360. }
  39361. if (parsedGeometry.uvs6) {
  39362. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39363. }
  39364. if (parsedGeometry.colors) {
  39365. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39366. }
  39367. if (parsedGeometry.matricesIndices) {
  39368. if (!parsedGeometry.matricesIndices._isExpanded) {
  39369. var floatIndices = [];
  39370. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39371. var matricesIndex = parsedGeometry.matricesIndices[i];
  39372. floatIndices.push(matricesIndex & 0x000000FF);
  39373. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39374. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39375. floatIndices.push(matricesIndex >> 24);
  39376. }
  39377. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39378. }
  39379. else {
  39380. delete parsedGeometry.matricesIndices._isExpanded;
  39381. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39382. }
  39383. }
  39384. if (parsedGeometry.matricesIndicesExtra) {
  39385. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39386. var floatIndices = [];
  39387. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39388. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39389. floatIndices.push(matricesIndex & 0x000000FF);
  39390. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39391. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39392. floatIndices.push(matricesIndex >> 24);
  39393. }
  39394. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39395. }
  39396. else {
  39397. delete parsedGeometry.matricesIndices._isExpanded;
  39398. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39399. }
  39400. }
  39401. if (parsedGeometry.matricesWeights) {
  39402. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39403. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39404. }
  39405. if (parsedGeometry.matricesWeightsExtra) {
  39406. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39407. }
  39408. mesh.setIndices(parsedGeometry.indices, null);
  39409. }
  39410. // SubMeshes
  39411. if (parsedGeometry.subMeshes) {
  39412. mesh.subMeshes = [];
  39413. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39414. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39415. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39416. }
  39417. }
  39418. // Flat shading
  39419. if (mesh._shouldGenerateFlatShading) {
  39420. mesh.convertToFlatShadedMesh();
  39421. delete mesh._shouldGenerateFlatShading;
  39422. }
  39423. // Update
  39424. mesh.computeWorldMatrix(true);
  39425. // Octree
  39426. var sceneOctree = scene.selectionOctree;
  39427. if (sceneOctree !== undefined && sceneOctree !== null) {
  39428. sceneOctree.addMesh(mesh);
  39429. }
  39430. };
  39431. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39432. var epsilon = 1e-3;
  39433. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39434. return;
  39435. }
  39436. var noInfluenceBoneIndex = 0.0;
  39437. if (parsedGeometry.skeletonId > -1) {
  39438. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39439. if (!skeleton) {
  39440. return;
  39441. }
  39442. noInfluenceBoneIndex = skeleton.bones.length;
  39443. }
  39444. else {
  39445. return;
  39446. }
  39447. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39448. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39449. var matricesWeights = parsedGeometry.matricesWeights;
  39450. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39451. var influencers = parsedGeometry.numBoneInfluencer;
  39452. var size = matricesWeights.length;
  39453. for (var i = 0; i < size; i += 4) {
  39454. var weight = 0.0;
  39455. var firstZeroWeight = -1;
  39456. for (var j = 0; j < 4; j++) {
  39457. var w = matricesWeights[i + j];
  39458. weight += w;
  39459. if (w < epsilon && firstZeroWeight < 0) {
  39460. firstZeroWeight = j;
  39461. }
  39462. }
  39463. if (matricesWeightsExtra) {
  39464. for (var j = 0; j < 4; j++) {
  39465. var w = matricesWeightsExtra[i + j];
  39466. weight += w;
  39467. if (w < epsilon && firstZeroWeight < 0) {
  39468. firstZeroWeight = j + 4;
  39469. }
  39470. }
  39471. }
  39472. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39473. firstZeroWeight = influencers - 1;
  39474. }
  39475. if (weight > epsilon) {
  39476. var mweight = 1.0 / weight;
  39477. for (var j = 0; j < 4; j++) {
  39478. matricesWeights[i + j] *= mweight;
  39479. }
  39480. if (matricesWeightsExtra) {
  39481. for (var j = 0; j < 4; j++) {
  39482. matricesWeightsExtra[i + j] *= mweight;
  39483. }
  39484. }
  39485. }
  39486. else {
  39487. if (firstZeroWeight >= 4) {
  39488. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39489. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39490. }
  39491. else {
  39492. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39493. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39494. }
  39495. }
  39496. }
  39497. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39498. if (parsedGeometry.matricesWeightsExtra) {
  39499. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39500. }
  39501. };
  39502. /**
  39503. * Create a new geometry from persisted data (Using .babylon file format)
  39504. * @param parsedVertexData defines the persisted data
  39505. * @param scene defines the hosting scene
  39506. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39507. * @returns the new geometry object
  39508. */
  39509. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39510. if (scene.getGeometryByID(parsedVertexData.id)) {
  39511. return null; // null since geometry could be something else than a box...
  39512. }
  39513. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39514. if (BABYLON.Tags) {
  39515. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39516. }
  39517. if (parsedVertexData.delayLoadingFile) {
  39518. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39519. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39520. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39521. geometry._delayInfo = [];
  39522. if (parsedVertexData.hasUVs) {
  39523. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39524. }
  39525. if (parsedVertexData.hasUVs2) {
  39526. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39527. }
  39528. if (parsedVertexData.hasUVs3) {
  39529. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39530. }
  39531. if (parsedVertexData.hasUVs4) {
  39532. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39533. }
  39534. if (parsedVertexData.hasUVs5) {
  39535. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39536. }
  39537. if (parsedVertexData.hasUVs6) {
  39538. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39539. }
  39540. if (parsedVertexData.hasColors) {
  39541. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39542. }
  39543. if (parsedVertexData.hasMatricesIndices) {
  39544. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39545. }
  39546. if (parsedVertexData.hasMatricesWeights) {
  39547. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39548. }
  39549. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39550. }
  39551. else {
  39552. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39553. }
  39554. scene.pushGeometry(geometry, true);
  39555. return geometry;
  39556. };
  39557. return Geometry;
  39558. }());
  39559. BABYLON.Geometry = Geometry;
  39560. // Primitives
  39561. /// Abstract class
  39562. /**
  39563. * Abstract class used to provide common services for all typed geometries
  39564. * @hidden
  39565. */
  39566. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39567. __extends(_PrimitiveGeometry, _super);
  39568. /**
  39569. * Creates a new typed geometry
  39570. * @param id defines the unique ID of the geometry
  39571. * @param scene defines the hosting scene
  39572. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39573. * @param mesh defines the hosting mesh (can be null)
  39574. */
  39575. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39576. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39577. if (mesh === void 0) { mesh = null; }
  39578. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39579. _this._canBeRegenerated = _canBeRegenerated;
  39580. _this._beingRegenerated = true;
  39581. _this.regenerate();
  39582. _this._beingRegenerated = false;
  39583. return _this;
  39584. }
  39585. /**
  39586. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39587. * @returns true if the geometry can be regenerated
  39588. */
  39589. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39590. return this._canBeRegenerated;
  39591. };
  39592. /**
  39593. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39594. */
  39595. _PrimitiveGeometry.prototype.regenerate = function () {
  39596. if (!this._canBeRegenerated) {
  39597. return;
  39598. }
  39599. this._beingRegenerated = true;
  39600. this.setAllVerticesData(this._regenerateVertexData(), false);
  39601. this._beingRegenerated = false;
  39602. };
  39603. /**
  39604. * Clone the geometry
  39605. * @param id defines the unique ID of the new geometry
  39606. * @returns the new geometry
  39607. */
  39608. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39609. return _super.prototype.copy.call(this, id);
  39610. };
  39611. // overrides
  39612. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39613. if (!this._beingRegenerated) {
  39614. return;
  39615. }
  39616. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39617. };
  39618. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39619. if (!this._beingRegenerated) {
  39620. return;
  39621. }
  39622. _super.prototype.setVerticesData.call(this, kind, data, false);
  39623. };
  39624. // to override
  39625. /** @hidden */
  39626. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39627. throw new Error("Abstract method");
  39628. };
  39629. _PrimitiveGeometry.prototype.copy = function (id) {
  39630. throw new Error("Must be overriden in sub-classes.");
  39631. };
  39632. _PrimitiveGeometry.prototype.serialize = function () {
  39633. var serializationObject = _super.prototype.serialize.call(this);
  39634. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39635. return serializationObject;
  39636. };
  39637. return _PrimitiveGeometry;
  39638. }(Geometry));
  39639. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39640. /**
  39641. * Creates a ribbon geometry
  39642. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39643. */
  39644. var RibbonGeometry = /** @class */ (function (_super) {
  39645. __extends(RibbonGeometry, _super);
  39646. /**
  39647. * Creates a ribbon geometry
  39648. * @param id defines the unique ID of the geometry
  39649. * @param scene defines the hosting scene
  39650. * @param pathArray defines the array of paths to use
  39651. * @param closeArray defines if the last path and the first path must be joined
  39652. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39653. * @param offset defines the offset between points
  39654. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39655. * @param mesh defines the hosting mesh (can be null)
  39656. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39657. */
  39658. function RibbonGeometry(id, scene,
  39659. /**
  39660. * Defines the array of paths to use
  39661. */
  39662. pathArray,
  39663. /**
  39664. * Defines if the last and first points of each path in your pathArray must be joined
  39665. */
  39666. closeArray,
  39667. /**
  39668. * Defines if the last and first points of each path in your pathArray must be joined
  39669. */
  39670. closePath,
  39671. /**
  39672. * Defines the offset between points
  39673. */
  39674. offset, canBeRegenerated, mesh,
  39675. /**
  39676. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39677. */
  39678. side) {
  39679. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39680. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39681. _this.pathArray = pathArray;
  39682. _this.closeArray = closeArray;
  39683. _this.closePath = closePath;
  39684. _this.offset = offset;
  39685. _this.side = side;
  39686. return _this;
  39687. }
  39688. /** @hidden */
  39689. RibbonGeometry.prototype._regenerateVertexData = function () {
  39690. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39691. };
  39692. RibbonGeometry.prototype.copy = function (id) {
  39693. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39694. };
  39695. return RibbonGeometry;
  39696. }(_PrimitiveGeometry));
  39697. BABYLON.RibbonGeometry = RibbonGeometry;
  39698. /**
  39699. * Creates a box geometry
  39700. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39701. */
  39702. var BoxGeometry = /** @class */ (function (_super) {
  39703. __extends(BoxGeometry, _super);
  39704. /**
  39705. * Creates a box geometry
  39706. * @param id defines the unique ID of the geometry
  39707. * @param scene defines the hosting scene
  39708. * @param size defines the zise of the box (width, height and depth are the same)
  39709. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39710. * @param mesh defines the hosting mesh (can be null)
  39711. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39712. */
  39713. function BoxGeometry(id, scene,
  39714. /**
  39715. * Defines the zise of the box (width, height and depth are the same)
  39716. */
  39717. size, canBeRegenerated, mesh,
  39718. /**
  39719. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39720. */
  39721. side) {
  39722. if (mesh === void 0) { mesh = null; }
  39723. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39724. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39725. _this.size = size;
  39726. _this.side = side;
  39727. return _this;
  39728. }
  39729. BoxGeometry.prototype._regenerateVertexData = function () {
  39730. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39731. };
  39732. BoxGeometry.prototype.copy = function (id) {
  39733. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39734. };
  39735. BoxGeometry.prototype.serialize = function () {
  39736. var serializationObject = _super.prototype.serialize.call(this);
  39737. serializationObject.size = this.size;
  39738. return serializationObject;
  39739. };
  39740. BoxGeometry.Parse = function (parsedBox, scene) {
  39741. if (scene.getGeometryByID(parsedBox.id)) {
  39742. return null; // null since geometry could be something else than a box...
  39743. }
  39744. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39745. if (BABYLON.Tags) {
  39746. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39747. }
  39748. scene.pushGeometry(box, true);
  39749. return box;
  39750. };
  39751. return BoxGeometry;
  39752. }(_PrimitiveGeometry));
  39753. BABYLON.BoxGeometry = BoxGeometry;
  39754. /**
  39755. * Creates a sphere geometry
  39756. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39757. */
  39758. var SphereGeometry = /** @class */ (function (_super) {
  39759. __extends(SphereGeometry, _super);
  39760. /**
  39761. * Create a new sphere geometry
  39762. * @param id defines the unique ID of the geometry
  39763. * @param scene defines the hosting scene
  39764. * @param segments defines the number of segments to use to create the sphere
  39765. * @param diameter defines the diameter of the sphere
  39766. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39767. * @param mesh defines the hosting mesh (can be null)
  39768. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39769. */
  39770. function SphereGeometry(id, scene,
  39771. /**
  39772. * Defines the number of segments to use to create the sphere
  39773. */
  39774. segments,
  39775. /**
  39776. * Defines the diameter of the sphere
  39777. */
  39778. diameter, canBeRegenerated, mesh,
  39779. /**
  39780. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39781. */
  39782. side) {
  39783. if (mesh === void 0) { mesh = null; }
  39784. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39785. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39786. _this.segments = segments;
  39787. _this.diameter = diameter;
  39788. _this.side = side;
  39789. return _this;
  39790. }
  39791. SphereGeometry.prototype._regenerateVertexData = function () {
  39792. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39793. };
  39794. SphereGeometry.prototype.copy = function (id) {
  39795. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39796. };
  39797. SphereGeometry.prototype.serialize = function () {
  39798. var serializationObject = _super.prototype.serialize.call(this);
  39799. serializationObject.segments = this.segments;
  39800. serializationObject.diameter = this.diameter;
  39801. return serializationObject;
  39802. };
  39803. SphereGeometry.Parse = function (parsedSphere, scene) {
  39804. if (scene.getGeometryByID(parsedSphere.id)) {
  39805. return null; // null since geometry could be something else than a sphere...
  39806. }
  39807. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39808. if (BABYLON.Tags) {
  39809. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39810. }
  39811. scene.pushGeometry(sphere, true);
  39812. return sphere;
  39813. };
  39814. return SphereGeometry;
  39815. }(_PrimitiveGeometry));
  39816. BABYLON.SphereGeometry = SphereGeometry;
  39817. /**
  39818. * Creates a disc geometry
  39819. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39820. */
  39821. var DiscGeometry = /** @class */ (function (_super) {
  39822. __extends(DiscGeometry, _super);
  39823. /**
  39824. * Creates a new disc geometry
  39825. * @param id defines the unique ID of the geometry
  39826. * @param scene defines the hosting scene
  39827. * @param radius defines the radius of the disc
  39828. * @param tessellation defines the tesselation factor to apply to the disc
  39829. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39830. * @param mesh defines the hosting mesh (can be null)
  39831. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39832. */
  39833. function DiscGeometry(id, scene,
  39834. /**
  39835. * Defines the radius of the disc
  39836. */
  39837. radius,
  39838. /**
  39839. * Defines the tesselation factor to apply to the disc
  39840. */
  39841. tessellation, canBeRegenerated, mesh,
  39842. /**
  39843. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39844. */
  39845. side) {
  39846. if (mesh === void 0) { mesh = null; }
  39847. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39848. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39849. _this.radius = radius;
  39850. _this.tessellation = tessellation;
  39851. _this.side = side;
  39852. return _this;
  39853. }
  39854. DiscGeometry.prototype._regenerateVertexData = function () {
  39855. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  39856. };
  39857. DiscGeometry.prototype.copy = function (id) {
  39858. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  39859. };
  39860. return DiscGeometry;
  39861. }(_PrimitiveGeometry));
  39862. BABYLON.DiscGeometry = DiscGeometry;
  39863. /**
  39864. * Creates a new cylinder geometry
  39865. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  39866. */
  39867. var CylinderGeometry = /** @class */ (function (_super) {
  39868. __extends(CylinderGeometry, _super);
  39869. /**
  39870. * Creates a new cylinder geometry
  39871. * @param id defines the unique ID of the geometry
  39872. * @param scene defines the hosting scene
  39873. * @param height defines the height of the cylinder
  39874. * @param diameterTop defines the diameter of the cylinder's top cap
  39875. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  39876. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  39877. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  39878. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39879. * @param mesh defines the hosting mesh (can be null)
  39880. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39881. */
  39882. function CylinderGeometry(id, scene,
  39883. /**
  39884. * Defines the height of the cylinder
  39885. */
  39886. height,
  39887. /**
  39888. * Defines the diameter of the cylinder's top cap
  39889. */
  39890. diameterTop,
  39891. /**
  39892. * Defines the diameter of the cylinder's bottom cap
  39893. */
  39894. diameterBottom,
  39895. /**
  39896. * Defines the tessellation factor to apply to the cylinder
  39897. */
  39898. tessellation,
  39899. /**
  39900. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  39901. */
  39902. subdivisions, canBeRegenerated, mesh,
  39903. /**
  39904. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39905. */
  39906. side) {
  39907. if (subdivisions === void 0) { subdivisions = 1; }
  39908. if (mesh === void 0) { mesh = null; }
  39909. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39910. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39911. _this.height = height;
  39912. _this.diameterTop = diameterTop;
  39913. _this.diameterBottom = diameterBottom;
  39914. _this.tessellation = tessellation;
  39915. _this.subdivisions = subdivisions;
  39916. _this.side = side;
  39917. return _this;
  39918. }
  39919. CylinderGeometry.prototype._regenerateVertexData = function () {
  39920. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  39921. };
  39922. CylinderGeometry.prototype.copy = function (id) {
  39923. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  39924. };
  39925. CylinderGeometry.prototype.serialize = function () {
  39926. var serializationObject = _super.prototype.serialize.call(this);
  39927. serializationObject.height = this.height;
  39928. serializationObject.diameterTop = this.diameterTop;
  39929. serializationObject.diameterBottom = this.diameterBottom;
  39930. serializationObject.tessellation = this.tessellation;
  39931. return serializationObject;
  39932. };
  39933. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  39934. if (scene.getGeometryByID(parsedCylinder.id)) {
  39935. return null; // null since geometry could be something else than a cylinder...
  39936. }
  39937. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  39938. if (BABYLON.Tags) {
  39939. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  39940. }
  39941. scene.pushGeometry(cylinder, true);
  39942. return cylinder;
  39943. };
  39944. return CylinderGeometry;
  39945. }(_PrimitiveGeometry));
  39946. BABYLON.CylinderGeometry = CylinderGeometry;
  39947. /**
  39948. * Creates a new torus geometry
  39949. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  39950. */
  39951. var TorusGeometry = /** @class */ (function (_super) {
  39952. __extends(TorusGeometry, _super);
  39953. /**
  39954. * Creates a new torus geometry
  39955. * @param id defines the unique ID of the geometry
  39956. * @param scene defines the hosting scene
  39957. * @param diameter defines the diameter of the torus
  39958. * @param thickness defines the thickness of the torus (ie. internal diameter)
  39959. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  39960. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39961. * @param mesh defines the hosting mesh (can be null)
  39962. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39963. */
  39964. function TorusGeometry(id, scene,
  39965. /**
  39966. * Defines the diameter of the torus
  39967. */
  39968. diameter,
  39969. /**
  39970. * Defines the thickness of the torus (ie. internal diameter)
  39971. */
  39972. thickness,
  39973. /**
  39974. * Defines the tesselation factor to apply to the torus
  39975. */
  39976. tessellation, canBeRegenerated, mesh,
  39977. /**
  39978. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39979. */
  39980. side) {
  39981. if (mesh === void 0) { mesh = null; }
  39982. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39983. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39984. _this.diameter = diameter;
  39985. _this.thickness = thickness;
  39986. _this.tessellation = tessellation;
  39987. _this.side = side;
  39988. return _this;
  39989. }
  39990. TorusGeometry.prototype._regenerateVertexData = function () {
  39991. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  39992. };
  39993. TorusGeometry.prototype.copy = function (id) {
  39994. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  39995. };
  39996. TorusGeometry.prototype.serialize = function () {
  39997. var serializationObject = _super.prototype.serialize.call(this);
  39998. serializationObject.diameter = this.diameter;
  39999. serializationObject.thickness = this.thickness;
  40000. serializationObject.tessellation = this.tessellation;
  40001. return serializationObject;
  40002. };
  40003. TorusGeometry.Parse = function (parsedTorus, scene) {
  40004. if (scene.getGeometryByID(parsedTorus.id)) {
  40005. return null; // null since geometry could be something else than a torus...
  40006. }
  40007. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40008. if (BABYLON.Tags) {
  40009. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40010. }
  40011. scene.pushGeometry(torus, true);
  40012. return torus;
  40013. };
  40014. return TorusGeometry;
  40015. }(_PrimitiveGeometry));
  40016. BABYLON.TorusGeometry = TorusGeometry;
  40017. /**
  40018. * Creates a new ground geometry
  40019. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40020. */
  40021. var GroundGeometry = /** @class */ (function (_super) {
  40022. __extends(GroundGeometry, _super);
  40023. /**
  40024. * Creates a new ground geometry
  40025. * @param id defines the unique ID of the geometry
  40026. * @param scene defines the hosting scene
  40027. * @param width defines the width of the ground
  40028. * @param height defines the height of the ground
  40029. * @param subdivisions defines the subdivisions to apply to the ground
  40030. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40031. * @param mesh defines the hosting mesh (can be null)
  40032. */
  40033. function GroundGeometry(id, scene,
  40034. /**
  40035. * Defines the width of the ground
  40036. */
  40037. width,
  40038. /**
  40039. * Defines the height of the ground
  40040. */
  40041. height,
  40042. /**
  40043. * Defines the subdivisions to apply to the ground
  40044. */
  40045. subdivisions, canBeRegenerated, mesh) {
  40046. if (mesh === void 0) { mesh = null; }
  40047. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40048. _this.width = width;
  40049. _this.height = height;
  40050. _this.subdivisions = subdivisions;
  40051. return _this;
  40052. }
  40053. GroundGeometry.prototype._regenerateVertexData = function () {
  40054. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40055. };
  40056. GroundGeometry.prototype.copy = function (id) {
  40057. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40058. };
  40059. GroundGeometry.prototype.serialize = function () {
  40060. var serializationObject = _super.prototype.serialize.call(this);
  40061. serializationObject.width = this.width;
  40062. serializationObject.height = this.height;
  40063. serializationObject.subdivisions = this.subdivisions;
  40064. return serializationObject;
  40065. };
  40066. GroundGeometry.Parse = function (parsedGround, scene) {
  40067. if (scene.getGeometryByID(parsedGround.id)) {
  40068. return null; // null since geometry could be something else than a ground...
  40069. }
  40070. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40071. if (BABYLON.Tags) {
  40072. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40073. }
  40074. scene.pushGeometry(ground, true);
  40075. return ground;
  40076. };
  40077. return GroundGeometry;
  40078. }(_PrimitiveGeometry));
  40079. BABYLON.GroundGeometry = GroundGeometry;
  40080. /**
  40081. * Creates a tiled ground geometry
  40082. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40083. */
  40084. var TiledGroundGeometry = /** @class */ (function (_super) {
  40085. __extends(TiledGroundGeometry, _super);
  40086. /**
  40087. * Creates a tiled ground geometry
  40088. * @param id defines the unique ID of the geometry
  40089. * @param scene defines the hosting scene
  40090. * @param xmin defines the minimum value on X axis
  40091. * @param zmin defines the minimum value on Z axis
  40092. * @param xmax defines the maximum value on X axis
  40093. * @param zmax defines the maximum value on Z axis
  40094. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40095. * @param precision defines the precision to use when computing the tiles
  40096. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40097. * @param mesh defines the hosting mesh (can be null)
  40098. */
  40099. function TiledGroundGeometry(id, scene,
  40100. /**
  40101. * Defines the minimum value on X axis
  40102. */
  40103. xmin,
  40104. /**
  40105. * Defines the minimum value on Z axis
  40106. */
  40107. zmin,
  40108. /**
  40109. * Defines the maximum value on X axis
  40110. */
  40111. xmax,
  40112. /**
  40113. * Defines the maximum value on Z axis
  40114. */
  40115. zmax,
  40116. /**
  40117. * Defines the subdivisions to apply to the ground
  40118. */
  40119. subdivisions,
  40120. /**
  40121. * Defines the precision to use when computing the tiles
  40122. */
  40123. precision, canBeRegenerated, mesh) {
  40124. if (mesh === void 0) { mesh = null; }
  40125. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40126. _this.xmin = xmin;
  40127. _this.zmin = zmin;
  40128. _this.xmax = xmax;
  40129. _this.zmax = zmax;
  40130. _this.subdivisions = subdivisions;
  40131. _this.precision = precision;
  40132. return _this;
  40133. }
  40134. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40135. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40136. };
  40137. TiledGroundGeometry.prototype.copy = function (id) {
  40138. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40139. };
  40140. return TiledGroundGeometry;
  40141. }(_PrimitiveGeometry));
  40142. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40143. /**
  40144. * Creates a plane geometry
  40145. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40146. */
  40147. var PlaneGeometry = /** @class */ (function (_super) {
  40148. __extends(PlaneGeometry, _super);
  40149. /**
  40150. * Creates a plane geometry
  40151. * @param id defines the unique ID of the geometry
  40152. * @param scene defines the hosting scene
  40153. * @param size defines the size of the plane (width === height)
  40154. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40155. * @param mesh defines the hosting mesh (can be null)
  40156. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40157. */
  40158. function PlaneGeometry(id, scene,
  40159. /**
  40160. * Defines the size of the plane (width === height)
  40161. */
  40162. size, canBeRegenerated, mesh,
  40163. /**
  40164. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40165. */
  40166. side) {
  40167. if (mesh === void 0) { mesh = null; }
  40168. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40169. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40170. _this.size = size;
  40171. _this.side = side;
  40172. return _this;
  40173. }
  40174. PlaneGeometry.prototype._regenerateVertexData = function () {
  40175. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40176. };
  40177. PlaneGeometry.prototype.copy = function (id) {
  40178. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40179. };
  40180. PlaneGeometry.prototype.serialize = function () {
  40181. var serializationObject = _super.prototype.serialize.call(this);
  40182. serializationObject.size = this.size;
  40183. return serializationObject;
  40184. };
  40185. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40186. if (scene.getGeometryByID(parsedPlane.id)) {
  40187. return null; // null since geometry could be something else than a ground...
  40188. }
  40189. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40190. if (BABYLON.Tags) {
  40191. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40192. }
  40193. scene.pushGeometry(plane, true);
  40194. return plane;
  40195. };
  40196. return PlaneGeometry;
  40197. }(_PrimitiveGeometry));
  40198. BABYLON.PlaneGeometry = PlaneGeometry;
  40199. /**
  40200. * Creates a torus knot geometry
  40201. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40202. */
  40203. var TorusKnotGeometry = /** @class */ (function (_super) {
  40204. __extends(TorusKnotGeometry, _super);
  40205. /**
  40206. * Creates a torus knot geometry
  40207. * @param id defines the unique ID of the geometry
  40208. * @param scene defines the hosting scene
  40209. * @param radius defines the radius of the torus knot
  40210. * @param tube defines the thickness of the torus knot tube
  40211. * @param radialSegments defines the number of radial segments
  40212. * @param tubularSegments defines the number of tubular segments
  40213. * @param p defines the first number of windings
  40214. * @param q defines the second number of windings
  40215. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40216. * @param mesh defines the hosting mesh (can be null)
  40217. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40218. */
  40219. function TorusKnotGeometry(id, scene,
  40220. /**
  40221. * Defines the radius of the torus knot
  40222. */
  40223. radius,
  40224. /**
  40225. * Defines the thickness of the torus knot tube
  40226. */
  40227. tube,
  40228. /**
  40229. * Defines the number of radial segments
  40230. */
  40231. radialSegments,
  40232. /**
  40233. * Defines the number of tubular segments
  40234. */
  40235. tubularSegments,
  40236. /**
  40237. * Defines the first number of windings
  40238. */
  40239. p,
  40240. /**
  40241. * Defines the second number of windings
  40242. */
  40243. q, canBeRegenerated, mesh,
  40244. /**
  40245. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40246. */
  40247. side) {
  40248. if (mesh === void 0) { mesh = null; }
  40249. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40250. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40251. _this.radius = radius;
  40252. _this.tube = tube;
  40253. _this.radialSegments = radialSegments;
  40254. _this.tubularSegments = tubularSegments;
  40255. _this.p = p;
  40256. _this.q = q;
  40257. _this.side = side;
  40258. return _this;
  40259. }
  40260. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40261. 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 });
  40262. };
  40263. TorusKnotGeometry.prototype.copy = function (id) {
  40264. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40265. };
  40266. TorusKnotGeometry.prototype.serialize = function () {
  40267. var serializationObject = _super.prototype.serialize.call(this);
  40268. serializationObject.radius = this.radius;
  40269. serializationObject.tube = this.tube;
  40270. serializationObject.radialSegments = this.radialSegments;
  40271. serializationObject.tubularSegments = this.tubularSegments;
  40272. serializationObject.p = this.p;
  40273. serializationObject.q = this.q;
  40274. return serializationObject;
  40275. };
  40276. ;
  40277. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40278. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40279. return null; // null since geometry could be something else than a ground...
  40280. }
  40281. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40282. if (BABYLON.Tags) {
  40283. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40284. }
  40285. scene.pushGeometry(torusKnot, true);
  40286. return torusKnot;
  40287. };
  40288. return TorusKnotGeometry;
  40289. }(_PrimitiveGeometry));
  40290. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40291. //}
  40292. })(BABYLON || (BABYLON = {}));
  40293. //# sourceMappingURL=babylon.geometry.js.map
  40294. var BABYLON;
  40295. (function (BABYLON) {
  40296. /**
  40297. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40298. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40299. */
  40300. var PostProcessManager = /** @class */ (function () {
  40301. /**
  40302. * Creates a new instance PostProcess
  40303. * @param scene The scene that the post process is associated with.
  40304. */
  40305. function PostProcessManager(scene) {
  40306. this._vertexBuffers = {};
  40307. this._scene = scene;
  40308. }
  40309. PostProcessManager.prototype._prepareBuffers = function () {
  40310. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40311. return;
  40312. }
  40313. // VBO
  40314. var vertices = [];
  40315. vertices.push(1, 1);
  40316. vertices.push(-1, 1);
  40317. vertices.push(-1, -1);
  40318. vertices.push(1, -1);
  40319. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40320. this._buildIndexBuffer();
  40321. };
  40322. PostProcessManager.prototype._buildIndexBuffer = function () {
  40323. // Indices
  40324. var indices = [];
  40325. indices.push(0);
  40326. indices.push(1);
  40327. indices.push(2);
  40328. indices.push(0);
  40329. indices.push(2);
  40330. indices.push(3);
  40331. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40332. };
  40333. /**
  40334. * Rebuilds the vertex buffers of the manager.
  40335. */
  40336. PostProcessManager.prototype._rebuild = function () {
  40337. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40338. if (!vb) {
  40339. return;
  40340. }
  40341. vb._rebuild();
  40342. this._buildIndexBuffer();
  40343. };
  40344. // Methods
  40345. /**
  40346. * Prepares a frame to be run through a post process.
  40347. * @param sourceTexture The input texture to the post procesess. (default: null)
  40348. * @param postProcesses An array of post processes to be run. (default: null)
  40349. * @returns True if the post processes were able to be run.
  40350. */
  40351. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40352. if (sourceTexture === void 0) { sourceTexture = null; }
  40353. if (postProcesses === void 0) { postProcesses = null; }
  40354. var camera = this._scene.activeCamera;
  40355. if (!camera) {
  40356. return false;
  40357. }
  40358. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40359. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40360. return false;
  40361. }
  40362. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40363. return true;
  40364. };
  40365. /**
  40366. * Manually render a set of post processes to a texture.
  40367. * @param postProcesses An array of post processes to be run.
  40368. * @param targetTexture The target texture to render to.
  40369. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40370. */
  40371. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40372. if (targetTexture === void 0) { targetTexture = null; }
  40373. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40374. var engine = this._scene.getEngine();
  40375. for (var index = 0; index < postProcesses.length; index++) {
  40376. if (index < postProcesses.length - 1) {
  40377. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40378. }
  40379. else {
  40380. if (targetTexture) {
  40381. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40382. }
  40383. else {
  40384. engine.restoreDefaultFramebuffer();
  40385. }
  40386. }
  40387. var pp = postProcesses[index];
  40388. var effect = pp.apply();
  40389. if (effect) {
  40390. pp.onBeforeRenderObservable.notifyObservers(effect);
  40391. // VBOs
  40392. this._prepareBuffers();
  40393. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40394. // Draw order
  40395. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40396. pp.onAfterRenderObservable.notifyObservers(effect);
  40397. }
  40398. }
  40399. // Restore depth buffer
  40400. engine.setDepthBuffer(true);
  40401. engine.setDepthWrite(true);
  40402. };
  40403. /**
  40404. * Finalize the result of the output of the postprocesses.
  40405. * @param doNotPresent If true the result will not be displayed to the screen.
  40406. * @param targetTexture The target texture to render to.
  40407. * @param faceIndex The index of the face to bind the target texture to.
  40408. * @param postProcesses The array of post processes to render.
  40409. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40410. */
  40411. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40412. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40413. var camera = this._scene.activeCamera;
  40414. if (!camera) {
  40415. return;
  40416. }
  40417. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40418. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40419. return;
  40420. }
  40421. var engine = this._scene.getEngine();
  40422. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40423. var pp = postProcesses[index];
  40424. if (index < len - 1) {
  40425. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40426. }
  40427. else {
  40428. if (targetTexture) {
  40429. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40430. pp._outputTexture = targetTexture;
  40431. }
  40432. else {
  40433. engine.restoreDefaultFramebuffer();
  40434. pp._outputTexture = null;
  40435. }
  40436. }
  40437. if (doNotPresent) {
  40438. break;
  40439. }
  40440. var effect = pp.apply();
  40441. if (effect) {
  40442. pp.onBeforeRenderObservable.notifyObservers(effect);
  40443. // VBOs
  40444. this._prepareBuffers();
  40445. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40446. // Draw order
  40447. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40448. pp.onAfterRenderObservable.notifyObservers(effect);
  40449. }
  40450. }
  40451. // Restore states
  40452. engine.setDepthBuffer(true);
  40453. engine.setDepthWrite(true);
  40454. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40455. };
  40456. /**
  40457. * Disposes of the post process manager.
  40458. */
  40459. PostProcessManager.prototype.dispose = function () {
  40460. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40461. if (buffer) {
  40462. buffer.dispose();
  40463. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40464. }
  40465. if (this._indexBuffer) {
  40466. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40467. this._indexBuffer = null;
  40468. }
  40469. };
  40470. return PostProcessManager;
  40471. }());
  40472. BABYLON.PostProcessManager = PostProcessManager;
  40473. })(BABYLON || (BABYLON = {}));
  40474. //# sourceMappingURL=babylon.postProcessManager.js.map
  40475. var BABYLON;
  40476. (function (BABYLON) {
  40477. /**
  40478. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40479. */
  40480. var PerformanceMonitor = /** @class */ (function () {
  40481. /**
  40482. * constructor
  40483. * @param frameSampleSize The number of samples required to saturate the sliding window
  40484. */
  40485. function PerformanceMonitor(frameSampleSize) {
  40486. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40487. this._enabled = true;
  40488. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40489. }
  40490. /**
  40491. * Samples current frame
  40492. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40493. */
  40494. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40495. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40496. if (!this._enabled)
  40497. return;
  40498. if (this._lastFrameTimeMs != null) {
  40499. var dt = timeMs - this._lastFrameTimeMs;
  40500. this._rollingFrameTime.add(dt);
  40501. }
  40502. this._lastFrameTimeMs = timeMs;
  40503. };
  40504. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40505. /**
  40506. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40507. * @return Average frame time in milliseconds
  40508. */
  40509. get: function () {
  40510. return this._rollingFrameTime.average;
  40511. },
  40512. enumerable: true,
  40513. configurable: true
  40514. });
  40515. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40516. /**
  40517. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40518. * @return Frame time variance in milliseconds squared
  40519. */
  40520. get: function () {
  40521. return this._rollingFrameTime.variance;
  40522. },
  40523. enumerable: true,
  40524. configurable: true
  40525. });
  40526. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40527. /**
  40528. * Returns the frame time of the most recent frame
  40529. * @return Frame time in milliseconds
  40530. */
  40531. get: function () {
  40532. return this._rollingFrameTime.history(0);
  40533. },
  40534. enumerable: true,
  40535. configurable: true
  40536. });
  40537. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40538. /**
  40539. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40540. * @return Framerate in frames per second
  40541. */
  40542. get: function () {
  40543. return 1000.0 / this._rollingFrameTime.average;
  40544. },
  40545. enumerable: true,
  40546. configurable: true
  40547. });
  40548. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40549. /**
  40550. * Returns the average framerate in frames per second using the most recent frame time
  40551. * @return Framerate in frames per second
  40552. */
  40553. get: function () {
  40554. var history = this._rollingFrameTime.history(0);
  40555. if (history === 0) {
  40556. return 0;
  40557. }
  40558. return 1000.0 / history;
  40559. },
  40560. enumerable: true,
  40561. configurable: true
  40562. });
  40563. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40564. /**
  40565. * Returns true if enough samples have been taken to completely fill the sliding window
  40566. * @return true if saturated
  40567. */
  40568. get: function () {
  40569. return this._rollingFrameTime.isSaturated();
  40570. },
  40571. enumerable: true,
  40572. configurable: true
  40573. });
  40574. /**
  40575. * Enables contributions to the sliding window sample set
  40576. */
  40577. PerformanceMonitor.prototype.enable = function () {
  40578. this._enabled = true;
  40579. };
  40580. /**
  40581. * Disables contributions to the sliding window sample set
  40582. * Samples will not be interpolated over the disabled period
  40583. */
  40584. PerformanceMonitor.prototype.disable = function () {
  40585. this._enabled = false;
  40586. //clear last sample to avoid interpolating over the disabled period when next enabled
  40587. this._lastFrameTimeMs = null;
  40588. };
  40589. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40590. /**
  40591. * Returns true if sampling is enabled
  40592. * @return true if enabled
  40593. */
  40594. get: function () {
  40595. return this._enabled;
  40596. },
  40597. enumerable: true,
  40598. configurable: true
  40599. });
  40600. /**
  40601. * Resets performance monitor
  40602. */
  40603. PerformanceMonitor.prototype.reset = function () {
  40604. //clear last sample to avoid interpolating over the disabled period when next enabled
  40605. this._lastFrameTimeMs = null;
  40606. //wipe record
  40607. this._rollingFrameTime.reset();
  40608. };
  40609. return PerformanceMonitor;
  40610. }());
  40611. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40612. /**
  40613. * RollingAverage
  40614. *
  40615. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40616. */
  40617. var RollingAverage = /** @class */ (function () {
  40618. /**
  40619. * constructor
  40620. * @param length The number of samples required to saturate the sliding window
  40621. */
  40622. function RollingAverage(length) {
  40623. this._samples = new Array(length);
  40624. this.reset();
  40625. }
  40626. /**
  40627. * Adds a sample to the sample set
  40628. * @param v The sample value
  40629. */
  40630. RollingAverage.prototype.add = function (v) {
  40631. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40632. var delta;
  40633. //we need to check if we've already wrapped round
  40634. if (this.isSaturated()) {
  40635. //remove bottom of stack from mean
  40636. var bottomValue = this._samples[this._pos];
  40637. delta = bottomValue - this.average;
  40638. this.average -= delta / (this._sampleCount - 1);
  40639. this._m2 -= delta * (bottomValue - this.average);
  40640. }
  40641. else {
  40642. this._sampleCount++;
  40643. }
  40644. //add new value to mean
  40645. delta = v - this.average;
  40646. this.average += delta / (this._sampleCount);
  40647. this._m2 += delta * (v - this.average);
  40648. //set the new variance
  40649. this.variance = this._m2 / (this._sampleCount - 1);
  40650. this._samples[this._pos] = v;
  40651. this._pos++;
  40652. this._pos %= this._samples.length; //positive wrap around
  40653. };
  40654. /**
  40655. * Returns previously added values or null if outside of history or outside the sliding window domain
  40656. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40657. * @return Value previously recorded with add() or null if outside of range
  40658. */
  40659. RollingAverage.prototype.history = function (i) {
  40660. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40661. return 0;
  40662. }
  40663. var i0 = this._wrapPosition(this._pos - 1.0);
  40664. return this._samples[this._wrapPosition(i0 - i)];
  40665. };
  40666. /**
  40667. * Returns true if enough samples have been taken to completely fill the sliding window
  40668. * @return true if sample-set saturated
  40669. */
  40670. RollingAverage.prototype.isSaturated = function () {
  40671. return this._sampleCount >= this._samples.length;
  40672. };
  40673. /**
  40674. * Resets the rolling average (equivalent to 0 samples taken so far)
  40675. */
  40676. RollingAverage.prototype.reset = function () {
  40677. this.average = 0;
  40678. this.variance = 0;
  40679. this._sampleCount = 0;
  40680. this._pos = 0;
  40681. this._m2 = 0;
  40682. };
  40683. /**
  40684. * Wraps a value around the sample range boundaries
  40685. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40686. * @return Wrapped position in sample range
  40687. */
  40688. RollingAverage.prototype._wrapPosition = function (i) {
  40689. var max = this._samples.length;
  40690. return ((i % max) + max) % max;
  40691. };
  40692. return RollingAverage;
  40693. }());
  40694. BABYLON.RollingAverage = RollingAverage;
  40695. })(BABYLON || (BABYLON = {}));
  40696. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40697. var BABYLON;
  40698. (function (BABYLON) {
  40699. /**
  40700. * This groups together the common properties used for image processing either in direct forward pass
  40701. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40702. * or not.
  40703. */
  40704. var ImageProcessingConfiguration = /** @class */ (function () {
  40705. function ImageProcessingConfiguration() {
  40706. /**
  40707. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40708. */
  40709. this.colorCurves = new BABYLON.ColorCurves();
  40710. this._colorCurvesEnabled = false;
  40711. this._colorGradingEnabled = false;
  40712. this._colorGradingWithGreenDepth = true;
  40713. this._colorGradingBGR = true;
  40714. this._exposure = 1.0;
  40715. this._toneMappingEnabled = false;
  40716. this._contrast = 1.0;
  40717. /**
  40718. * Vignette stretch size.
  40719. */
  40720. this.vignetteStretch = 0;
  40721. /**
  40722. * Vignette centre X Offset.
  40723. */
  40724. this.vignetteCentreX = 0;
  40725. /**
  40726. * Vignette centre Y Offset.
  40727. */
  40728. this.vignetteCentreY = 0;
  40729. /**
  40730. * Vignette weight or intensity of the vignette effect.
  40731. */
  40732. this.vignetteWeight = 1.5;
  40733. /**
  40734. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40735. * if vignetteEnabled is set to true.
  40736. */
  40737. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40738. /**
  40739. * Camera field of view used by the Vignette effect.
  40740. */
  40741. this.vignetteCameraFov = 0.5;
  40742. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40743. this._vignetteEnabled = false;
  40744. this._applyByPostProcess = false;
  40745. this._isEnabled = true;
  40746. /**
  40747. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40748. */
  40749. this.onUpdateParameters = new BABYLON.Observable();
  40750. }
  40751. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40752. /**
  40753. * Gets wether the color curves effect is enabled.
  40754. */
  40755. get: function () {
  40756. return this._colorCurvesEnabled;
  40757. },
  40758. /**
  40759. * Sets wether the color curves effect is enabled.
  40760. */
  40761. set: function (value) {
  40762. if (this._colorCurvesEnabled === value) {
  40763. return;
  40764. }
  40765. this._colorCurvesEnabled = value;
  40766. this._updateParameters();
  40767. },
  40768. enumerable: true,
  40769. configurable: true
  40770. });
  40771. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40772. /**
  40773. * Gets wether the color grading effect is enabled.
  40774. */
  40775. get: function () {
  40776. return this._colorGradingEnabled;
  40777. },
  40778. /**
  40779. * Sets wether the color grading effect is enabled.
  40780. */
  40781. set: function (value) {
  40782. if (this._colorGradingEnabled === value) {
  40783. return;
  40784. }
  40785. this._colorGradingEnabled = value;
  40786. this._updateParameters();
  40787. },
  40788. enumerable: true,
  40789. configurable: true
  40790. });
  40791. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40792. /**
  40793. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40794. */
  40795. get: function () {
  40796. return this._colorGradingWithGreenDepth;
  40797. },
  40798. /**
  40799. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40800. */
  40801. set: function (value) {
  40802. if (this._colorGradingWithGreenDepth === value) {
  40803. return;
  40804. }
  40805. this._colorGradingWithGreenDepth = value;
  40806. this._updateParameters();
  40807. },
  40808. enumerable: true,
  40809. configurable: true
  40810. });
  40811. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40812. /**
  40813. * Gets wether the color grading texture contains BGR values.
  40814. */
  40815. get: function () {
  40816. return this._colorGradingBGR;
  40817. },
  40818. /**
  40819. * Sets wether the color grading texture contains BGR values.
  40820. */
  40821. set: function (value) {
  40822. if (this._colorGradingBGR === value) {
  40823. return;
  40824. }
  40825. this._colorGradingBGR = value;
  40826. this._updateParameters();
  40827. },
  40828. enumerable: true,
  40829. configurable: true
  40830. });
  40831. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40832. /**
  40833. * Gets the Exposure used in the effect.
  40834. */
  40835. get: function () {
  40836. return this._exposure;
  40837. },
  40838. /**
  40839. * Sets the Exposure used in the effect.
  40840. */
  40841. set: function (value) {
  40842. if (this._exposure === value) {
  40843. return;
  40844. }
  40845. this._exposure = value;
  40846. this._updateParameters();
  40847. },
  40848. enumerable: true,
  40849. configurable: true
  40850. });
  40851. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40852. /**
  40853. * Gets wether the tone mapping effect is enabled.
  40854. */
  40855. get: function () {
  40856. return this._toneMappingEnabled;
  40857. },
  40858. /**
  40859. * Sets wether the tone mapping effect is enabled.
  40860. */
  40861. set: function (value) {
  40862. if (this._toneMappingEnabled === value) {
  40863. return;
  40864. }
  40865. this._toneMappingEnabled = value;
  40866. this._updateParameters();
  40867. },
  40868. enumerable: true,
  40869. configurable: true
  40870. });
  40871. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  40872. /**
  40873. * Gets the contrast used in the effect.
  40874. */
  40875. get: function () {
  40876. return this._contrast;
  40877. },
  40878. /**
  40879. * Sets the contrast used in the effect.
  40880. */
  40881. set: function (value) {
  40882. if (this._contrast === value) {
  40883. return;
  40884. }
  40885. this._contrast = value;
  40886. this._updateParameters();
  40887. },
  40888. enumerable: true,
  40889. configurable: true
  40890. });
  40891. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  40892. /**
  40893. * Gets the vignette blend mode allowing different kind of effect.
  40894. */
  40895. get: function () {
  40896. return this._vignetteBlendMode;
  40897. },
  40898. /**
  40899. * Sets the vignette blend mode allowing different kind of effect.
  40900. */
  40901. set: function (value) {
  40902. if (this._vignetteBlendMode === value) {
  40903. return;
  40904. }
  40905. this._vignetteBlendMode = value;
  40906. this._updateParameters();
  40907. },
  40908. enumerable: true,
  40909. configurable: true
  40910. });
  40911. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  40912. /**
  40913. * Gets wether the vignette effect is enabled.
  40914. */
  40915. get: function () {
  40916. return this._vignetteEnabled;
  40917. },
  40918. /**
  40919. * Sets wether the vignette effect is enabled.
  40920. */
  40921. set: function (value) {
  40922. if (this._vignetteEnabled === value) {
  40923. return;
  40924. }
  40925. this._vignetteEnabled = value;
  40926. this._updateParameters();
  40927. },
  40928. enumerable: true,
  40929. configurable: true
  40930. });
  40931. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  40932. /**
  40933. * Gets wether the image processing is applied through a post process or not.
  40934. */
  40935. get: function () {
  40936. return this._applyByPostProcess;
  40937. },
  40938. /**
  40939. * Sets wether the image processing is applied through a post process or not.
  40940. */
  40941. set: function (value) {
  40942. if (this._applyByPostProcess === value) {
  40943. return;
  40944. }
  40945. this._applyByPostProcess = value;
  40946. this._updateParameters();
  40947. },
  40948. enumerable: true,
  40949. configurable: true
  40950. });
  40951. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  40952. /**
  40953. * Gets wether the image processing is enabled or not.
  40954. */
  40955. get: function () {
  40956. return this._isEnabled;
  40957. },
  40958. /**
  40959. * Sets wether the image processing is enabled or not.
  40960. */
  40961. set: function (value) {
  40962. if (this._isEnabled === value) {
  40963. return;
  40964. }
  40965. this._isEnabled = value;
  40966. this._updateParameters();
  40967. },
  40968. enumerable: true,
  40969. configurable: true
  40970. });
  40971. /**
  40972. * Method called each time the image processing information changes requires to recompile the effect.
  40973. */
  40974. ImageProcessingConfiguration.prototype._updateParameters = function () {
  40975. this.onUpdateParameters.notifyObservers(this);
  40976. };
  40977. ImageProcessingConfiguration.prototype.getClassName = function () {
  40978. return "ImageProcessingConfiguration";
  40979. };
  40980. /**
  40981. * Prepare the list of uniforms associated with the Image Processing effects.
  40982. * @param uniformsList The list of uniforms used in the effect
  40983. * @param defines the list of defines currently in use
  40984. */
  40985. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  40986. if (defines.EXPOSURE) {
  40987. uniforms.push("exposureLinear");
  40988. }
  40989. if (defines.CONTRAST) {
  40990. uniforms.push("contrast");
  40991. }
  40992. if (defines.COLORGRADING) {
  40993. uniforms.push("colorTransformSettings");
  40994. }
  40995. if (defines.VIGNETTE) {
  40996. uniforms.push("vInverseScreenSize");
  40997. uniforms.push("vignetteSettings1");
  40998. uniforms.push("vignetteSettings2");
  40999. }
  41000. if (defines.COLORCURVES) {
  41001. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41002. }
  41003. };
  41004. /**
  41005. * Prepare the list of samplers associated with the Image Processing effects.
  41006. * @param uniformsList The list of uniforms used in the effect
  41007. * @param defines the list of defines currently in use
  41008. */
  41009. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41010. if (defines.COLORGRADING) {
  41011. samplersList.push("txColorTransform");
  41012. }
  41013. };
  41014. /**
  41015. * Prepare the list of defines associated to the shader.
  41016. * @param defines the list of defines to complete
  41017. */
  41018. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41019. if (forPostProcess === void 0) { forPostProcess = false; }
  41020. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41021. defines.VIGNETTE = false;
  41022. defines.TONEMAPPING = false;
  41023. defines.CONTRAST = false;
  41024. defines.EXPOSURE = false;
  41025. defines.COLORCURVES = false;
  41026. defines.COLORGRADING = false;
  41027. defines.COLORGRADING3D = false;
  41028. defines.IMAGEPROCESSING = false;
  41029. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41030. return;
  41031. }
  41032. defines.VIGNETTE = this.vignetteEnabled;
  41033. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41034. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41035. defines.TONEMAPPING = this.toneMappingEnabled;
  41036. defines.CONTRAST = (this.contrast !== 1.0);
  41037. defines.EXPOSURE = (this.exposure !== 1.0);
  41038. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41039. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41040. if (defines.COLORGRADING) {
  41041. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41042. }
  41043. else {
  41044. defines.COLORGRADING3D = false;
  41045. }
  41046. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41047. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41048. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41049. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41050. };
  41051. /**
  41052. * Returns true if all the image processing information are ready.
  41053. */
  41054. ImageProcessingConfiguration.prototype.isReady = function () {
  41055. // Color Grading texure can not be none blocking.
  41056. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41057. };
  41058. /**
  41059. * Binds the image processing to the shader.
  41060. * @param effect The effect to bind to
  41061. */
  41062. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41063. if (aspectRatio === void 0) { aspectRatio = 1; }
  41064. // Color Curves
  41065. if (this._colorCurvesEnabled && this.colorCurves) {
  41066. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41067. }
  41068. // Vignette
  41069. if (this._vignetteEnabled) {
  41070. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41071. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41072. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41073. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41074. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41075. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41076. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41077. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41078. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41079. var vignettePower = -2.0 * this.vignetteWeight;
  41080. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41081. }
  41082. // Exposure
  41083. effect.setFloat("exposureLinear", this.exposure);
  41084. // Contrast
  41085. effect.setFloat("contrast", this.contrast);
  41086. // Color transform settings
  41087. if (this.colorGradingTexture) {
  41088. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41089. var textureSize = this.colorGradingTexture.getSize().height;
  41090. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41091. 0.5 / textureSize, // textureOffset
  41092. textureSize, // textureSize
  41093. this.colorGradingTexture.level // weight
  41094. );
  41095. }
  41096. };
  41097. /**
  41098. * Clones the current image processing instance.
  41099. * @return The cloned image processing
  41100. */
  41101. ImageProcessingConfiguration.prototype.clone = function () {
  41102. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41103. };
  41104. /**
  41105. * Serializes the current image processing instance to a json representation.
  41106. * @return a JSON representation
  41107. */
  41108. ImageProcessingConfiguration.prototype.serialize = function () {
  41109. return BABYLON.SerializationHelper.Serialize(this);
  41110. };
  41111. /**
  41112. * Parses the image processing from a json representation.
  41113. * @param source the JSON source to parse
  41114. * @return The parsed image processing
  41115. */
  41116. ImageProcessingConfiguration.Parse = function (source) {
  41117. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41118. };
  41119. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41120. /**
  41121. * Used to apply the vignette as a mix with the pixel color.
  41122. */
  41123. get: function () {
  41124. return this._VIGNETTEMODE_MULTIPLY;
  41125. },
  41126. enumerable: true,
  41127. configurable: true
  41128. });
  41129. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41130. /**
  41131. * Used to apply the vignette as a replacement of the pixel color.
  41132. */
  41133. get: function () {
  41134. return this._VIGNETTEMODE_OPAQUE;
  41135. },
  41136. enumerable: true,
  41137. configurable: true
  41138. });
  41139. // Static constants associated to the image processing.
  41140. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41141. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41142. __decorate([
  41143. BABYLON.serializeAsColorCurves()
  41144. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41145. __decorate([
  41146. BABYLON.serialize()
  41147. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41148. __decorate([
  41149. BABYLON.serializeAsTexture()
  41150. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41151. __decorate([
  41152. BABYLON.serialize()
  41153. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41154. __decorate([
  41155. BABYLON.serialize()
  41156. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41157. __decorate([
  41158. BABYLON.serialize()
  41159. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41160. __decorate([
  41161. BABYLON.serialize()
  41162. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41163. __decorate([
  41164. BABYLON.serialize()
  41165. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41166. __decorate([
  41167. BABYLON.serialize()
  41168. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41169. __decorate([
  41170. BABYLON.serialize()
  41171. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41172. __decorate([
  41173. BABYLON.serialize()
  41174. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41175. __decorate([
  41176. BABYLON.serialize()
  41177. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41178. __decorate([
  41179. BABYLON.serialize()
  41180. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41181. __decorate([
  41182. BABYLON.serializeAsColor4()
  41183. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41184. __decorate([
  41185. BABYLON.serialize()
  41186. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41187. __decorate([
  41188. BABYLON.serialize()
  41189. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41190. __decorate([
  41191. BABYLON.serialize()
  41192. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41193. __decorate([
  41194. BABYLON.serialize()
  41195. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41196. __decorate([
  41197. BABYLON.serialize()
  41198. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41199. return ImageProcessingConfiguration;
  41200. }());
  41201. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41202. })(BABYLON || (BABYLON = {}));
  41203. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41204. var BABYLON;
  41205. (function (BABYLON) {
  41206. /**
  41207. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41208. * It can help converting any input color in a desired output one. This can then be used to create effects
  41209. * from sepia, black and white to sixties or futuristic rendering...
  41210. *
  41211. * The only supported format is currently 3dl.
  41212. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41213. */
  41214. var ColorGradingTexture = /** @class */ (function (_super) {
  41215. __extends(ColorGradingTexture, _super);
  41216. /**
  41217. * Instantiates a ColorGradingTexture from the following parameters.
  41218. *
  41219. * @param url The location of the color gradind data (currently only supporting 3dl)
  41220. * @param scene The scene the texture will be used in
  41221. */
  41222. function ColorGradingTexture(url, scene) {
  41223. var _this = _super.call(this, scene) || this;
  41224. if (!url) {
  41225. return _this;
  41226. }
  41227. _this._engine = scene.getEngine();
  41228. _this._textureMatrix = BABYLON.Matrix.Identity();
  41229. _this.name = url;
  41230. _this.url = url;
  41231. _this.hasAlpha = false;
  41232. _this.isCube = false;
  41233. _this.is3D = _this._engine.webGLVersion > 1;
  41234. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41235. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41236. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41237. _this.anisotropicFilteringLevel = 1;
  41238. _this._texture = _this._getFromCache(url, true);
  41239. if (!_this._texture) {
  41240. if (!scene.useDelayedTextureLoading) {
  41241. _this.loadTexture();
  41242. }
  41243. else {
  41244. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41245. }
  41246. }
  41247. return _this;
  41248. }
  41249. /**
  41250. * Returns the texture matrix used in most of the material.
  41251. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41252. */
  41253. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41254. return this._textureMatrix;
  41255. };
  41256. /**
  41257. * Occurs when the file being loaded is a .3dl LUT file.
  41258. */
  41259. ColorGradingTexture.prototype.load3dlTexture = function () {
  41260. var engine = this._engine;
  41261. var texture;
  41262. if (engine.webGLVersion === 1) {
  41263. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41264. }
  41265. else {
  41266. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41267. }
  41268. this._texture = texture;
  41269. var callback = function (text) {
  41270. if (typeof text !== "string") {
  41271. return;
  41272. }
  41273. var data = null;
  41274. var tempData = null;
  41275. var line;
  41276. var lines = text.split('\n');
  41277. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41278. var maxColor = 0;
  41279. for (var i = 0; i < lines.length; i++) {
  41280. line = lines[i];
  41281. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41282. continue;
  41283. if (line.indexOf('#') === 0)
  41284. continue;
  41285. var words = line.split(" ");
  41286. if (size === 0) {
  41287. // Number of space + one
  41288. size = words.length;
  41289. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41290. tempData = new Float32Array(size * size * size * 4);
  41291. continue;
  41292. }
  41293. if (size != 0) {
  41294. var r = Math.max(parseInt(words[0]), 0);
  41295. var g = Math.max(parseInt(words[1]), 0);
  41296. var b = Math.max(parseInt(words[2]), 0);
  41297. maxColor = Math.max(r, maxColor);
  41298. maxColor = Math.max(g, maxColor);
  41299. maxColor = Math.max(b, maxColor);
  41300. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41301. if (tempData) {
  41302. tempData[pixelStorageIndex + 0] = r;
  41303. tempData[pixelStorageIndex + 1] = g;
  41304. tempData[pixelStorageIndex + 2] = b;
  41305. }
  41306. pixelIndexSlice++;
  41307. if (pixelIndexSlice % size == 0) {
  41308. pixelIndexH++;
  41309. pixelIndexSlice = 0;
  41310. if (pixelIndexH % size == 0) {
  41311. pixelIndexW++;
  41312. pixelIndexH = 0;
  41313. }
  41314. }
  41315. }
  41316. }
  41317. if (tempData && data) {
  41318. for (var i = 0; i < tempData.length; i++) {
  41319. if (i > 0 && (i + 1) % 4 === 0) {
  41320. data[i] = 255;
  41321. }
  41322. else {
  41323. var value = tempData[i];
  41324. data[i] = (value / maxColor * 255);
  41325. }
  41326. }
  41327. }
  41328. if (texture.is3D) {
  41329. texture.updateSize(size, size, size);
  41330. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41331. }
  41332. else {
  41333. texture.updateSize(size * size, size);
  41334. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41335. }
  41336. };
  41337. var scene = this.getScene();
  41338. if (scene) {
  41339. scene._loadFile(this.url, callback);
  41340. }
  41341. else {
  41342. this._engine._loadFile(this.url, callback);
  41343. }
  41344. return this._texture;
  41345. };
  41346. /**
  41347. * Starts the loading process of the texture.
  41348. */
  41349. ColorGradingTexture.prototype.loadTexture = function () {
  41350. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41351. this.load3dlTexture();
  41352. }
  41353. };
  41354. /**
  41355. * Clones the color gradind texture.
  41356. */
  41357. ColorGradingTexture.prototype.clone = function () {
  41358. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41359. // Base texture
  41360. newTexture.level = this.level;
  41361. return newTexture;
  41362. };
  41363. /**
  41364. * Called during delayed load for textures.
  41365. */
  41366. ColorGradingTexture.prototype.delayLoad = function () {
  41367. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41368. return;
  41369. }
  41370. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41371. this._texture = this._getFromCache(this.url, true);
  41372. if (!this._texture) {
  41373. this.loadTexture();
  41374. }
  41375. };
  41376. /**
  41377. * Parses a color grading texture serialized by Babylon.
  41378. * @param parsedTexture The texture information being parsedTexture
  41379. * @param scene The scene to load the texture in
  41380. * @param rootUrl The root url of the data assets to load
  41381. * @return A color gradind texture
  41382. */
  41383. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41384. var texture = null;
  41385. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41386. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41387. texture.name = parsedTexture.name;
  41388. texture.level = parsedTexture.level;
  41389. }
  41390. return texture;
  41391. };
  41392. /**
  41393. * Serializes the LUT texture to json format.
  41394. */
  41395. ColorGradingTexture.prototype.serialize = function () {
  41396. if (!this.name) {
  41397. return null;
  41398. }
  41399. var serializationObject = {};
  41400. serializationObject.name = this.name;
  41401. serializationObject.level = this.level;
  41402. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41403. return serializationObject;
  41404. };
  41405. /**
  41406. * Empty line regex stored for GC.
  41407. */
  41408. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41409. return ColorGradingTexture;
  41410. }(BABYLON.BaseTexture));
  41411. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41412. })(BABYLON || (BABYLON = {}));
  41413. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41414. var BABYLON;
  41415. (function (BABYLON) {
  41416. /**
  41417. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41418. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41419. * 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;
  41420. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41421. */
  41422. var ColorCurves = /** @class */ (function () {
  41423. function ColorCurves() {
  41424. this._dirty = true;
  41425. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41426. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41427. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41428. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41429. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41430. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41431. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41432. this._globalHue = 30;
  41433. this._globalDensity = 0;
  41434. this._globalSaturation = 0;
  41435. this._globalExposure = 0;
  41436. this._highlightsHue = 30;
  41437. this._highlightsDensity = 0;
  41438. this._highlightsSaturation = 0;
  41439. this._highlightsExposure = 0;
  41440. this._midtonesHue = 30;
  41441. this._midtonesDensity = 0;
  41442. this._midtonesSaturation = 0;
  41443. this._midtonesExposure = 0;
  41444. this._shadowsHue = 30;
  41445. this._shadowsDensity = 0;
  41446. this._shadowsSaturation = 0;
  41447. this._shadowsExposure = 0;
  41448. }
  41449. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41450. /**
  41451. * Gets the global Hue value.
  41452. * 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).
  41453. */
  41454. get: function () {
  41455. return this._globalHue;
  41456. },
  41457. /**
  41458. * Sets the global Hue value.
  41459. * 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).
  41460. */
  41461. set: function (value) {
  41462. this._globalHue = value;
  41463. this._dirty = true;
  41464. },
  41465. enumerable: true,
  41466. configurable: true
  41467. });
  41468. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41469. /**
  41470. * Gets the global Density value.
  41471. * 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.
  41472. * Values less than zero provide a filter of opposite hue.
  41473. */
  41474. get: function () {
  41475. return this._globalDensity;
  41476. },
  41477. /**
  41478. * Sets the global Density value.
  41479. * 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.
  41480. * Values less than zero provide a filter of opposite hue.
  41481. */
  41482. set: function (value) {
  41483. this._globalDensity = value;
  41484. this._dirty = true;
  41485. },
  41486. enumerable: true,
  41487. configurable: true
  41488. });
  41489. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41490. /**
  41491. * Gets the global Saturation value.
  41492. * 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.
  41493. */
  41494. get: function () {
  41495. return this._globalSaturation;
  41496. },
  41497. /**
  41498. * Sets the global Saturation value.
  41499. * 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.
  41500. */
  41501. set: function (value) {
  41502. this._globalSaturation = value;
  41503. this._dirty = true;
  41504. },
  41505. enumerable: true,
  41506. configurable: true
  41507. });
  41508. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41509. /**
  41510. * Gets the highlights Hue value.
  41511. * 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).
  41512. */
  41513. get: function () {
  41514. return this._highlightsHue;
  41515. },
  41516. /**
  41517. * Sets the highlights Hue value.
  41518. * 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).
  41519. */
  41520. set: function (value) {
  41521. this._highlightsHue = value;
  41522. this._dirty = true;
  41523. },
  41524. enumerable: true,
  41525. configurable: true
  41526. });
  41527. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41528. /**
  41529. * Gets the highlights Density value.
  41530. * 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.
  41531. * Values less than zero provide a filter of opposite hue.
  41532. */
  41533. get: function () {
  41534. return this._highlightsDensity;
  41535. },
  41536. /**
  41537. * Sets the highlights Density value.
  41538. * 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.
  41539. * Values less than zero provide a filter of opposite hue.
  41540. */
  41541. set: function (value) {
  41542. this._highlightsDensity = value;
  41543. this._dirty = true;
  41544. },
  41545. enumerable: true,
  41546. configurable: true
  41547. });
  41548. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41549. /**
  41550. * Gets the highlights Saturation value.
  41551. * 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.
  41552. */
  41553. get: function () {
  41554. return this._highlightsSaturation;
  41555. },
  41556. /**
  41557. * Sets the highlights Saturation value.
  41558. * 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.
  41559. */
  41560. set: function (value) {
  41561. this._highlightsSaturation = value;
  41562. this._dirty = true;
  41563. },
  41564. enumerable: true,
  41565. configurable: true
  41566. });
  41567. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41568. /**
  41569. * Gets the highlights Exposure value.
  41570. * 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.
  41571. */
  41572. get: function () {
  41573. return this._highlightsExposure;
  41574. },
  41575. /**
  41576. * Sets the highlights Exposure value.
  41577. * 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.
  41578. */
  41579. set: function (value) {
  41580. this._highlightsExposure = value;
  41581. this._dirty = true;
  41582. },
  41583. enumerable: true,
  41584. configurable: true
  41585. });
  41586. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41587. /**
  41588. * Gets the midtones Hue value.
  41589. * 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).
  41590. */
  41591. get: function () {
  41592. return this._midtonesHue;
  41593. },
  41594. /**
  41595. * Sets the midtones Hue value.
  41596. * 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).
  41597. */
  41598. set: function (value) {
  41599. this._midtonesHue = value;
  41600. this._dirty = true;
  41601. },
  41602. enumerable: true,
  41603. configurable: true
  41604. });
  41605. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41606. /**
  41607. * Gets the midtones Density value.
  41608. * 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.
  41609. * Values less than zero provide a filter of opposite hue.
  41610. */
  41611. get: function () {
  41612. return this._midtonesDensity;
  41613. },
  41614. /**
  41615. * Sets the midtones Density value.
  41616. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  41617. * Values less than zero provide a filter of opposite hue.
  41618. */
  41619. set: function (value) {
  41620. this._midtonesDensity = value;
  41621. this._dirty = true;
  41622. },
  41623. enumerable: true,
  41624. configurable: true
  41625. });
  41626. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41627. /**
  41628. * Gets the midtones Saturation value.
  41629. * 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.
  41630. */
  41631. get: function () {
  41632. return this._midtonesSaturation;
  41633. },
  41634. /**
  41635. * Sets the midtones Saturation value.
  41636. * 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.
  41637. */
  41638. set: function (value) {
  41639. this._midtonesSaturation = value;
  41640. this._dirty = true;
  41641. },
  41642. enumerable: true,
  41643. configurable: true
  41644. });
  41645. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41646. /**
  41647. * Gets the midtones Exposure value.
  41648. * 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.
  41649. */
  41650. get: function () {
  41651. return this._midtonesExposure;
  41652. },
  41653. /**
  41654. * Sets the midtones Exposure value.
  41655. * 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.
  41656. */
  41657. set: function (value) {
  41658. this._midtonesExposure = value;
  41659. this._dirty = true;
  41660. },
  41661. enumerable: true,
  41662. configurable: true
  41663. });
  41664. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41665. /**
  41666. * Gets the shadows Hue value.
  41667. * 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).
  41668. */
  41669. get: function () {
  41670. return this._shadowsHue;
  41671. },
  41672. /**
  41673. * Sets the shadows Hue value.
  41674. * 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).
  41675. */
  41676. set: function (value) {
  41677. this._shadowsHue = value;
  41678. this._dirty = true;
  41679. },
  41680. enumerable: true,
  41681. configurable: true
  41682. });
  41683. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41684. /**
  41685. * Gets the shadows Density value.
  41686. * 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.
  41687. * Values less than zero provide a filter of opposite hue.
  41688. */
  41689. get: function () {
  41690. return this._shadowsDensity;
  41691. },
  41692. /**
  41693. * Sets the shadows Density value.
  41694. * 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.
  41695. * Values less than zero provide a filter of opposite hue.
  41696. */
  41697. set: function (value) {
  41698. this._shadowsDensity = value;
  41699. this._dirty = true;
  41700. },
  41701. enumerable: true,
  41702. configurable: true
  41703. });
  41704. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41705. /**
  41706. * Gets the shadows Saturation value.
  41707. * 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.
  41708. */
  41709. get: function () {
  41710. return this._shadowsSaturation;
  41711. },
  41712. /**
  41713. * Sets the shadows Saturation value.
  41714. * 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.
  41715. */
  41716. set: function (value) {
  41717. this._shadowsSaturation = value;
  41718. this._dirty = true;
  41719. },
  41720. enumerable: true,
  41721. configurable: true
  41722. });
  41723. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41724. /**
  41725. * Gets the shadows Exposure value.
  41726. * 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.
  41727. */
  41728. get: function () {
  41729. return this._shadowsExposure;
  41730. },
  41731. /**
  41732. * Sets the shadows Exposure value.
  41733. * 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.
  41734. */
  41735. set: function (value) {
  41736. this._shadowsExposure = value;
  41737. this._dirty = true;
  41738. },
  41739. enumerable: true,
  41740. configurable: true
  41741. });
  41742. ColorCurves.prototype.getClassName = function () {
  41743. return "ColorCurves";
  41744. };
  41745. /**
  41746. * Binds the color curves to the shader.
  41747. * @param colorCurves The color curve to bind
  41748. * @param effect The effect to bind to
  41749. */
  41750. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41751. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41752. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41753. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41754. if (colorCurves._dirty) {
  41755. colorCurves._dirty = false;
  41756. // Fill in global info.
  41757. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41758. // Compute highlights info.
  41759. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41760. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41761. // Compute midtones info.
  41762. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41763. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41764. // Compute shadows info.
  41765. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41766. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41767. // Compute deltas (neutral is midtones).
  41768. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41769. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41770. }
  41771. if (effect) {
  41772. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41773. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41774. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41775. }
  41776. };
  41777. /**
  41778. * Prepare the list of uniforms associated with the ColorCurves effects.
  41779. * @param uniformsList The list of uniforms used in the effect
  41780. */
  41781. ColorCurves.PrepareUniforms = function (uniformsList) {
  41782. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41783. };
  41784. /**
  41785. * Returns color grading data based on a hue, density, saturation and exposure value.
  41786. * @param filterHue The hue of the color filter.
  41787. * @param filterDensity The density of the color filter.
  41788. * @param saturation The saturation.
  41789. * @param exposure The exposure.
  41790. * @param result The result data container.
  41791. */
  41792. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41793. if (hue == null) {
  41794. return;
  41795. }
  41796. hue = ColorCurves.clamp(hue, 0, 360);
  41797. density = ColorCurves.clamp(density, -100, 100);
  41798. saturation = ColorCurves.clamp(saturation, -100, 100);
  41799. exposure = ColorCurves.clamp(exposure, -100, 100);
  41800. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41801. // so that the maximum filter density is only 50% control. This provides fine control
  41802. // for small values and reasonable range.
  41803. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41804. density *= 0.5;
  41805. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41806. if (density < 0) {
  41807. density *= -1;
  41808. hue = (hue + 180) % 360;
  41809. }
  41810. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41811. result.scaleToRef(2, result);
  41812. result.a = 1 + 0.01 * saturation;
  41813. };
  41814. /**
  41815. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41816. * @param value The input slider value in range [-100,100].
  41817. * @returns Adjusted value.
  41818. */
  41819. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41820. value /= 100;
  41821. var x = Math.abs(value);
  41822. x = Math.pow(x, 2);
  41823. if (value < 0) {
  41824. x *= -1;
  41825. }
  41826. x *= 100;
  41827. return x;
  41828. };
  41829. /**
  41830. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41831. * @param hue The hue (H) input.
  41832. * @param saturation The saturation (S) input.
  41833. * @param brightness The brightness (B) input.
  41834. * @result An RGBA color represented as Vector4.
  41835. */
  41836. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41837. var h = ColorCurves.clamp(hue, 0, 360);
  41838. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41839. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41840. if (s === 0) {
  41841. result.r = v;
  41842. result.g = v;
  41843. result.b = v;
  41844. }
  41845. else {
  41846. // sector 0 to 5
  41847. h /= 60;
  41848. var i = Math.floor(h);
  41849. // fractional part of h
  41850. var f = h - i;
  41851. var p = v * (1 - s);
  41852. var q = v * (1 - s * f);
  41853. var t = v * (1 - s * (1 - f));
  41854. switch (i) {
  41855. case 0:
  41856. result.r = v;
  41857. result.g = t;
  41858. result.b = p;
  41859. break;
  41860. case 1:
  41861. result.r = q;
  41862. result.g = v;
  41863. result.b = p;
  41864. break;
  41865. case 2:
  41866. result.r = p;
  41867. result.g = v;
  41868. result.b = t;
  41869. break;
  41870. case 3:
  41871. result.r = p;
  41872. result.g = q;
  41873. result.b = v;
  41874. break;
  41875. case 4:
  41876. result.r = t;
  41877. result.g = p;
  41878. result.b = v;
  41879. break;
  41880. default: // case 5:
  41881. result.r = v;
  41882. result.g = p;
  41883. result.b = q;
  41884. break;
  41885. }
  41886. }
  41887. result.a = 1;
  41888. };
  41889. /**
  41890. * Returns a value clamped between min and max
  41891. * @param value The value to clamp
  41892. * @param min The minimum of value
  41893. * @param max The maximum of value
  41894. * @returns The clamped value.
  41895. */
  41896. ColorCurves.clamp = function (value, min, max) {
  41897. return Math.min(Math.max(value, min), max);
  41898. };
  41899. /**
  41900. * Clones the current color curve instance.
  41901. * @return The cloned curves
  41902. */
  41903. ColorCurves.prototype.clone = function () {
  41904. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  41905. };
  41906. /**
  41907. * Serializes the current color curve instance to a json representation.
  41908. * @return a JSON representation
  41909. */
  41910. ColorCurves.prototype.serialize = function () {
  41911. return BABYLON.SerializationHelper.Serialize(this);
  41912. };
  41913. /**
  41914. * Parses the color curve from a json representation.
  41915. * @param source the JSON source to parse
  41916. * @return The parsed curves
  41917. */
  41918. ColorCurves.Parse = function (source) {
  41919. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  41920. };
  41921. __decorate([
  41922. BABYLON.serialize()
  41923. ], ColorCurves.prototype, "_globalHue", void 0);
  41924. __decorate([
  41925. BABYLON.serialize()
  41926. ], ColorCurves.prototype, "_globalDensity", void 0);
  41927. __decorate([
  41928. BABYLON.serialize()
  41929. ], ColorCurves.prototype, "_globalSaturation", void 0);
  41930. __decorate([
  41931. BABYLON.serialize()
  41932. ], ColorCurves.prototype, "_globalExposure", void 0);
  41933. __decorate([
  41934. BABYLON.serialize()
  41935. ], ColorCurves.prototype, "_highlightsHue", void 0);
  41936. __decorate([
  41937. BABYLON.serialize()
  41938. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  41939. __decorate([
  41940. BABYLON.serialize()
  41941. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  41942. __decorate([
  41943. BABYLON.serialize()
  41944. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  41945. __decorate([
  41946. BABYLON.serialize()
  41947. ], ColorCurves.prototype, "_midtonesHue", void 0);
  41948. __decorate([
  41949. BABYLON.serialize()
  41950. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  41951. __decorate([
  41952. BABYLON.serialize()
  41953. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  41954. __decorate([
  41955. BABYLON.serialize()
  41956. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  41957. return ColorCurves;
  41958. }());
  41959. BABYLON.ColorCurves = ColorCurves;
  41960. })(BABYLON || (BABYLON = {}));
  41961. //# sourceMappingURL=babylon.colorCurves.js.map
  41962. //# sourceMappingURL=babylon.behavior.js.map
  41963. var BABYLON;
  41964. (function (BABYLON) {
  41965. /**
  41966. * "Static Class" containing the most commonly used helper while dealing with material for
  41967. * rendering purpose.
  41968. *
  41969. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41970. *
  41971. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41972. */
  41973. var MaterialHelper = /** @class */ (function () {
  41974. function MaterialHelper() {
  41975. }
  41976. /**
  41977. * Bind the current view position to an effect.
  41978. * @param effect The effect to be bound
  41979. * @param scene The scene the eyes position is used from
  41980. */
  41981. MaterialHelper.BindEyePosition = function (effect, scene) {
  41982. if (scene._forcedViewPosition) {
  41983. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41984. return;
  41985. }
  41986. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41987. };
  41988. /**
  41989. * Helps preparing the defines values about the UVs in used in the effect.
  41990. * UVs are shared as much as we can accross chanels in the shaders.
  41991. * @param texture The texture we are preparing the UVs for
  41992. * @param defines The defines to update
  41993. * @param key The chanel key "diffuse", "specular"... used in the shader
  41994. */
  41995. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41996. defines._needUVs = true;
  41997. defines[key] = true;
  41998. if (texture.getTextureMatrix().isIdentity(true)) {
  41999. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42000. if (texture.coordinatesIndex === 0) {
  42001. defines["MAINUV1"] = true;
  42002. }
  42003. else {
  42004. defines["MAINUV2"] = true;
  42005. }
  42006. }
  42007. else {
  42008. defines[key + "DIRECTUV"] = 0;
  42009. }
  42010. };
  42011. /**
  42012. * Binds a texture matrix value to its corrsponding uniform
  42013. * @param texture The texture to bind the matrix for
  42014. * @param uniformBuffer The uniform buffer receivin the data
  42015. * @param key The chanel key "diffuse", "specular"... used in the shader
  42016. */
  42017. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42018. var matrix = texture.getTextureMatrix();
  42019. if (!matrix.isIdentity(true)) {
  42020. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42021. }
  42022. };
  42023. /**
  42024. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42025. * @param mesh defines the current mesh
  42026. * @param scene defines the current scene
  42027. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42028. * @param pointsCloud defines if point cloud rendering has to be turned on
  42029. * @param fogEnabled defines if fog has to be turned on
  42030. * @param alphaTest defines if alpha testing has to be turned on
  42031. * @param defines defines the current list of defines
  42032. */
  42033. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42034. if (defines._areMiscDirty) {
  42035. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42036. defines["POINTSIZE"] = pointsCloud;
  42037. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42038. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42039. defines["ALPHATEST"] = alphaTest;
  42040. }
  42041. };
  42042. /**
  42043. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42044. * @param scene defines the current scene
  42045. * @param engine defines the current engine
  42046. * @param defines specifies the list of active defines
  42047. * @param useInstances defines if instances have to be turned on
  42048. * @param useClipPlane defines if clip plane have to be turned on
  42049. */
  42050. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42051. if (useClipPlane === void 0) { useClipPlane = null; }
  42052. var changed = false;
  42053. if (useClipPlane == null) {
  42054. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42055. }
  42056. if (defines["CLIPPLANE"] !== useClipPlane) {
  42057. defines["CLIPPLANE"] = useClipPlane;
  42058. changed = true;
  42059. }
  42060. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42061. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42062. changed = true;
  42063. }
  42064. if (defines["INSTANCES"] !== useInstances) {
  42065. defines["INSTANCES"] = useInstances;
  42066. changed = true;
  42067. }
  42068. if (changed) {
  42069. defines.markAsUnprocessed();
  42070. }
  42071. };
  42072. /**
  42073. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42074. * @param mesh The mesh containing the geometry data we will draw
  42075. * @param defines The defines to update
  42076. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42077. * @param useBones Precise whether bones should be used or not (override mesh info)
  42078. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42079. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42080. * @returns false if defines are considered not dirty and have not been checked
  42081. */
  42082. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42083. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42084. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42085. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42086. return false;
  42087. }
  42088. defines._normals = defines._needNormals;
  42089. defines._uvs = defines._needUVs;
  42090. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42091. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42092. defines["TANGENT"] = true;
  42093. }
  42094. if (defines._needUVs) {
  42095. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42096. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42097. }
  42098. else {
  42099. defines["UV1"] = false;
  42100. defines["UV2"] = false;
  42101. }
  42102. if (useVertexColor) {
  42103. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42104. defines["VERTEXCOLOR"] = hasVertexColors;
  42105. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42106. }
  42107. if (useBones) {
  42108. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42109. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42110. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42111. }
  42112. else {
  42113. defines["NUM_BONE_INFLUENCERS"] = 0;
  42114. defines["BonesPerMesh"] = 0;
  42115. }
  42116. }
  42117. if (useMorphTargets) {
  42118. var manager = mesh.morphTargetManager;
  42119. if (manager) {
  42120. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42121. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42122. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42123. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42124. }
  42125. else {
  42126. defines["MORPHTARGETS_TANGENT"] = false;
  42127. defines["MORPHTARGETS_NORMAL"] = false;
  42128. defines["MORPHTARGETS"] = false;
  42129. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42130. }
  42131. }
  42132. return true;
  42133. };
  42134. /**
  42135. * Prepares the defines related to the light information passed in parameter
  42136. * @param scene The scene we are intending to draw
  42137. * @param mesh The mesh the effect is compiling for
  42138. * @param defines The defines to update
  42139. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42140. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42141. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42142. * @returns true if normals will be required for the rest of the effect
  42143. */
  42144. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42145. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42146. if (disableLighting === void 0) { disableLighting = false; }
  42147. if (!defines._areLightsDirty) {
  42148. return defines._needNormals;
  42149. }
  42150. var lightIndex = 0;
  42151. var needNormals = false;
  42152. var needRebuild = false;
  42153. var lightmapMode = false;
  42154. var shadowEnabled = false;
  42155. var specularEnabled = false;
  42156. if (scene.lightsEnabled && !disableLighting) {
  42157. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42158. var light = _a[_i];
  42159. needNormals = true;
  42160. if (defines["LIGHT" + lightIndex] === undefined) {
  42161. needRebuild = true;
  42162. }
  42163. defines["LIGHT" + lightIndex] = true;
  42164. defines["SPOTLIGHT" + lightIndex] = false;
  42165. defines["HEMILIGHT" + lightIndex] = false;
  42166. defines["POINTLIGHT" + lightIndex] = false;
  42167. defines["DIRLIGHT" + lightIndex] = false;
  42168. var type;
  42169. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42170. type = "SPOTLIGHT" + lightIndex;
  42171. var spotLight = light;
  42172. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42173. }
  42174. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42175. type = "HEMILIGHT" + lightIndex;
  42176. }
  42177. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42178. type = "POINTLIGHT" + lightIndex;
  42179. }
  42180. else {
  42181. type = "DIRLIGHT" + lightIndex;
  42182. }
  42183. defines[type] = true;
  42184. // Specular
  42185. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42186. specularEnabled = true;
  42187. }
  42188. // Shadows
  42189. defines["SHADOW" + lightIndex] = false;
  42190. defines["SHADOWPCF" + lightIndex] = false;
  42191. defines["SHADOWPCSS" + lightIndex] = false;
  42192. defines["SHADOWPOISSON" + lightIndex] = false;
  42193. defines["SHADOWESM" + lightIndex] = false;
  42194. defines["SHADOWCUBE" + lightIndex] = false;
  42195. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42196. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42197. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42198. var shadowGenerator = light.getShadowGenerator();
  42199. if (shadowGenerator) {
  42200. shadowEnabled = true;
  42201. shadowGenerator.prepareDefines(defines, lightIndex);
  42202. }
  42203. }
  42204. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42205. lightmapMode = true;
  42206. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42207. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42208. }
  42209. else {
  42210. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42211. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42212. }
  42213. lightIndex++;
  42214. if (lightIndex === maxSimultaneousLights)
  42215. break;
  42216. }
  42217. }
  42218. defines["SPECULARTERM"] = specularEnabled;
  42219. defines["SHADOWS"] = shadowEnabled;
  42220. // Resetting all other lights if any
  42221. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42222. if (defines["LIGHT" + index] !== undefined) {
  42223. defines["LIGHT" + index] = false;
  42224. defines["HEMILIGHT" + lightIndex] = false;
  42225. defines["POINTLIGHT" + lightIndex] = false;
  42226. defines["DIRLIGHT" + lightIndex] = false;
  42227. defines["SPOTLIGHT" + lightIndex] = false;
  42228. defines["SHADOW" + lightIndex] = false;
  42229. }
  42230. }
  42231. var caps = scene.getEngine().getCaps();
  42232. if (defines["SHADOWFLOAT"] === undefined) {
  42233. needRebuild = true;
  42234. }
  42235. defines["SHADOWFLOAT"] = shadowEnabled &&
  42236. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42237. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42238. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42239. if (needRebuild) {
  42240. defines.rebuild();
  42241. }
  42242. return needNormals;
  42243. };
  42244. /**
  42245. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42246. * that won t be acctive due to defines being turned off.
  42247. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42248. * @param samplersList The samplers list
  42249. * @param defines The defines helping in the list generation
  42250. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42251. */
  42252. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42253. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42254. var uniformsList;
  42255. var uniformBuffersList = null;
  42256. if (uniformsListOrOptions.uniformsNames) {
  42257. var options = uniformsListOrOptions;
  42258. uniformsList = options.uniformsNames;
  42259. uniformBuffersList = options.uniformBuffersNames;
  42260. samplersList = options.samplers;
  42261. defines = options.defines;
  42262. maxSimultaneousLights = options.maxSimultaneousLights;
  42263. }
  42264. else {
  42265. uniformsList = uniformsListOrOptions;
  42266. if (!samplersList) {
  42267. samplersList = [];
  42268. }
  42269. }
  42270. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42271. if (!defines["LIGHT" + lightIndex]) {
  42272. break;
  42273. }
  42274. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42275. if (uniformBuffersList) {
  42276. uniformBuffersList.push("Light" + lightIndex);
  42277. }
  42278. samplersList.push("shadowSampler" + lightIndex);
  42279. samplersList.push("depthSampler" + lightIndex);
  42280. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42281. samplersList.push("projectionLightSampler" + lightIndex);
  42282. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42283. }
  42284. }
  42285. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42286. uniformsList.push("morphTargetInfluences");
  42287. }
  42288. };
  42289. /**
  42290. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42291. * @param defines The defines to update while falling back
  42292. * @param fallbacks The authorized effect fallbacks
  42293. * @param maxSimultaneousLights The maximum number of lights allowed
  42294. * @param rank the current rank of the Effect
  42295. * @returns The newly affected rank
  42296. */
  42297. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42298. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42299. if (rank === void 0) { rank = 0; }
  42300. var lightFallbackRank = 0;
  42301. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42302. if (!defines["LIGHT" + lightIndex]) {
  42303. break;
  42304. }
  42305. if (lightIndex > 0) {
  42306. lightFallbackRank = rank + lightIndex;
  42307. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42308. }
  42309. if (!defines["SHADOWS"]) {
  42310. if (defines["SHADOW" + lightIndex]) {
  42311. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42312. }
  42313. if (defines["SHADOWPCF" + lightIndex]) {
  42314. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42315. }
  42316. if (defines["SHADOWPCSS" + lightIndex]) {
  42317. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42318. }
  42319. if (defines["SHADOWPOISSON" + lightIndex]) {
  42320. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42321. }
  42322. if (defines["SHADOWESM" + lightIndex]) {
  42323. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42324. }
  42325. }
  42326. }
  42327. return lightFallbackRank++;
  42328. };
  42329. /**
  42330. * Prepares the list of attributes required for morph targets according to the effect defines.
  42331. * @param attribs The current list of supported attribs
  42332. * @param mesh The mesh to prepare the morph targets attributes for
  42333. * @param defines The current Defines of the effect
  42334. */
  42335. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42336. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42337. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42338. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42339. var manager = mesh.morphTargetManager;
  42340. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42341. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42342. for (var index = 0; index < influencers; index++) {
  42343. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42344. if (normal) {
  42345. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42346. }
  42347. if (tangent) {
  42348. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42349. }
  42350. if (attribs.length > maxAttributesCount) {
  42351. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42352. }
  42353. }
  42354. }
  42355. };
  42356. /**
  42357. * Prepares the list of attributes required for bones according to the effect defines.
  42358. * @param attribs The current list of supported attribs
  42359. * @param mesh The mesh to prepare the bones attributes for
  42360. * @param defines The current Defines of the effect
  42361. * @param fallbacks The current efffect fallback strategy
  42362. */
  42363. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42364. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42365. fallbacks.addCPUSkinningFallback(0, mesh);
  42366. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42367. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42368. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42369. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42370. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42371. }
  42372. }
  42373. };
  42374. /**
  42375. * Prepares the list of attributes required for instances according to the effect defines.
  42376. * @param attribs The current list of supported attribs
  42377. * @param defines The current Defines of the effect
  42378. */
  42379. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42380. if (defines["INSTANCES"]) {
  42381. attribs.push("world0");
  42382. attribs.push("world1");
  42383. attribs.push("world2");
  42384. attribs.push("world3");
  42385. }
  42386. };
  42387. /**
  42388. * Binds the light shadow information to the effect for the given mesh.
  42389. * @param light The light containing the generator
  42390. * @param scene The scene the lights belongs to
  42391. * @param mesh The mesh we are binding the information to render
  42392. * @param lightIndex The light index in the effect used to render the mesh
  42393. * @param effect The effect we are binding the data to
  42394. */
  42395. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42396. if (light.shadowEnabled && mesh.receiveShadows) {
  42397. var shadowGenerator = light.getShadowGenerator();
  42398. if (shadowGenerator) {
  42399. shadowGenerator.bindShadowLight(lightIndex, effect);
  42400. }
  42401. }
  42402. };
  42403. /**
  42404. * Binds the light information to the effect.
  42405. * @param light The light containing the generator
  42406. * @param effect The effect we are binding the data to
  42407. * @param lightIndex The light index in the effect used to render
  42408. */
  42409. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42410. light.transferToEffect(effect, lightIndex + "");
  42411. };
  42412. /**
  42413. * Binds the lights information from the scene to the effect for the given mesh.
  42414. * @param scene The scene the lights belongs to
  42415. * @param mesh The mesh we are binding the information to render
  42416. * @param effect The effect we are binding the data to
  42417. * @param defines The generated defines for the effect
  42418. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42419. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42420. */
  42421. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42422. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42423. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42424. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42425. for (var i = 0; i < len; i++) {
  42426. var light = mesh._lightSources[i];
  42427. var iAsString = i.toString();
  42428. var scaledIntensity = light.getScaledIntensity();
  42429. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42430. MaterialHelper.BindLightProperties(light, effect, i);
  42431. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42432. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42433. if (defines["SPECULARTERM"]) {
  42434. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42435. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42436. }
  42437. // Shadows
  42438. if (scene.shadowsEnabled) {
  42439. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42440. }
  42441. light._uniformBuffer.update();
  42442. }
  42443. };
  42444. /**
  42445. * Binds the fog information from the scene to the effect for the given mesh.
  42446. * @param scene The scene the lights belongs to
  42447. * @param mesh The mesh we are binding the information to render
  42448. * @param effect The effect we are binding the data to
  42449. */
  42450. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42451. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42452. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42453. effect.setColor3("vFogColor", scene.fogColor);
  42454. }
  42455. };
  42456. /**
  42457. * Binds the bones information from the mesh to the effect.
  42458. * @param mesh The mesh we are binding the information to render
  42459. * @param effect The effect we are binding the data to
  42460. */
  42461. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42462. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42463. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42464. if (matrices && effect) {
  42465. effect.setMatrices("mBones", matrices);
  42466. }
  42467. }
  42468. };
  42469. /**
  42470. * Binds the morph targets information from the mesh to the effect.
  42471. * @param abstractMesh The mesh we are binding the information to render
  42472. * @param effect The effect we are binding the data to
  42473. */
  42474. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42475. var manager = abstractMesh.morphTargetManager;
  42476. if (!abstractMesh || !manager) {
  42477. return;
  42478. }
  42479. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42480. };
  42481. /**
  42482. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42483. * @param defines The generated defines used in the effect
  42484. * @param effect The effect we are binding the data to
  42485. * @param scene The scene we are willing to render with logarithmic scale for
  42486. */
  42487. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42488. if (defines["LOGARITHMICDEPTH"]) {
  42489. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42490. }
  42491. };
  42492. /**
  42493. * Binds the clip plane information from the scene to the effect.
  42494. * @param scene The scene the clip plane information are extracted from
  42495. * @param effect The effect we are binding the data to
  42496. */
  42497. MaterialHelper.BindClipPlane = function (effect, scene) {
  42498. if (scene.clipPlane) {
  42499. var clipPlane = scene.clipPlane;
  42500. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42501. }
  42502. };
  42503. return MaterialHelper;
  42504. }());
  42505. BABYLON.MaterialHelper = MaterialHelper;
  42506. })(BABYLON || (BABYLON = {}));
  42507. //# sourceMappingURL=babylon.materialHelper.js.map
  42508. var BABYLON;
  42509. (function (BABYLON) {
  42510. var PushMaterial = /** @class */ (function (_super) {
  42511. __extends(PushMaterial, _super);
  42512. function PushMaterial(name, scene) {
  42513. var _this = _super.call(this, name, scene) || this;
  42514. _this._normalMatrix = new BABYLON.Matrix();
  42515. _this.storeEffectOnSubMeshes = true;
  42516. return _this;
  42517. }
  42518. PushMaterial.prototype.getEffect = function () {
  42519. return this._activeEffect;
  42520. };
  42521. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42522. if (!mesh) {
  42523. return false;
  42524. }
  42525. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42526. return true;
  42527. }
  42528. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42529. };
  42530. /**
  42531. * Binds the given world matrix to the active effect
  42532. *
  42533. * @param world the matrix to bind
  42534. */
  42535. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42536. this._activeEffect.setMatrix("world", world);
  42537. };
  42538. /**
  42539. * Binds the given normal matrix to the active effect
  42540. *
  42541. * @param normalMatrix the matrix to bind
  42542. */
  42543. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42544. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42545. };
  42546. PushMaterial.prototype.bind = function (world, mesh) {
  42547. if (!mesh) {
  42548. return;
  42549. }
  42550. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42551. };
  42552. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42553. if (effect === void 0) { effect = null; }
  42554. _super.prototype._afterBind.call(this, mesh);
  42555. this.getScene()._cachedEffect = effect;
  42556. };
  42557. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42558. if (visibility === void 0) { visibility = 1; }
  42559. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42560. };
  42561. return PushMaterial;
  42562. }(BABYLON.Material));
  42563. BABYLON.PushMaterial = PushMaterial;
  42564. })(BABYLON || (BABYLON = {}));
  42565. //# sourceMappingURL=babylon.pushMaterial.js.map
  42566. var BABYLON;
  42567. (function (BABYLON) {
  42568. /** @hidden */
  42569. var StandardMaterialDefines = /** @class */ (function (_super) {
  42570. __extends(StandardMaterialDefines, _super);
  42571. function StandardMaterialDefines() {
  42572. var _this = _super.call(this) || this;
  42573. _this.MAINUV1 = false;
  42574. _this.MAINUV2 = false;
  42575. _this.DIFFUSE = false;
  42576. _this.DIFFUSEDIRECTUV = 0;
  42577. _this.AMBIENT = false;
  42578. _this.AMBIENTDIRECTUV = 0;
  42579. _this.OPACITY = false;
  42580. _this.OPACITYDIRECTUV = 0;
  42581. _this.OPACITYRGB = false;
  42582. _this.REFLECTION = false;
  42583. _this.EMISSIVE = false;
  42584. _this.EMISSIVEDIRECTUV = 0;
  42585. _this.SPECULAR = false;
  42586. _this.SPECULARDIRECTUV = 0;
  42587. _this.BUMP = false;
  42588. _this.BUMPDIRECTUV = 0;
  42589. _this.PARALLAX = false;
  42590. _this.PARALLAXOCCLUSION = false;
  42591. _this.SPECULAROVERALPHA = false;
  42592. _this.CLIPPLANE = false;
  42593. _this.ALPHATEST = false;
  42594. _this.DEPTHPREPASS = false;
  42595. _this.ALPHAFROMDIFFUSE = false;
  42596. _this.POINTSIZE = false;
  42597. _this.FOG = false;
  42598. _this.SPECULARTERM = false;
  42599. _this.DIFFUSEFRESNEL = false;
  42600. _this.OPACITYFRESNEL = false;
  42601. _this.REFLECTIONFRESNEL = false;
  42602. _this.REFRACTIONFRESNEL = false;
  42603. _this.EMISSIVEFRESNEL = false;
  42604. _this.FRESNEL = false;
  42605. _this.NORMAL = false;
  42606. _this.UV1 = false;
  42607. _this.UV2 = false;
  42608. _this.VERTEXCOLOR = false;
  42609. _this.VERTEXALPHA = false;
  42610. _this.NUM_BONE_INFLUENCERS = 0;
  42611. _this.BonesPerMesh = 0;
  42612. _this.INSTANCES = false;
  42613. _this.GLOSSINESS = false;
  42614. _this.ROUGHNESS = false;
  42615. _this.EMISSIVEASILLUMINATION = false;
  42616. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42617. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42618. _this.LIGHTMAP = false;
  42619. _this.LIGHTMAPDIRECTUV = 0;
  42620. _this.OBJECTSPACE_NORMALMAP = false;
  42621. _this.USELIGHTMAPASSHADOWMAP = false;
  42622. _this.REFLECTIONMAP_3D = false;
  42623. _this.REFLECTIONMAP_SPHERICAL = false;
  42624. _this.REFLECTIONMAP_PLANAR = false;
  42625. _this.REFLECTIONMAP_CUBIC = false;
  42626. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42627. _this.REFLECTIONMAP_PROJECTION = false;
  42628. _this.REFLECTIONMAP_SKYBOX = false;
  42629. _this.REFLECTIONMAP_EXPLICIT = false;
  42630. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42631. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42632. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42633. _this.INVERTCUBICMAP = false;
  42634. _this.LOGARITHMICDEPTH = false;
  42635. _this.REFRACTION = false;
  42636. _this.REFRACTIONMAP_3D = false;
  42637. _this.REFLECTIONOVERALPHA = false;
  42638. _this.TWOSIDEDLIGHTING = false;
  42639. _this.SHADOWFLOAT = false;
  42640. _this.MORPHTARGETS = false;
  42641. _this.MORPHTARGETS_NORMAL = false;
  42642. _this.MORPHTARGETS_TANGENT = false;
  42643. _this.NUM_MORPH_INFLUENCERS = 0;
  42644. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42645. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42646. _this.IMAGEPROCESSING = false;
  42647. _this.VIGNETTE = false;
  42648. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42649. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42650. _this.TONEMAPPING = false;
  42651. _this.CONTRAST = false;
  42652. _this.COLORCURVES = false;
  42653. _this.COLORGRADING = false;
  42654. _this.COLORGRADING3D = false;
  42655. _this.SAMPLER3DGREENDEPTH = false;
  42656. _this.SAMPLER3DBGRMAP = false;
  42657. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42658. /**
  42659. * If the reflection texture on this material is in linear color space
  42660. * @hidden
  42661. */
  42662. _this.IS_REFLECTION_LINEAR = false;
  42663. /**
  42664. * If the refraction texture on this material is in linear color space
  42665. * @hidden
  42666. */
  42667. _this.IS_REFRACTION_LINEAR = false;
  42668. _this.EXPOSURE = false;
  42669. _this.rebuild();
  42670. return _this;
  42671. }
  42672. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42673. var modes = [
  42674. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42675. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42676. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42677. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42678. ];
  42679. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42680. var mode = modes_1[_i];
  42681. this[mode] = (mode === modeToEnable);
  42682. }
  42683. };
  42684. return StandardMaterialDefines;
  42685. }(BABYLON.MaterialDefines));
  42686. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42687. var StandardMaterial = /** @class */ (function (_super) {
  42688. __extends(StandardMaterial, _super);
  42689. function StandardMaterial(name, scene) {
  42690. var _this = _super.call(this, name, scene) || this;
  42691. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42692. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42693. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42694. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42695. _this.specularPower = 64;
  42696. _this._useAlphaFromDiffuseTexture = false;
  42697. _this._useEmissiveAsIllumination = false;
  42698. _this._linkEmissiveWithDiffuse = false;
  42699. _this._useSpecularOverAlpha = false;
  42700. _this._useReflectionOverAlpha = false;
  42701. _this._disableLighting = false;
  42702. _this._useObjectSpaceNormalMap = false;
  42703. _this._useParallax = false;
  42704. _this._useParallaxOcclusion = false;
  42705. _this.parallaxScaleBias = 0.05;
  42706. _this._roughness = 0;
  42707. _this.indexOfRefraction = 0.98;
  42708. _this.invertRefractionY = true;
  42709. /**
  42710. * Defines the alpha limits in alpha test mode
  42711. */
  42712. _this.alphaCutOff = 0.4;
  42713. _this._useLightmapAsShadowmap = false;
  42714. _this._useReflectionFresnelFromSpecular = false;
  42715. _this._useGlossinessFromSpecularMapAlpha = false;
  42716. _this._maxSimultaneousLights = 4;
  42717. /**
  42718. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42719. */
  42720. _this._invertNormalMapX = false;
  42721. /**
  42722. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42723. */
  42724. _this._invertNormalMapY = false;
  42725. /**
  42726. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42727. */
  42728. _this._twoSidedLighting = false;
  42729. _this._renderTargets = new BABYLON.SmartArray(16);
  42730. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42731. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42732. // Setup the default processing configuration to the scene.
  42733. _this._attachImageProcessingConfiguration(null);
  42734. _this.getRenderTargetTextures = function () {
  42735. _this._renderTargets.reset();
  42736. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42737. _this._renderTargets.push(_this._reflectionTexture);
  42738. }
  42739. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42740. _this._renderTargets.push(_this._refractionTexture);
  42741. }
  42742. return _this._renderTargets;
  42743. };
  42744. return _this;
  42745. }
  42746. ;
  42747. ;
  42748. ;
  42749. ;
  42750. ;
  42751. ;
  42752. ;
  42753. ;
  42754. ;
  42755. ;
  42756. ;
  42757. ;
  42758. ;
  42759. ;
  42760. ;
  42761. ;
  42762. ;
  42763. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42764. /**
  42765. * Gets the image processing configuration used either in this material.
  42766. */
  42767. get: function () {
  42768. return this._imageProcessingConfiguration;
  42769. },
  42770. /**
  42771. * Sets the Default image processing configuration used either in the this material.
  42772. *
  42773. * If sets to null, the scene one is in use.
  42774. */
  42775. set: function (value) {
  42776. this._attachImageProcessingConfiguration(value);
  42777. // Ensure the effect will be rebuilt.
  42778. this._markAllSubMeshesAsTexturesDirty();
  42779. },
  42780. enumerable: true,
  42781. configurable: true
  42782. });
  42783. /**
  42784. * Attaches a new image processing configuration to the Standard Material.
  42785. * @param configuration
  42786. */
  42787. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42788. var _this = this;
  42789. if (configuration === this._imageProcessingConfiguration) {
  42790. return;
  42791. }
  42792. // Detaches observer.
  42793. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42794. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42795. }
  42796. // Pick the scene configuration if needed.
  42797. if (!configuration) {
  42798. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42799. }
  42800. else {
  42801. this._imageProcessingConfiguration = configuration;
  42802. }
  42803. // Attaches observer.
  42804. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42805. _this._markAllSubMeshesAsImageProcessingDirty();
  42806. });
  42807. };
  42808. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42809. /**
  42810. * Gets wether the color curves effect is enabled.
  42811. */
  42812. get: function () {
  42813. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42814. },
  42815. /**
  42816. * Sets wether the color curves effect is enabled.
  42817. */
  42818. set: function (value) {
  42819. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42820. },
  42821. enumerable: true,
  42822. configurable: true
  42823. });
  42824. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42825. /**
  42826. * Gets wether the color grading effect is enabled.
  42827. */
  42828. get: function () {
  42829. return this.imageProcessingConfiguration.colorGradingEnabled;
  42830. },
  42831. /**
  42832. * Gets wether the color grading effect is enabled.
  42833. */
  42834. set: function (value) {
  42835. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42836. },
  42837. enumerable: true,
  42838. configurable: true
  42839. });
  42840. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42841. /**
  42842. * Gets wether tonemapping is enabled or not.
  42843. */
  42844. get: function () {
  42845. return this._imageProcessingConfiguration.toneMappingEnabled;
  42846. },
  42847. /**
  42848. * Sets wether tonemapping is enabled or not
  42849. */
  42850. set: function (value) {
  42851. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42852. },
  42853. enumerable: true,
  42854. configurable: true
  42855. });
  42856. ;
  42857. ;
  42858. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42859. /**
  42860. * The camera exposure used on this material.
  42861. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42862. * This corresponds to a photographic exposure.
  42863. */
  42864. get: function () {
  42865. return this._imageProcessingConfiguration.exposure;
  42866. },
  42867. /**
  42868. * The camera exposure used on this material.
  42869. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42870. * This corresponds to a photographic exposure.
  42871. */
  42872. set: function (value) {
  42873. this._imageProcessingConfiguration.exposure = value;
  42874. },
  42875. enumerable: true,
  42876. configurable: true
  42877. });
  42878. ;
  42879. ;
  42880. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42881. /**
  42882. * Gets The camera contrast used on this material.
  42883. */
  42884. get: function () {
  42885. return this._imageProcessingConfiguration.contrast;
  42886. },
  42887. /**
  42888. * Sets The camera contrast used on this material.
  42889. */
  42890. set: function (value) {
  42891. this._imageProcessingConfiguration.contrast = value;
  42892. },
  42893. enumerable: true,
  42894. configurable: true
  42895. });
  42896. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42897. /**
  42898. * Gets the Color Grading 2D Lookup Texture.
  42899. */
  42900. get: function () {
  42901. return this._imageProcessingConfiguration.colorGradingTexture;
  42902. },
  42903. /**
  42904. * Sets the Color Grading 2D Lookup Texture.
  42905. */
  42906. set: function (value) {
  42907. this._imageProcessingConfiguration.colorGradingTexture = value;
  42908. },
  42909. enumerable: true,
  42910. configurable: true
  42911. });
  42912. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42913. /**
  42914. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42915. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42916. * 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;
  42917. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42918. */
  42919. get: function () {
  42920. return this._imageProcessingConfiguration.colorCurves;
  42921. },
  42922. /**
  42923. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42924. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42925. * 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;
  42926. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42927. */
  42928. set: function (value) {
  42929. this._imageProcessingConfiguration.colorCurves = value;
  42930. },
  42931. enumerable: true,
  42932. configurable: true
  42933. });
  42934. StandardMaterial.prototype.getClassName = function () {
  42935. return "StandardMaterial";
  42936. };
  42937. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42938. get: function () {
  42939. return this._useLogarithmicDepth;
  42940. },
  42941. set: function (value) {
  42942. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42943. this._markAllSubMeshesAsMiscDirty();
  42944. },
  42945. enumerable: true,
  42946. configurable: true
  42947. });
  42948. StandardMaterial.prototype.needAlphaBlending = function () {
  42949. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42950. };
  42951. StandardMaterial.prototype.needAlphaTesting = function () {
  42952. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42953. };
  42954. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42955. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42956. };
  42957. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42958. return this._diffuseTexture;
  42959. };
  42960. /**
  42961. * Child classes can use it to update shaders
  42962. */
  42963. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42964. if (useInstances === void 0) { useInstances = false; }
  42965. if (subMesh.effect && this.isFrozen) {
  42966. if (this._wasPreviouslyReady && subMesh.effect) {
  42967. return true;
  42968. }
  42969. }
  42970. if (!subMesh._materialDefines) {
  42971. subMesh._materialDefines = new StandardMaterialDefines();
  42972. }
  42973. var scene = this.getScene();
  42974. var defines = subMesh._materialDefines;
  42975. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42976. if (defines._renderId === scene.getRenderId()) {
  42977. return true;
  42978. }
  42979. }
  42980. var engine = scene.getEngine();
  42981. // Lights
  42982. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42983. // Textures
  42984. if (defines._areTexturesDirty) {
  42985. defines._needUVs = false;
  42986. defines.MAINUV1 = false;
  42987. defines.MAINUV2 = false;
  42988. if (scene.texturesEnabled) {
  42989. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42990. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42991. return false;
  42992. }
  42993. else {
  42994. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42995. }
  42996. }
  42997. else {
  42998. defines.DIFFUSE = false;
  42999. }
  43000. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43001. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43002. return false;
  43003. }
  43004. else {
  43005. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43006. }
  43007. }
  43008. else {
  43009. defines.AMBIENT = false;
  43010. }
  43011. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43012. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43013. return false;
  43014. }
  43015. else {
  43016. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43017. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43018. }
  43019. }
  43020. else {
  43021. defines.OPACITY = false;
  43022. }
  43023. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43024. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43025. return false;
  43026. }
  43027. else {
  43028. defines._needNormals = true;
  43029. defines.REFLECTION = true;
  43030. defines.ROUGHNESS = (this._roughness > 0);
  43031. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43032. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43033. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43034. switch (this._reflectionTexture.coordinatesMode) {
  43035. case BABYLON.Texture.EXPLICIT_MODE:
  43036. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43037. break;
  43038. case BABYLON.Texture.PLANAR_MODE:
  43039. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43040. break;
  43041. case BABYLON.Texture.PROJECTION_MODE:
  43042. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43043. break;
  43044. case BABYLON.Texture.SKYBOX_MODE:
  43045. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43046. break;
  43047. case BABYLON.Texture.SPHERICAL_MODE:
  43048. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43049. break;
  43050. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43051. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43052. break;
  43053. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43054. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43055. break;
  43056. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43057. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43058. break;
  43059. case BABYLON.Texture.CUBIC_MODE:
  43060. case BABYLON.Texture.INVCUBIC_MODE:
  43061. default:
  43062. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43063. break;
  43064. }
  43065. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43066. }
  43067. }
  43068. else {
  43069. defines.REFLECTION = false;
  43070. }
  43071. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43072. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43073. return false;
  43074. }
  43075. else {
  43076. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43077. }
  43078. }
  43079. else {
  43080. defines.EMISSIVE = false;
  43081. }
  43082. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43083. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43084. return false;
  43085. }
  43086. else {
  43087. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43088. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43089. }
  43090. }
  43091. else {
  43092. defines.LIGHTMAP = false;
  43093. }
  43094. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43095. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43096. return false;
  43097. }
  43098. else {
  43099. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43100. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43101. }
  43102. }
  43103. else {
  43104. defines.SPECULAR = false;
  43105. }
  43106. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43107. // Bump texure can not be not blocking.
  43108. if (!this._bumpTexture.isReady()) {
  43109. return false;
  43110. }
  43111. else {
  43112. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43113. defines.PARALLAX = this._useParallax;
  43114. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43115. }
  43116. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43117. }
  43118. else {
  43119. defines.BUMP = false;
  43120. }
  43121. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43122. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43123. return false;
  43124. }
  43125. else {
  43126. defines._needUVs = true;
  43127. defines.REFRACTION = true;
  43128. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43129. }
  43130. }
  43131. else {
  43132. defines.REFRACTION = false;
  43133. }
  43134. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43135. }
  43136. else {
  43137. defines.DIFFUSE = false;
  43138. defines.AMBIENT = false;
  43139. defines.OPACITY = false;
  43140. defines.REFLECTION = false;
  43141. defines.EMISSIVE = false;
  43142. defines.LIGHTMAP = false;
  43143. defines.BUMP = false;
  43144. defines.REFRACTION = false;
  43145. }
  43146. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43147. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43148. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43149. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43150. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43151. }
  43152. if (defines._areImageProcessingDirty) {
  43153. if (!this._imageProcessingConfiguration.isReady()) {
  43154. return false;
  43155. }
  43156. this._imageProcessingConfiguration.prepareDefines(defines);
  43157. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43158. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43159. }
  43160. if (defines._areFresnelDirty) {
  43161. if (StandardMaterial.FresnelEnabled) {
  43162. // Fresnel
  43163. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43164. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43165. this._reflectionFresnelParameters) {
  43166. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43167. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43168. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43169. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43170. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43171. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43172. defines._needNormals = true;
  43173. defines.FRESNEL = true;
  43174. }
  43175. }
  43176. else {
  43177. defines.FRESNEL = false;
  43178. }
  43179. }
  43180. // Misc.
  43181. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43182. // Attribs
  43183. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43184. // Values that need to be evaluated on every frame
  43185. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43186. // Get correct effect
  43187. if (defines.isDirty) {
  43188. defines.markAsProcessed();
  43189. scene.resetCachedMaterial();
  43190. // Fallbacks
  43191. var fallbacks = new BABYLON.EffectFallbacks();
  43192. if (defines.REFLECTION) {
  43193. fallbacks.addFallback(0, "REFLECTION");
  43194. }
  43195. if (defines.SPECULAR) {
  43196. fallbacks.addFallback(0, "SPECULAR");
  43197. }
  43198. if (defines.BUMP) {
  43199. fallbacks.addFallback(0, "BUMP");
  43200. }
  43201. if (defines.PARALLAX) {
  43202. fallbacks.addFallback(1, "PARALLAX");
  43203. }
  43204. if (defines.PARALLAXOCCLUSION) {
  43205. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43206. }
  43207. if (defines.SPECULAROVERALPHA) {
  43208. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43209. }
  43210. if (defines.FOG) {
  43211. fallbacks.addFallback(1, "FOG");
  43212. }
  43213. if (defines.POINTSIZE) {
  43214. fallbacks.addFallback(0, "POINTSIZE");
  43215. }
  43216. if (defines.LOGARITHMICDEPTH) {
  43217. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43218. }
  43219. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43220. if (defines.SPECULARTERM) {
  43221. fallbacks.addFallback(0, "SPECULARTERM");
  43222. }
  43223. if (defines.DIFFUSEFRESNEL) {
  43224. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43225. }
  43226. if (defines.OPACITYFRESNEL) {
  43227. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43228. }
  43229. if (defines.REFLECTIONFRESNEL) {
  43230. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43231. }
  43232. if (defines.EMISSIVEFRESNEL) {
  43233. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43234. }
  43235. if (defines.FRESNEL) {
  43236. fallbacks.addFallback(4, "FRESNEL");
  43237. }
  43238. //Attributes
  43239. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43240. if (defines.NORMAL) {
  43241. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43242. }
  43243. if (defines.UV1) {
  43244. attribs.push(BABYLON.VertexBuffer.UVKind);
  43245. }
  43246. if (defines.UV2) {
  43247. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43248. }
  43249. if (defines.VERTEXCOLOR) {
  43250. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43251. }
  43252. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43253. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43254. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43255. var shaderName = "default";
  43256. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43257. "vFogInfos", "vFogColor", "pointSize",
  43258. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43259. "mBones",
  43260. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43261. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43262. "vReflectionPosition", "vReflectionSize",
  43263. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43264. ];
  43265. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43266. var uniformBuffers = ["Material", "Scene"];
  43267. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43268. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43269. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43270. uniformsNames: uniforms,
  43271. uniformBuffersNames: uniformBuffers,
  43272. samplers: samplers,
  43273. defines: defines,
  43274. maxSimultaneousLights: this._maxSimultaneousLights
  43275. });
  43276. if (this.customShaderNameResolve) {
  43277. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43278. }
  43279. var join = defines.toString();
  43280. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43281. attributes: attribs,
  43282. uniformsNames: uniforms,
  43283. uniformBuffersNames: uniformBuffers,
  43284. samplers: samplers,
  43285. defines: join,
  43286. fallbacks: fallbacks,
  43287. onCompiled: this.onCompiled,
  43288. onError: this.onError,
  43289. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43290. }, engine), defines);
  43291. this.buildUniformLayout();
  43292. }
  43293. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43294. return false;
  43295. }
  43296. defines._renderId = scene.getRenderId();
  43297. this._wasPreviouslyReady = true;
  43298. return true;
  43299. };
  43300. StandardMaterial.prototype.buildUniformLayout = function () {
  43301. // Order is important !
  43302. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43303. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43304. this._uniformBuffer.addUniform("opacityParts", 4);
  43305. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43306. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43307. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43308. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43309. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43310. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43311. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43312. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43313. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43314. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43315. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43316. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43317. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43318. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43319. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43320. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43321. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43322. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43323. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43324. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43325. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43326. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43327. this._uniformBuffer.addUniform("specularMatrix", 16);
  43328. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43329. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43330. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43331. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43332. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43333. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43334. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43335. this._uniformBuffer.addUniform("pointSize", 1);
  43336. this._uniformBuffer.create();
  43337. };
  43338. StandardMaterial.prototype.unbind = function () {
  43339. if (this._activeEffect) {
  43340. var needFlag = false;
  43341. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43342. this._activeEffect.setTexture("reflection2DSampler", null);
  43343. needFlag = true;
  43344. }
  43345. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43346. this._activeEffect.setTexture("refraction2DSampler", null);
  43347. needFlag = true;
  43348. }
  43349. if (needFlag) {
  43350. this._markAllSubMeshesAsTexturesDirty();
  43351. }
  43352. }
  43353. _super.prototype.unbind.call(this);
  43354. };
  43355. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43356. var scene = this.getScene();
  43357. var defines = subMesh._materialDefines;
  43358. if (!defines) {
  43359. return;
  43360. }
  43361. var effect = subMesh.effect;
  43362. if (!effect) {
  43363. return;
  43364. }
  43365. this._activeEffect = effect;
  43366. // Matrices
  43367. this.bindOnlyWorldMatrix(world);
  43368. // Normal Matrix
  43369. if (defines.OBJECTSPACE_NORMALMAP) {
  43370. world.toNormalMatrix(this._normalMatrix);
  43371. this.bindOnlyNormalMatrix(this._normalMatrix);
  43372. }
  43373. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43374. // Bones
  43375. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43376. if (mustRebind) {
  43377. this._uniformBuffer.bindToEffect(effect, "Material");
  43378. this.bindViewProjection(effect);
  43379. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43380. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43381. // Fresnel
  43382. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43383. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43384. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43385. }
  43386. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43387. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43388. }
  43389. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43390. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43391. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43392. }
  43393. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43394. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43395. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43396. }
  43397. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43398. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43399. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43400. }
  43401. }
  43402. // Textures
  43403. if (scene.texturesEnabled) {
  43404. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43405. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43406. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43407. if (this._diffuseTexture.hasAlpha) {
  43408. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43409. }
  43410. }
  43411. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43412. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43413. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43414. }
  43415. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43416. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43417. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43418. }
  43419. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43420. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43421. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43422. if (this._reflectionTexture.boundingBoxSize) {
  43423. var cubeTexture = this._reflectionTexture;
  43424. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43425. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43426. }
  43427. }
  43428. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43429. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43430. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43431. }
  43432. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43433. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43434. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43435. }
  43436. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43437. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43438. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43439. }
  43440. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43441. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43442. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43443. if (scene._mirroredCameraPosition) {
  43444. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43445. }
  43446. else {
  43447. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43448. }
  43449. }
  43450. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43451. var depth = 1.0;
  43452. if (!this._refractionTexture.isCube) {
  43453. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43454. if (this._refractionTexture.depth) {
  43455. depth = this._refractionTexture.depth;
  43456. }
  43457. }
  43458. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43459. }
  43460. }
  43461. // Point size
  43462. if (this.pointsCloud) {
  43463. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43464. }
  43465. if (defines.SPECULARTERM) {
  43466. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43467. }
  43468. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43469. // Diffuse
  43470. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43471. }
  43472. // Textures
  43473. if (scene.texturesEnabled) {
  43474. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43475. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43476. }
  43477. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43478. effect.setTexture("ambientSampler", this._ambientTexture);
  43479. }
  43480. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43481. effect.setTexture("opacitySampler", this._opacityTexture);
  43482. }
  43483. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43484. if (this._reflectionTexture.isCube) {
  43485. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43486. }
  43487. else {
  43488. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43489. }
  43490. }
  43491. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43492. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43493. }
  43494. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43495. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43496. }
  43497. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43498. effect.setTexture("specularSampler", this._specularTexture);
  43499. }
  43500. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43501. effect.setTexture("bumpSampler", this._bumpTexture);
  43502. }
  43503. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43504. var depth = 1.0;
  43505. if (this._refractionTexture.isCube) {
  43506. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43507. }
  43508. else {
  43509. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43510. }
  43511. }
  43512. }
  43513. // Clip plane
  43514. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43515. // Colors
  43516. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43517. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43518. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43519. }
  43520. if (mustRebind || !this.isFrozen) {
  43521. // Lights
  43522. if (scene.lightsEnabled && !this._disableLighting) {
  43523. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43524. }
  43525. // View
  43526. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43527. this.bindView(effect);
  43528. }
  43529. // Fog
  43530. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43531. // Morph targets
  43532. if (defines.NUM_MORPH_INFLUENCERS) {
  43533. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43534. }
  43535. // Log. depth
  43536. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43537. // image processing
  43538. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43539. this._imageProcessingConfiguration.bind(this._activeEffect);
  43540. }
  43541. }
  43542. this._uniformBuffer.update();
  43543. this._afterBind(mesh, this._activeEffect);
  43544. };
  43545. StandardMaterial.prototype.getAnimatables = function () {
  43546. var results = [];
  43547. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43548. results.push(this._diffuseTexture);
  43549. }
  43550. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43551. results.push(this._ambientTexture);
  43552. }
  43553. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43554. results.push(this._opacityTexture);
  43555. }
  43556. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43557. results.push(this._reflectionTexture);
  43558. }
  43559. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43560. results.push(this._emissiveTexture);
  43561. }
  43562. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43563. results.push(this._specularTexture);
  43564. }
  43565. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43566. results.push(this._bumpTexture);
  43567. }
  43568. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43569. results.push(this._lightmapTexture);
  43570. }
  43571. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43572. results.push(this._refractionTexture);
  43573. }
  43574. return results;
  43575. };
  43576. StandardMaterial.prototype.getActiveTextures = function () {
  43577. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43578. if (this._diffuseTexture) {
  43579. activeTextures.push(this._diffuseTexture);
  43580. }
  43581. if (this._ambientTexture) {
  43582. activeTextures.push(this._ambientTexture);
  43583. }
  43584. if (this._opacityTexture) {
  43585. activeTextures.push(this._opacityTexture);
  43586. }
  43587. if (this._reflectionTexture) {
  43588. activeTextures.push(this._reflectionTexture);
  43589. }
  43590. if (this._emissiveTexture) {
  43591. activeTextures.push(this._emissiveTexture);
  43592. }
  43593. if (this._specularTexture) {
  43594. activeTextures.push(this._specularTexture);
  43595. }
  43596. if (this._bumpTexture) {
  43597. activeTextures.push(this._bumpTexture);
  43598. }
  43599. if (this._lightmapTexture) {
  43600. activeTextures.push(this._lightmapTexture);
  43601. }
  43602. if (this._refractionTexture) {
  43603. activeTextures.push(this._refractionTexture);
  43604. }
  43605. return activeTextures;
  43606. };
  43607. StandardMaterial.prototype.hasTexture = function (texture) {
  43608. if (_super.prototype.hasTexture.call(this, texture)) {
  43609. return true;
  43610. }
  43611. if (this._diffuseTexture === texture) {
  43612. return true;
  43613. }
  43614. if (this._ambientTexture === texture) {
  43615. return true;
  43616. }
  43617. if (this._opacityTexture === texture) {
  43618. return true;
  43619. }
  43620. if (this._reflectionTexture === texture) {
  43621. return true;
  43622. }
  43623. if (this._emissiveTexture === texture) {
  43624. return true;
  43625. }
  43626. if (this._specularTexture === texture) {
  43627. return true;
  43628. }
  43629. if (this._bumpTexture === texture) {
  43630. return true;
  43631. }
  43632. if (this._lightmapTexture === texture) {
  43633. return true;
  43634. }
  43635. if (this._refractionTexture === texture) {
  43636. return true;
  43637. }
  43638. return false;
  43639. };
  43640. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43641. if (forceDisposeTextures) {
  43642. if (this._diffuseTexture) {
  43643. this._diffuseTexture.dispose();
  43644. }
  43645. if (this._ambientTexture) {
  43646. this._ambientTexture.dispose();
  43647. }
  43648. if (this._opacityTexture) {
  43649. this._opacityTexture.dispose();
  43650. }
  43651. if (this._reflectionTexture) {
  43652. this._reflectionTexture.dispose();
  43653. }
  43654. if (this._emissiveTexture) {
  43655. this._emissiveTexture.dispose();
  43656. }
  43657. if (this._specularTexture) {
  43658. this._specularTexture.dispose();
  43659. }
  43660. if (this._bumpTexture) {
  43661. this._bumpTexture.dispose();
  43662. }
  43663. if (this._lightmapTexture) {
  43664. this._lightmapTexture.dispose();
  43665. }
  43666. if (this._refractionTexture) {
  43667. this._refractionTexture.dispose();
  43668. }
  43669. }
  43670. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43671. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43672. }
  43673. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43674. };
  43675. StandardMaterial.prototype.clone = function (name) {
  43676. var _this = this;
  43677. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43678. result.name = name;
  43679. result.id = name;
  43680. return result;
  43681. };
  43682. StandardMaterial.prototype.serialize = function () {
  43683. return BABYLON.SerializationHelper.Serialize(this);
  43684. };
  43685. // Statics
  43686. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43687. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43688. };
  43689. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43690. get: function () {
  43691. return StandardMaterial._DiffuseTextureEnabled;
  43692. },
  43693. set: function (value) {
  43694. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43695. return;
  43696. }
  43697. StandardMaterial._DiffuseTextureEnabled = value;
  43698. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43699. },
  43700. enumerable: true,
  43701. configurable: true
  43702. });
  43703. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43704. get: function () {
  43705. return StandardMaterial._AmbientTextureEnabled;
  43706. },
  43707. set: function (value) {
  43708. if (StandardMaterial._AmbientTextureEnabled === value) {
  43709. return;
  43710. }
  43711. StandardMaterial._AmbientTextureEnabled = value;
  43712. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43713. },
  43714. enumerable: true,
  43715. configurable: true
  43716. });
  43717. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43718. get: function () {
  43719. return StandardMaterial._OpacityTextureEnabled;
  43720. },
  43721. set: function (value) {
  43722. if (StandardMaterial._OpacityTextureEnabled === value) {
  43723. return;
  43724. }
  43725. StandardMaterial._OpacityTextureEnabled = value;
  43726. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43727. },
  43728. enumerable: true,
  43729. configurable: true
  43730. });
  43731. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43732. get: function () {
  43733. return StandardMaterial._ReflectionTextureEnabled;
  43734. },
  43735. set: function (value) {
  43736. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43737. return;
  43738. }
  43739. StandardMaterial._ReflectionTextureEnabled = value;
  43740. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43741. },
  43742. enumerable: true,
  43743. configurable: true
  43744. });
  43745. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43746. get: function () {
  43747. return StandardMaterial._EmissiveTextureEnabled;
  43748. },
  43749. set: function (value) {
  43750. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43751. return;
  43752. }
  43753. StandardMaterial._EmissiveTextureEnabled = value;
  43754. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43755. },
  43756. enumerable: true,
  43757. configurable: true
  43758. });
  43759. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43760. get: function () {
  43761. return StandardMaterial._SpecularTextureEnabled;
  43762. },
  43763. set: function (value) {
  43764. if (StandardMaterial._SpecularTextureEnabled === value) {
  43765. return;
  43766. }
  43767. StandardMaterial._SpecularTextureEnabled = value;
  43768. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43769. },
  43770. enumerable: true,
  43771. configurable: true
  43772. });
  43773. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43774. get: function () {
  43775. return StandardMaterial._BumpTextureEnabled;
  43776. },
  43777. set: function (value) {
  43778. if (StandardMaterial._BumpTextureEnabled === value) {
  43779. return;
  43780. }
  43781. StandardMaterial._BumpTextureEnabled = value;
  43782. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43783. },
  43784. enumerable: true,
  43785. configurable: true
  43786. });
  43787. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43788. get: function () {
  43789. return StandardMaterial._LightmapTextureEnabled;
  43790. },
  43791. set: function (value) {
  43792. if (StandardMaterial._LightmapTextureEnabled === value) {
  43793. return;
  43794. }
  43795. StandardMaterial._LightmapTextureEnabled = value;
  43796. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43797. },
  43798. enumerable: true,
  43799. configurable: true
  43800. });
  43801. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43802. get: function () {
  43803. return StandardMaterial._RefractionTextureEnabled;
  43804. },
  43805. set: function (value) {
  43806. if (StandardMaterial._RefractionTextureEnabled === value) {
  43807. return;
  43808. }
  43809. StandardMaterial._RefractionTextureEnabled = value;
  43810. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43811. },
  43812. enumerable: true,
  43813. configurable: true
  43814. });
  43815. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43816. get: function () {
  43817. return StandardMaterial._ColorGradingTextureEnabled;
  43818. },
  43819. set: function (value) {
  43820. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43821. return;
  43822. }
  43823. StandardMaterial._ColorGradingTextureEnabled = value;
  43824. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43825. },
  43826. enumerable: true,
  43827. configurable: true
  43828. });
  43829. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43830. get: function () {
  43831. return StandardMaterial._FresnelEnabled;
  43832. },
  43833. set: function (value) {
  43834. if (StandardMaterial._FresnelEnabled === value) {
  43835. return;
  43836. }
  43837. StandardMaterial._FresnelEnabled = value;
  43838. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43839. },
  43840. enumerable: true,
  43841. configurable: true
  43842. });
  43843. // Flags used to enable or disable a type of texture for all Standard Materials
  43844. StandardMaterial._DiffuseTextureEnabled = true;
  43845. StandardMaterial._AmbientTextureEnabled = true;
  43846. StandardMaterial._OpacityTextureEnabled = true;
  43847. StandardMaterial._ReflectionTextureEnabled = true;
  43848. StandardMaterial._EmissiveTextureEnabled = true;
  43849. StandardMaterial._SpecularTextureEnabled = true;
  43850. StandardMaterial._BumpTextureEnabled = true;
  43851. StandardMaterial._LightmapTextureEnabled = true;
  43852. StandardMaterial._RefractionTextureEnabled = true;
  43853. StandardMaterial._ColorGradingTextureEnabled = true;
  43854. StandardMaterial._FresnelEnabled = true;
  43855. __decorate([
  43856. BABYLON.serializeAsTexture("diffuseTexture")
  43857. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43858. __decorate([
  43859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43860. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43861. __decorate([
  43862. BABYLON.serializeAsTexture("ambientTexture")
  43863. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43864. __decorate([
  43865. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43866. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43867. __decorate([
  43868. BABYLON.serializeAsTexture("opacityTexture")
  43869. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43870. __decorate([
  43871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43872. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43873. __decorate([
  43874. BABYLON.serializeAsTexture("reflectionTexture")
  43875. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43876. __decorate([
  43877. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43878. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43879. __decorate([
  43880. BABYLON.serializeAsTexture("emissiveTexture")
  43881. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43882. __decorate([
  43883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43884. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43885. __decorate([
  43886. BABYLON.serializeAsTexture("specularTexture")
  43887. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43888. __decorate([
  43889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43890. ], StandardMaterial.prototype, "specularTexture", void 0);
  43891. __decorate([
  43892. BABYLON.serializeAsTexture("bumpTexture")
  43893. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43894. __decorate([
  43895. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43896. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43897. __decorate([
  43898. BABYLON.serializeAsTexture("lightmapTexture")
  43899. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43900. __decorate([
  43901. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43902. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43903. __decorate([
  43904. BABYLON.serializeAsTexture("refractionTexture")
  43905. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43906. __decorate([
  43907. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43908. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43909. __decorate([
  43910. BABYLON.serializeAsColor3("ambient")
  43911. ], StandardMaterial.prototype, "ambientColor", void 0);
  43912. __decorate([
  43913. BABYLON.serializeAsColor3("diffuse")
  43914. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43915. __decorate([
  43916. BABYLON.serializeAsColor3("specular")
  43917. ], StandardMaterial.prototype, "specularColor", void 0);
  43918. __decorate([
  43919. BABYLON.serializeAsColor3("emissive")
  43920. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43921. __decorate([
  43922. BABYLON.serialize()
  43923. ], StandardMaterial.prototype, "specularPower", void 0);
  43924. __decorate([
  43925. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43926. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43927. __decorate([
  43928. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43929. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43930. __decorate([
  43931. BABYLON.serialize("useEmissiveAsIllumination")
  43932. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43933. __decorate([
  43934. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43935. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43936. __decorate([
  43937. BABYLON.serialize("linkEmissiveWithDiffuse")
  43938. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43939. __decorate([
  43940. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43941. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43942. __decorate([
  43943. BABYLON.serialize("useSpecularOverAlpha")
  43944. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43945. __decorate([
  43946. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43947. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43948. __decorate([
  43949. BABYLON.serialize("useReflectionOverAlpha")
  43950. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43951. __decorate([
  43952. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43953. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43954. __decorate([
  43955. BABYLON.serialize("disableLighting")
  43956. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43957. __decorate([
  43958. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43959. ], StandardMaterial.prototype, "disableLighting", void 0);
  43960. __decorate([
  43961. BABYLON.serialize("useObjectSpaceNormalMap")
  43962. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43963. __decorate([
  43964. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43965. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43966. __decorate([
  43967. BABYLON.serialize("useParallax")
  43968. ], StandardMaterial.prototype, "_useParallax", void 0);
  43969. __decorate([
  43970. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43971. ], StandardMaterial.prototype, "useParallax", void 0);
  43972. __decorate([
  43973. BABYLON.serialize("useParallaxOcclusion")
  43974. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43975. __decorate([
  43976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43977. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43978. __decorate([
  43979. BABYLON.serialize()
  43980. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43981. __decorate([
  43982. BABYLON.serialize("roughness")
  43983. ], StandardMaterial.prototype, "_roughness", void 0);
  43984. __decorate([
  43985. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43986. ], StandardMaterial.prototype, "roughness", void 0);
  43987. __decorate([
  43988. BABYLON.serialize()
  43989. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43990. __decorate([
  43991. BABYLON.serialize()
  43992. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43993. __decorate([
  43994. BABYLON.serialize()
  43995. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43996. __decorate([
  43997. BABYLON.serialize("useLightmapAsShadowmap")
  43998. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43999. __decorate([
  44000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44001. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44002. __decorate([
  44003. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44004. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44005. __decorate([
  44006. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44007. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44008. __decorate([
  44009. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44010. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44011. __decorate([
  44012. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44013. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44014. __decorate([
  44015. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44016. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44017. __decorate([
  44018. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44019. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44020. __decorate([
  44021. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44022. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44023. __decorate([
  44024. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44025. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44026. __decorate([
  44027. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44028. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44029. __decorate([
  44030. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44031. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44032. __decorate([
  44033. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44034. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44035. __decorate([
  44036. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44037. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44038. __decorate([
  44039. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44040. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44041. __decorate([
  44042. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44043. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44044. __decorate([
  44045. BABYLON.serialize("maxSimultaneousLights")
  44046. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44047. __decorate([
  44048. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44049. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44050. __decorate([
  44051. BABYLON.serialize("invertNormalMapX")
  44052. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44053. __decorate([
  44054. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44055. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44056. __decorate([
  44057. BABYLON.serialize("invertNormalMapY")
  44058. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44059. __decorate([
  44060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44061. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44062. __decorate([
  44063. BABYLON.serialize("twoSidedLighting")
  44064. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44065. __decorate([
  44066. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44067. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44068. __decorate([
  44069. BABYLON.serialize()
  44070. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44071. return StandardMaterial;
  44072. }(BABYLON.PushMaterial));
  44073. BABYLON.StandardMaterial = StandardMaterial;
  44074. })(BABYLON || (BABYLON = {}));
  44075. //# sourceMappingURL=babylon.standardMaterial.js.map
  44076. var BABYLON;
  44077. (function (BABYLON) {
  44078. /**
  44079. * Manages the defines for the PBR Material.
  44080. * @hiddenChildren
  44081. */
  44082. var PBRMaterialDefines = /** @class */ (function (_super) {
  44083. __extends(PBRMaterialDefines, _super);
  44084. /**
  44085. * Initializes the PBR Material defines.
  44086. */
  44087. function PBRMaterialDefines() {
  44088. var _this = _super.call(this) || this;
  44089. _this.PBR = true;
  44090. _this.MAINUV1 = false;
  44091. _this.MAINUV2 = false;
  44092. _this.UV1 = false;
  44093. _this.UV2 = false;
  44094. _this.ALBEDO = false;
  44095. _this.ALBEDODIRECTUV = 0;
  44096. _this.VERTEXCOLOR = false;
  44097. _this.AMBIENT = false;
  44098. _this.AMBIENTDIRECTUV = 0;
  44099. _this.AMBIENTINGRAYSCALE = false;
  44100. _this.OPACITY = false;
  44101. _this.VERTEXALPHA = false;
  44102. _this.OPACITYDIRECTUV = 0;
  44103. _this.OPACITYRGB = false;
  44104. _this.ALPHATEST = false;
  44105. _this.DEPTHPREPASS = false;
  44106. _this.ALPHABLEND = false;
  44107. _this.ALPHAFROMALBEDO = false;
  44108. _this.ALPHATESTVALUE = "0.5";
  44109. _this.SPECULAROVERALPHA = false;
  44110. _this.RADIANCEOVERALPHA = false;
  44111. _this.ALPHAFRESNEL = false;
  44112. _this.LINEARALPHAFRESNEL = false;
  44113. _this.PREMULTIPLYALPHA = false;
  44114. _this.EMISSIVE = false;
  44115. _this.EMISSIVEDIRECTUV = 0;
  44116. _this.REFLECTIVITY = false;
  44117. _this.REFLECTIVITYDIRECTUV = 0;
  44118. _this.SPECULARTERM = false;
  44119. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44120. _this.MICROSURFACEAUTOMATIC = false;
  44121. _this.LODBASEDMICROSFURACE = false;
  44122. _this.MICROSURFACEMAP = false;
  44123. _this.MICROSURFACEMAPDIRECTUV = 0;
  44124. _this.METALLICWORKFLOW = false;
  44125. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44126. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44127. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44128. _this.AOSTOREINMETALMAPRED = false;
  44129. _this.ENVIRONMENTBRDF = false;
  44130. _this.NORMAL = false;
  44131. _this.TANGENT = false;
  44132. _this.BUMP = false;
  44133. _this.BUMPDIRECTUV = 0;
  44134. _this.OBJECTSPACE_NORMALMAP = false;
  44135. _this.PARALLAX = false;
  44136. _this.PARALLAXOCCLUSION = false;
  44137. _this.NORMALXYSCALE = true;
  44138. _this.LIGHTMAP = false;
  44139. _this.LIGHTMAPDIRECTUV = 0;
  44140. _this.USELIGHTMAPASSHADOWMAP = false;
  44141. _this.GAMMALIGHTMAP = false;
  44142. _this.REFLECTION = false;
  44143. _this.REFLECTIONMAP_3D = false;
  44144. _this.REFLECTIONMAP_SPHERICAL = false;
  44145. _this.REFLECTIONMAP_PLANAR = false;
  44146. _this.REFLECTIONMAP_CUBIC = false;
  44147. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44148. _this.REFLECTIONMAP_PROJECTION = false;
  44149. _this.REFLECTIONMAP_SKYBOX = false;
  44150. _this.REFLECTIONMAP_EXPLICIT = false;
  44151. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44152. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44153. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44154. _this.INVERTCUBICMAP = false;
  44155. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44156. _this.USESPHERICALINVERTEX = false;
  44157. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44158. _this.LODINREFLECTIONALPHA = false;
  44159. _this.GAMMAREFLECTION = false;
  44160. _this.RADIANCEOCCLUSION = false;
  44161. _this.HORIZONOCCLUSION = false;
  44162. _this.REFRACTION = false;
  44163. _this.REFRACTIONMAP_3D = false;
  44164. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44165. _this.LODINREFRACTIONALPHA = false;
  44166. _this.GAMMAREFRACTION = false;
  44167. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44168. _this.INSTANCES = false;
  44169. _this.NUM_BONE_INFLUENCERS = 0;
  44170. _this.BonesPerMesh = 0;
  44171. _this.NONUNIFORMSCALING = false;
  44172. _this.MORPHTARGETS = false;
  44173. _this.MORPHTARGETS_NORMAL = false;
  44174. _this.MORPHTARGETS_TANGENT = false;
  44175. _this.NUM_MORPH_INFLUENCERS = 0;
  44176. _this.IMAGEPROCESSING = false;
  44177. _this.VIGNETTE = false;
  44178. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44179. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44180. _this.TONEMAPPING = false;
  44181. _this.CONTRAST = false;
  44182. _this.COLORCURVES = false;
  44183. _this.COLORGRADING = false;
  44184. _this.COLORGRADING3D = false;
  44185. _this.SAMPLER3DGREENDEPTH = false;
  44186. _this.SAMPLER3DBGRMAP = false;
  44187. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44188. _this.EXPOSURE = false;
  44189. _this.USEPHYSICALLIGHTFALLOFF = false;
  44190. _this.TWOSIDEDLIGHTING = false;
  44191. _this.SHADOWFLOAT = false;
  44192. _this.CLIPPLANE = false;
  44193. _this.POINTSIZE = false;
  44194. _this.FOG = false;
  44195. _this.LOGARITHMICDEPTH = false;
  44196. _this.FORCENORMALFORWARD = false;
  44197. _this.SPECULARAA = false;
  44198. _this.UNLIT = false;
  44199. _this.rebuild();
  44200. return _this;
  44201. }
  44202. /**
  44203. * Resets the PBR Material defines.
  44204. */
  44205. PBRMaterialDefines.prototype.reset = function () {
  44206. _super.prototype.reset.call(this);
  44207. this.ALPHATESTVALUE = "0.5";
  44208. this.PBR = true;
  44209. };
  44210. return PBRMaterialDefines;
  44211. }(BABYLON.MaterialDefines));
  44212. /**
  44213. * The Physically based material base class of BJS.
  44214. *
  44215. * This offers the main features of a standard PBR material.
  44216. * For more information, please refer to the documentation :
  44217. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44218. */
  44219. var PBRBaseMaterial = /** @class */ (function (_super) {
  44220. __extends(PBRBaseMaterial, _super);
  44221. /**
  44222. * Instantiates a new PBRMaterial instance.
  44223. *
  44224. * @param name The material name
  44225. * @param scene The scene the material will be use in.
  44226. */
  44227. function PBRBaseMaterial(name, scene) {
  44228. var _this = _super.call(this, name, scene) || this;
  44229. /**
  44230. * Intensity of the direct lights e.g. the four lights available in your scene.
  44231. * This impacts both the direct diffuse and specular highlights.
  44232. */
  44233. _this._directIntensity = 1.0;
  44234. /**
  44235. * Intensity of the emissive part of the material.
  44236. * This helps controlling the emissive effect without modifying the emissive color.
  44237. */
  44238. _this._emissiveIntensity = 1.0;
  44239. /**
  44240. * Intensity of the environment e.g. how much the environment will light the object
  44241. * either through harmonics for rough material or through the refelction for shiny ones.
  44242. */
  44243. _this._environmentIntensity = 1.0;
  44244. /**
  44245. * This is a special control allowing the reduction of the specular highlights coming from the
  44246. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44247. */
  44248. _this._specularIntensity = 1.0;
  44249. /**
  44250. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44251. */
  44252. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44253. /**
  44254. * Debug Control allowing disabling the bump map on this material.
  44255. */
  44256. _this._disableBumpMap = false;
  44257. /**
  44258. * AKA Occlusion Texture Intensity in other nomenclature.
  44259. */
  44260. _this._ambientTextureStrength = 1.0;
  44261. /**
  44262. * The color of a material in ambient lighting.
  44263. */
  44264. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44265. /**
  44266. * AKA Diffuse Color in other nomenclature.
  44267. */
  44268. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44269. /**
  44270. * AKA Specular Color in other nomenclature.
  44271. */
  44272. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44273. /**
  44274. * The color applied when light is reflected from a material.
  44275. */
  44276. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44277. /**
  44278. * The color applied when light is emitted from a material.
  44279. */
  44280. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44281. /**
  44282. * AKA Glossiness in other nomenclature.
  44283. */
  44284. _this._microSurface = 0.9;
  44285. /**
  44286. * source material index of refraction (IOR)' / 'destination material IOR.
  44287. */
  44288. _this._indexOfRefraction = 0.66;
  44289. /**
  44290. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44291. */
  44292. _this._invertRefractionY = false;
  44293. /**
  44294. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44295. * Materials half opaque for instance using refraction could benefit from this control.
  44296. */
  44297. _this._linkRefractionWithTransparency = false;
  44298. /**
  44299. * Specifies that the material will use the light map as a show map.
  44300. */
  44301. _this._useLightmapAsShadowmap = false;
  44302. /**
  44303. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44304. * makes the reflect vector face the model (under horizon).
  44305. */
  44306. _this._useHorizonOcclusion = true;
  44307. /**
  44308. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44309. * too much the area relying on ambient texture to define their ambient occlusion.
  44310. */
  44311. _this._useRadianceOcclusion = true;
  44312. /**
  44313. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44314. */
  44315. _this._useAlphaFromAlbedoTexture = false;
  44316. /**
  44317. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44318. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44319. */
  44320. _this._useSpecularOverAlpha = true;
  44321. /**
  44322. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44323. */
  44324. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44325. /**
  44326. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44327. */
  44328. _this._useRoughnessFromMetallicTextureAlpha = true;
  44329. /**
  44330. * Specifies if the metallic texture contains the roughness information in its green channel.
  44331. */
  44332. _this._useRoughnessFromMetallicTextureGreen = false;
  44333. /**
  44334. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44335. */
  44336. _this._useMetallnessFromMetallicTextureBlue = false;
  44337. /**
  44338. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44339. */
  44340. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44341. /**
  44342. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44343. */
  44344. _this._useAmbientInGrayScale = false;
  44345. /**
  44346. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44347. * The material will try to infer what glossiness each pixel should be.
  44348. */
  44349. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44350. /**
  44351. * BJS is using an harcoded light falloff based on a manually sets up range.
  44352. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44353. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44354. */
  44355. _this._usePhysicalLightFalloff = true;
  44356. /**
  44357. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44358. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44359. */
  44360. _this._useRadianceOverAlpha = true;
  44361. /**
  44362. * Allows using an object space normal map (instead of tangent space).
  44363. */
  44364. _this._useObjectSpaceNormalMap = false;
  44365. /**
  44366. * Allows using the bump map in parallax mode.
  44367. */
  44368. _this._useParallax = false;
  44369. /**
  44370. * Allows using the bump map in parallax occlusion mode.
  44371. */
  44372. _this._useParallaxOcclusion = false;
  44373. /**
  44374. * Controls the scale bias of the parallax mode.
  44375. */
  44376. _this._parallaxScaleBias = 0.05;
  44377. /**
  44378. * If sets to true, disables all the lights affecting the material.
  44379. */
  44380. _this._disableLighting = false;
  44381. /**
  44382. * Number of Simultaneous lights allowed on the material.
  44383. */
  44384. _this._maxSimultaneousLights = 4;
  44385. /**
  44386. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44387. */
  44388. _this._invertNormalMapX = false;
  44389. /**
  44390. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44391. */
  44392. _this._invertNormalMapY = false;
  44393. /**
  44394. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44395. */
  44396. _this._twoSidedLighting = false;
  44397. /**
  44398. * Defines the alpha limits in alpha test mode.
  44399. */
  44400. _this._alphaCutOff = 0.4;
  44401. /**
  44402. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44403. */
  44404. _this._forceAlphaTest = false;
  44405. /**
  44406. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44407. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44408. */
  44409. _this._useAlphaFresnel = false;
  44410. /**
  44411. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44412. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44413. */
  44414. _this._useLinearAlphaFresnel = false;
  44415. /**
  44416. * The transparency mode of the material.
  44417. */
  44418. _this._transparencyMode = null;
  44419. /**
  44420. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44421. * from cos thetav and roughness:
  44422. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44423. */
  44424. _this._environmentBRDFTexture = null;
  44425. /**
  44426. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44427. */
  44428. _this._forceIrradianceInFragment = false;
  44429. /**
  44430. * Force normal to face away from face.
  44431. */
  44432. _this._forceNormalForward = false;
  44433. /**
  44434. * Enables specular anti aliasing in the PBR shader.
  44435. * It will both interacts on the Geometry for analytical and IBL lighting.
  44436. * It also prefilter the roughness map based on the bump values.
  44437. */
  44438. _this._enableSpecularAntiAliasing = false;
  44439. /**
  44440. * Stores the available render targets.
  44441. */
  44442. _this._renderTargets = new BABYLON.SmartArray(16);
  44443. /**
  44444. * Sets the global ambient color for the material used in lighting calculations.
  44445. */
  44446. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44447. /**
  44448. * If set to true, no lighting calculations will be applied.
  44449. */
  44450. _this._unlit = false;
  44451. // Setup the default processing configuration to the scene.
  44452. _this._attachImageProcessingConfiguration(null);
  44453. _this.getRenderTargetTextures = function () {
  44454. _this._renderTargets.reset();
  44455. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44456. _this._renderTargets.push(_this._reflectionTexture);
  44457. }
  44458. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44459. _this._renderTargets.push(_this._refractionTexture);
  44460. }
  44461. return _this._renderTargets;
  44462. };
  44463. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44464. return _this;
  44465. }
  44466. /**
  44467. * Attaches a new image processing configuration to the PBR Material.
  44468. * @param configuration
  44469. */
  44470. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44471. var _this = this;
  44472. if (configuration === this._imageProcessingConfiguration) {
  44473. return;
  44474. }
  44475. // Detaches observer.
  44476. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44477. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44478. }
  44479. // Pick the scene configuration if needed.
  44480. if (!configuration) {
  44481. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44482. }
  44483. else {
  44484. this._imageProcessingConfiguration = configuration;
  44485. }
  44486. // Attaches observer.
  44487. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44488. _this._markAllSubMeshesAsImageProcessingDirty();
  44489. });
  44490. };
  44491. /**
  44492. * Gets the name of the material class.
  44493. */
  44494. PBRBaseMaterial.prototype.getClassName = function () {
  44495. return "PBRBaseMaterial";
  44496. };
  44497. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44498. /**
  44499. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44500. */
  44501. get: function () {
  44502. return this._useLogarithmicDepth;
  44503. },
  44504. /**
  44505. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44506. */
  44507. set: function (value) {
  44508. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44509. },
  44510. enumerable: true,
  44511. configurable: true
  44512. });
  44513. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44514. /**
  44515. * Gets the current transparency mode.
  44516. */
  44517. get: function () {
  44518. return this._transparencyMode;
  44519. },
  44520. /**
  44521. * Sets the transparency mode of the material.
  44522. */
  44523. set: function (value) {
  44524. if (this._transparencyMode === value) {
  44525. return;
  44526. }
  44527. this._transparencyMode = value;
  44528. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44529. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44530. },
  44531. enumerable: true,
  44532. configurable: true
  44533. });
  44534. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44535. /**
  44536. * Returns true if alpha blending should be disabled.
  44537. */
  44538. get: function () {
  44539. return (this._linkRefractionWithTransparency ||
  44540. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44541. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44542. },
  44543. enumerable: true,
  44544. configurable: true
  44545. });
  44546. /**
  44547. * Specifies whether or not this material should be rendered in alpha blend mode.
  44548. */
  44549. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44550. if (this._disableAlphaBlending) {
  44551. return false;
  44552. }
  44553. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44554. };
  44555. /**
  44556. * Specifies if the mesh will require alpha blending.
  44557. * @param mesh - BJS mesh.
  44558. */
  44559. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44560. if (this._disableAlphaBlending) {
  44561. return false;
  44562. }
  44563. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44564. };
  44565. /**
  44566. * Specifies whether or not this material should be rendered in alpha test mode.
  44567. */
  44568. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44569. if (this._forceAlphaTest) {
  44570. return true;
  44571. }
  44572. if (this._linkRefractionWithTransparency) {
  44573. return false;
  44574. }
  44575. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44576. };
  44577. /**
  44578. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44579. */
  44580. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44581. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44582. };
  44583. /**
  44584. * Gets the texture used for the alpha test.
  44585. */
  44586. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44587. return this._albedoTexture;
  44588. };
  44589. /**
  44590. * Specifies that the submesh is ready to be used.
  44591. * @param mesh - BJS mesh.
  44592. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44593. * @param useInstances - Specifies that instances should be used.
  44594. * @returns - boolean indicating that the submesh is ready or not.
  44595. */
  44596. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44597. if (subMesh.effect && this.isFrozen) {
  44598. if (this._wasPreviouslyReady) {
  44599. return true;
  44600. }
  44601. }
  44602. if (!subMesh._materialDefines) {
  44603. subMesh._materialDefines = new PBRMaterialDefines();
  44604. }
  44605. var defines = subMesh._materialDefines;
  44606. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44607. if (defines._renderId === this.getScene().getRenderId()) {
  44608. return true;
  44609. }
  44610. }
  44611. var scene = this.getScene();
  44612. var engine = scene.getEngine();
  44613. if (defines._areTexturesDirty) {
  44614. if (scene.texturesEnabled) {
  44615. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44616. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44617. return false;
  44618. }
  44619. }
  44620. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44621. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44622. return false;
  44623. }
  44624. }
  44625. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44626. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44627. return false;
  44628. }
  44629. }
  44630. var reflectionTexture = this._getReflectionTexture();
  44631. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44632. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44633. return false;
  44634. }
  44635. }
  44636. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44637. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44638. return false;
  44639. }
  44640. }
  44641. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44642. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44643. return false;
  44644. }
  44645. }
  44646. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44647. if (this._metallicTexture) {
  44648. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44649. return false;
  44650. }
  44651. }
  44652. else if (this._reflectivityTexture) {
  44653. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44654. return false;
  44655. }
  44656. }
  44657. if (this._microSurfaceTexture) {
  44658. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44659. return false;
  44660. }
  44661. }
  44662. }
  44663. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44664. // Bump texture cannot be not blocking.
  44665. if (!this._bumpTexture.isReady()) {
  44666. return false;
  44667. }
  44668. }
  44669. var refractionTexture = this._getRefractionTexture();
  44670. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44671. if (!refractionTexture.isReadyOrNotBlocking()) {
  44672. return false;
  44673. }
  44674. }
  44675. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44676. // This is blocking.
  44677. if (!this._environmentBRDFTexture.isReady()) {
  44678. return false;
  44679. }
  44680. }
  44681. }
  44682. }
  44683. if (defines._areImageProcessingDirty) {
  44684. if (!this._imageProcessingConfiguration.isReady()) {
  44685. return false;
  44686. }
  44687. }
  44688. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44689. mesh.createNormals(true);
  44690. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44691. }
  44692. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44693. if (effect) {
  44694. scene.resetCachedMaterial();
  44695. subMesh.setEffect(effect, defines);
  44696. this.buildUniformLayout();
  44697. }
  44698. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44699. return false;
  44700. }
  44701. defines._renderId = scene.getRenderId();
  44702. this._wasPreviouslyReady = true;
  44703. return true;
  44704. };
  44705. /**
  44706. * Specifies if the material uses metallic roughness workflow.
  44707. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44708. */
  44709. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44710. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44711. return true;
  44712. }
  44713. return false;
  44714. };
  44715. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44716. if (onCompiled === void 0) { onCompiled = null; }
  44717. if (onError === void 0) { onError = null; }
  44718. if (useInstances === void 0) { useInstances = null; }
  44719. if (useClipPlane === void 0) { useClipPlane = null; }
  44720. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44721. if (!defines.isDirty) {
  44722. return null;
  44723. }
  44724. defines.markAsProcessed();
  44725. var scene = this.getScene();
  44726. var engine = scene.getEngine();
  44727. // Fallbacks
  44728. var fallbacks = new BABYLON.EffectFallbacks();
  44729. var fallbackRank = 0;
  44730. if (defines.USESPHERICALINVERTEX) {
  44731. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44732. }
  44733. if (defines.FOG) {
  44734. fallbacks.addFallback(fallbackRank, "FOG");
  44735. }
  44736. if (defines.POINTSIZE) {
  44737. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44738. }
  44739. if (defines.LOGARITHMICDEPTH) {
  44740. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44741. }
  44742. if (defines.PARALLAX) {
  44743. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44744. }
  44745. if (defines.PARALLAXOCCLUSION) {
  44746. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44747. }
  44748. if (defines.ENVIRONMENTBRDF) {
  44749. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44750. }
  44751. if (defines.TANGENT) {
  44752. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44753. }
  44754. if (defines.BUMP) {
  44755. fallbacks.addFallback(fallbackRank++, "BUMP");
  44756. }
  44757. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44758. if (defines.SPECULARTERM) {
  44759. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44760. }
  44761. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44762. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44763. }
  44764. if (defines.LIGHTMAP) {
  44765. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44766. }
  44767. if (defines.NORMAL) {
  44768. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44769. }
  44770. if (defines.AMBIENT) {
  44771. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44772. }
  44773. if (defines.EMISSIVE) {
  44774. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44775. }
  44776. if (defines.VERTEXCOLOR) {
  44777. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44778. }
  44779. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44780. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44781. }
  44782. if (defines.MORPHTARGETS) {
  44783. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44784. }
  44785. //Attributes
  44786. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44787. if (defines.NORMAL) {
  44788. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44789. }
  44790. if (defines.TANGENT) {
  44791. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44792. }
  44793. if (defines.UV1) {
  44794. attribs.push(BABYLON.VertexBuffer.UVKind);
  44795. }
  44796. if (defines.UV2) {
  44797. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44798. }
  44799. if (defines.VERTEXCOLOR) {
  44800. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44801. }
  44802. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44803. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44804. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44805. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44806. "vFogInfos", "vFogColor", "pointSize",
  44807. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44808. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44809. "mBones",
  44810. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44811. "vLightingIntensity",
  44812. "logarithmicDepthConstant",
  44813. "vSphericalX", "vSphericalY", "vSphericalZ",
  44814. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44815. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44816. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44817. "vTangentSpaceParams"
  44818. ];
  44819. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44820. "bumpSampler", "lightmapSampler", "opacitySampler",
  44821. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44822. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44823. "microSurfaceSampler", "environmentBrdfSampler"];
  44824. var uniformBuffers = ["Material", "Scene"];
  44825. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44826. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44827. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44828. uniformsNames: uniforms,
  44829. uniformBuffersNames: uniformBuffers,
  44830. samplers: samplers,
  44831. defines: defines,
  44832. maxSimultaneousLights: this._maxSimultaneousLights
  44833. });
  44834. var join = defines.toString();
  44835. return engine.createEffect("pbr", {
  44836. attributes: attribs,
  44837. uniformsNames: uniforms,
  44838. uniformBuffersNames: uniformBuffers,
  44839. samplers: samplers,
  44840. defines: join,
  44841. fallbacks: fallbacks,
  44842. onCompiled: onCompiled,
  44843. onError: onError,
  44844. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44845. }, engine);
  44846. };
  44847. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44848. if (useInstances === void 0) { useInstances = null; }
  44849. if (useClipPlane === void 0) { useClipPlane = null; }
  44850. var scene = this.getScene();
  44851. var engine = scene.getEngine();
  44852. // Lights
  44853. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44854. defines._needNormals = true;
  44855. // Textures
  44856. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44857. if (defines._areTexturesDirty) {
  44858. defines._needUVs = false;
  44859. if (scene.texturesEnabled) {
  44860. if (scene.getEngine().getCaps().textureLOD) {
  44861. defines.LODBASEDMICROSFURACE = true;
  44862. }
  44863. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44864. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44865. }
  44866. else {
  44867. defines.ALBEDO = false;
  44868. }
  44869. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44870. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44871. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44872. }
  44873. else {
  44874. defines.AMBIENT = false;
  44875. }
  44876. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44877. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44878. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44879. }
  44880. else {
  44881. defines.OPACITY = false;
  44882. }
  44883. var reflectionTexture = this._getReflectionTexture();
  44884. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44885. defines.REFLECTION = true;
  44886. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44887. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44888. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44889. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44890. defines.INVERTCUBICMAP = true;
  44891. }
  44892. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44893. switch (reflectionTexture.coordinatesMode) {
  44894. case BABYLON.Texture.EXPLICIT_MODE:
  44895. defines.REFLECTIONMAP_EXPLICIT = true;
  44896. break;
  44897. case BABYLON.Texture.PLANAR_MODE:
  44898. defines.REFLECTIONMAP_PLANAR = true;
  44899. break;
  44900. case BABYLON.Texture.PROJECTION_MODE:
  44901. defines.REFLECTIONMAP_PROJECTION = true;
  44902. break;
  44903. case BABYLON.Texture.SKYBOX_MODE:
  44904. defines.REFLECTIONMAP_SKYBOX = true;
  44905. break;
  44906. case BABYLON.Texture.SPHERICAL_MODE:
  44907. defines.REFLECTIONMAP_SPHERICAL = true;
  44908. break;
  44909. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44910. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44911. break;
  44912. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44913. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44914. break;
  44915. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44916. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44917. break;
  44918. case BABYLON.Texture.CUBIC_MODE:
  44919. case BABYLON.Texture.INVCUBIC_MODE:
  44920. default:
  44921. defines.REFLECTIONMAP_CUBIC = true;
  44922. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44923. break;
  44924. }
  44925. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44926. if (reflectionTexture.sphericalPolynomial) {
  44927. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44928. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44929. defines.USESPHERICALINVERTEX = false;
  44930. }
  44931. else {
  44932. defines.USESPHERICALINVERTEX = true;
  44933. }
  44934. }
  44935. }
  44936. }
  44937. else {
  44938. defines.REFLECTION = false;
  44939. defines.REFLECTIONMAP_3D = false;
  44940. defines.REFLECTIONMAP_SPHERICAL = false;
  44941. defines.REFLECTIONMAP_PLANAR = false;
  44942. defines.REFLECTIONMAP_CUBIC = false;
  44943. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44944. defines.REFLECTIONMAP_PROJECTION = false;
  44945. defines.REFLECTIONMAP_SKYBOX = false;
  44946. defines.REFLECTIONMAP_EXPLICIT = false;
  44947. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44948. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44949. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44950. defines.INVERTCUBICMAP = false;
  44951. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44952. defines.USESPHERICALINVERTEX = false;
  44953. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44954. defines.LODINREFLECTIONALPHA = false;
  44955. defines.GAMMAREFLECTION = false;
  44956. }
  44957. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44958. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44959. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44960. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44961. }
  44962. else {
  44963. defines.LIGHTMAP = false;
  44964. }
  44965. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44966. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44967. }
  44968. else {
  44969. defines.EMISSIVE = false;
  44970. }
  44971. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44972. if (this._metallicTexture) {
  44973. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44974. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44975. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44976. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44977. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44978. }
  44979. else if (this._reflectivityTexture) {
  44980. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44981. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44982. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44983. }
  44984. else {
  44985. defines.REFLECTIVITY = false;
  44986. }
  44987. if (this._microSurfaceTexture) {
  44988. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44989. }
  44990. else {
  44991. defines.MICROSURFACEMAP = false;
  44992. }
  44993. }
  44994. else {
  44995. defines.REFLECTIVITY = false;
  44996. defines.MICROSURFACEMAP = false;
  44997. }
  44998. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44999. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45000. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45001. defines.PARALLAX = true;
  45002. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45003. }
  45004. else {
  45005. defines.PARALLAX = false;
  45006. }
  45007. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45008. }
  45009. else {
  45010. defines.BUMP = false;
  45011. }
  45012. var refractionTexture = this._getRefractionTexture();
  45013. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45014. defines.REFRACTION = true;
  45015. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45016. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45017. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45018. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45019. if (this._linkRefractionWithTransparency) {
  45020. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45021. }
  45022. }
  45023. else {
  45024. defines.REFRACTION = false;
  45025. }
  45026. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45027. defines.ENVIRONMENTBRDF = true;
  45028. }
  45029. else {
  45030. defines.ENVIRONMENTBRDF = false;
  45031. }
  45032. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45033. defines.ALPHAFROMALBEDO = true;
  45034. }
  45035. else {
  45036. defines.ALPHAFROMALBEDO = false;
  45037. }
  45038. }
  45039. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45040. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45041. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45042. if (!this.backFaceCulling && this._twoSidedLighting) {
  45043. defines.TWOSIDEDLIGHTING = true;
  45044. }
  45045. else {
  45046. defines.TWOSIDEDLIGHTING = false;
  45047. }
  45048. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45049. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45050. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45051. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45052. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45053. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45054. }
  45055. if (defines._areImageProcessingDirty) {
  45056. this._imageProcessingConfiguration.prepareDefines(defines);
  45057. }
  45058. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45059. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45060. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45061. // Misc.
  45062. if (defines._areMiscDirty) {
  45063. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45064. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45065. }
  45066. // Values that need to be evaluated on every frame
  45067. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45068. // Attribs
  45069. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45070. };
  45071. /**
  45072. * Force shader compilation
  45073. */
  45074. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45075. var _this = this;
  45076. var localOptions = __assign({ clipPlane: false }, options);
  45077. var defines = new PBRMaterialDefines();
  45078. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45079. if (effect.isReady()) {
  45080. if (onCompiled) {
  45081. onCompiled(this);
  45082. }
  45083. }
  45084. else {
  45085. effect.onCompileObservable.add(function () {
  45086. if (onCompiled) {
  45087. onCompiled(_this);
  45088. }
  45089. });
  45090. }
  45091. };
  45092. /**
  45093. * Initializes the uniform buffer layout for the shader.
  45094. */
  45095. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45096. // Order is important !
  45097. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45098. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45099. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45100. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45101. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45102. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45103. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45104. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45105. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45106. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45107. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45108. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45109. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45110. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45111. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45112. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45113. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45114. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45115. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45116. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45117. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45118. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45119. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45120. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45121. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45122. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45123. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45124. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45125. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45126. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45127. this._uniformBuffer.addUniform("pointSize", 1);
  45128. this._uniformBuffer.create();
  45129. };
  45130. /**
  45131. * Unbinds the textures.
  45132. */
  45133. PBRBaseMaterial.prototype.unbind = function () {
  45134. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45135. this._uniformBuffer.setTexture("reflectionSampler", null);
  45136. }
  45137. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45138. this._uniformBuffer.setTexture("refractionSampler", null);
  45139. }
  45140. _super.prototype.unbind.call(this);
  45141. };
  45142. /**
  45143. * Binds the submesh data.
  45144. * @param world - The world matrix.
  45145. * @param mesh - The BJS mesh.
  45146. * @param subMesh - A submesh of the BJS mesh.
  45147. */
  45148. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45149. var scene = this.getScene();
  45150. var defines = subMesh._materialDefines;
  45151. if (!defines) {
  45152. return;
  45153. }
  45154. var effect = subMesh.effect;
  45155. if (!effect) {
  45156. return;
  45157. }
  45158. this._activeEffect = effect;
  45159. // Matrices
  45160. this.bindOnlyWorldMatrix(world);
  45161. // Normal Matrix
  45162. if (defines.OBJECTSPACE_NORMALMAP) {
  45163. world.toNormalMatrix(this._normalMatrix);
  45164. this.bindOnlyNormalMatrix(this._normalMatrix);
  45165. }
  45166. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45167. // Bones
  45168. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45169. var reflectionTexture = null;
  45170. if (mustRebind) {
  45171. this._uniformBuffer.bindToEffect(effect, "Material");
  45172. this.bindViewProjection(effect);
  45173. reflectionTexture = this._getReflectionTexture();
  45174. var refractionTexture = this._getRefractionTexture();
  45175. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45176. // Texture uniforms
  45177. if (scene.texturesEnabled) {
  45178. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45179. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45180. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45181. }
  45182. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45183. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45184. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45185. }
  45186. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45187. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45188. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45189. }
  45190. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45191. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45192. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45193. if (reflectionTexture.boundingBoxSize) {
  45194. var cubeTexture = reflectionTexture;
  45195. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45196. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45197. }
  45198. var polynomials = reflectionTexture.sphericalPolynomial;
  45199. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45200. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45201. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45202. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45203. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45204. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45205. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45206. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45207. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45208. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45209. }
  45210. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45211. }
  45212. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45213. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45214. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45215. }
  45216. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45217. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45218. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45219. }
  45220. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45221. if (this._metallicTexture) {
  45222. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45223. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45224. }
  45225. else if (this._reflectivityTexture) {
  45226. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45227. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45228. }
  45229. if (this._microSurfaceTexture) {
  45230. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45231. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45232. }
  45233. }
  45234. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45235. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45236. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45237. if (scene._mirroredCameraPosition) {
  45238. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45239. }
  45240. else {
  45241. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45242. }
  45243. }
  45244. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45245. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45246. var depth = 1.0;
  45247. if (!refractionTexture.isCube) {
  45248. if (refractionTexture.depth) {
  45249. depth = refractionTexture.depth;
  45250. }
  45251. }
  45252. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45253. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45254. }
  45255. }
  45256. // Point size
  45257. if (this.pointsCloud) {
  45258. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45259. }
  45260. // Colors
  45261. if (defines.METALLICWORKFLOW) {
  45262. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45263. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45264. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45265. }
  45266. else {
  45267. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45268. }
  45269. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45270. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45271. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45272. // Misc
  45273. this._lightingInfos.x = this._directIntensity;
  45274. this._lightingInfos.y = this._emissiveIntensity;
  45275. this._lightingInfos.z = this._environmentIntensity;
  45276. this._lightingInfos.w = this._specularIntensity;
  45277. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45278. }
  45279. // Textures
  45280. if (scene.texturesEnabled) {
  45281. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45282. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45283. }
  45284. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45285. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45286. }
  45287. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45288. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45289. }
  45290. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45291. if (defines.LODBASEDMICROSFURACE) {
  45292. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45293. }
  45294. else {
  45295. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45296. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45297. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45298. }
  45299. }
  45300. if (defines.ENVIRONMENTBRDF) {
  45301. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45302. }
  45303. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45304. if (defines.LODBASEDMICROSFURACE) {
  45305. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45306. }
  45307. else {
  45308. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45309. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45310. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45311. }
  45312. }
  45313. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45314. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45315. }
  45316. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45317. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45318. }
  45319. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45320. if (this._metallicTexture) {
  45321. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45322. }
  45323. else if (this._reflectivityTexture) {
  45324. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45325. }
  45326. if (this._microSurfaceTexture) {
  45327. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45328. }
  45329. }
  45330. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45331. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45332. }
  45333. }
  45334. // Clip plane
  45335. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45336. // Colors
  45337. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45338. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45339. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45340. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45341. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45342. }
  45343. if (mustRebind || !this.isFrozen) {
  45344. // Lights
  45345. if (scene.lightsEnabled && !this._disableLighting) {
  45346. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45347. }
  45348. // View
  45349. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45350. this.bindView(effect);
  45351. }
  45352. // Fog
  45353. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45354. // Morph targets
  45355. if (defines.NUM_MORPH_INFLUENCERS) {
  45356. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45357. }
  45358. // image processing
  45359. this._imageProcessingConfiguration.bind(this._activeEffect);
  45360. // Log. depth
  45361. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45362. }
  45363. this._uniformBuffer.update();
  45364. this._afterBind(mesh);
  45365. };
  45366. /**
  45367. * Returns the animatable textures.
  45368. * @returns - Array of animatable textures.
  45369. */
  45370. PBRBaseMaterial.prototype.getAnimatables = function () {
  45371. var results = [];
  45372. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45373. results.push(this._albedoTexture);
  45374. }
  45375. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45376. results.push(this._ambientTexture);
  45377. }
  45378. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45379. results.push(this._opacityTexture);
  45380. }
  45381. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45382. results.push(this._reflectionTexture);
  45383. }
  45384. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45385. results.push(this._emissiveTexture);
  45386. }
  45387. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45388. results.push(this._metallicTexture);
  45389. }
  45390. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45391. results.push(this._reflectivityTexture);
  45392. }
  45393. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45394. results.push(this._bumpTexture);
  45395. }
  45396. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45397. results.push(this._lightmapTexture);
  45398. }
  45399. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45400. results.push(this._refractionTexture);
  45401. }
  45402. return results;
  45403. };
  45404. /**
  45405. * Returns the texture used for reflections.
  45406. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45407. */
  45408. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45409. if (this._reflectionTexture) {
  45410. return this._reflectionTexture;
  45411. }
  45412. return this.getScene().environmentTexture;
  45413. };
  45414. /**
  45415. * Returns the texture used for refraction or null if none is used.
  45416. * @returns - Refection texture if present. If no refraction texture and refraction
  45417. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45418. */
  45419. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45420. if (this._refractionTexture) {
  45421. return this._refractionTexture;
  45422. }
  45423. if (this._linkRefractionWithTransparency) {
  45424. return this.getScene().environmentTexture;
  45425. }
  45426. return null;
  45427. };
  45428. /**
  45429. * Disposes the resources of the material.
  45430. * @param forceDisposeEffect - Forces the disposal of effects.
  45431. * @param forceDisposeTextures - Forces the disposal of all textures.
  45432. */
  45433. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45434. if (forceDisposeTextures) {
  45435. if (this._albedoTexture) {
  45436. this._albedoTexture.dispose();
  45437. }
  45438. if (this._ambientTexture) {
  45439. this._ambientTexture.dispose();
  45440. }
  45441. if (this._opacityTexture) {
  45442. this._opacityTexture.dispose();
  45443. }
  45444. if (this._reflectionTexture) {
  45445. this._reflectionTexture.dispose();
  45446. }
  45447. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45448. this._environmentBRDFTexture.dispose();
  45449. }
  45450. if (this._emissiveTexture) {
  45451. this._emissiveTexture.dispose();
  45452. }
  45453. if (this._metallicTexture) {
  45454. this._metallicTexture.dispose();
  45455. }
  45456. if (this._reflectivityTexture) {
  45457. this._reflectivityTexture.dispose();
  45458. }
  45459. if (this._bumpTexture) {
  45460. this._bumpTexture.dispose();
  45461. }
  45462. if (this._lightmapTexture) {
  45463. this._lightmapTexture.dispose();
  45464. }
  45465. if (this._refractionTexture) {
  45466. this._refractionTexture.dispose();
  45467. }
  45468. }
  45469. this._renderTargets.dispose();
  45470. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45471. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45472. }
  45473. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45474. };
  45475. /**
  45476. * Stores the reflectivity values based on metallic roughness workflow.
  45477. */
  45478. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45479. __decorate([
  45480. BABYLON.serializeAsImageProcessingConfiguration()
  45481. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45482. __decorate([
  45483. BABYLON.serialize()
  45484. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45485. __decorate([
  45486. BABYLON.serialize()
  45487. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45488. return PBRBaseMaterial;
  45489. }(BABYLON.PushMaterial));
  45490. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45491. })(BABYLON || (BABYLON = {}));
  45492. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45493. var BABYLON;
  45494. (function (BABYLON) {
  45495. /**
  45496. * The Physically based simple base material of BJS.
  45497. *
  45498. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45499. * It is used as the base class for both the specGloss and metalRough conventions.
  45500. */
  45501. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45502. __extends(PBRBaseSimpleMaterial, _super);
  45503. /**
  45504. * Instantiates a new PBRMaterial instance.
  45505. *
  45506. * @param name The material name
  45507. * @param scene The scene the material will be use in.
  45508. */
  45509. function PBRBaseSimpleMaterial(name, scene) {
  45510. var _this = _super.call(this, name, scene) || this;
  45511. /**
  45512. * Number of Simultaneous lights allowed on the material.
  45513. */
  45514. _this.maxSimultaneousLights = 4;
  45515. /**
  45516. * If sets to true, disables all the lights affecting the material.
  45517. */
  45518. _this.disableLighting = false;
  45519. /**
  45520. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45521. */
  45522. _this.invertNormalMapX = false;
  45523. /**
  45524. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45525. */
  45526. _this.invertNormalMapY = false;
  45527. /**
  45528. * Emissivie color used to self-illuminate the model.
  45529. */
  45530. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45531. /**
  45532. * Occlusion Channel Strenght.
  45533. */
  45534. _this.occlusionStrength = 1.0;
  45535. _this.useLightmapAsShadowmap = false;
  45536. _this._useAlphaFromAlbedoTexture = true;
  45537. _this._useAmbientInGrayScale = true;
  45538. return _this;
  45539. }
  45540. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45541. /**
  45542. * Gets the current double sided mode.
  45543. */
  45544. get: function () {
  45545. return this._twoSidedLighting;
  45546. },
  45547. /**
  45548. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45549. */
  45550. set: function (value) {
  45551. if (this._twoSidedLighting === value) {
  45552. return;
  45553. }
  45554. this._twoSidedLighting = value;
  45555. this.backFaceCulling = !value;
  45556. this._markAllSubMeshesAsTexturesDirty();
  45557. },
  45558. enumerable: true,
  45559. configurable: true
  45560. });
  45561. /**
  45562. * Return the active textures of the material.
  45563. */
  45564. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45565. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45566. if (this.environmentTexture) {
  45567. activeTextures.push(this.environmentTexture);
  45568. }
  45569. if (this.normalTexture) {
  45570. activeTextures.push(this.normalTexture);
  45571. }
  45572. if (this.emissiveTexture) {
  45573. activeTextures.push(this.emissiveTexture);
  45574. }
  45575. if (this.occlusionTexture) {
  45576. activeTextures.push(this.occlusionTexture);
  45577. }
  45578. if (this.lightmapTexture) {
  45579. activeTextures.push(this.lightmapTexture);
  45580. }
  45581. return activeTextures;
  45582. };
  45583. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45584. if (_super.prototype.hasTexture.call(this, texture)) {
  45585. return true;
  45586. }
  45587. if (this.lightmapTexture === texture) {
  45588. return true;
  45589. }
  45590. return false;
  45591. };
  45592. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45593. return "PBRBaseSimpleMaterial";
  45594. };
  45595. __decorate([
  45596. BABYLON.serialize(),
  45597. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45598. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45599. __decorate([
  45600. BABYLON.serialize(),
  45601. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45602. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45603. __decorate([
  45604. BABYLON.serializeAsTexture(),
  45605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45606. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45607. __decorate([
  45608. BABYLON.serialize(),
  45609. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45610. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45611. __decorate([
  45612. BABYLON.serialize(),
  45613. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45614. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45615. __decorate([
  45616. BABYLON.serializeAsTexture(),
  45617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45618. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45619. __decorate([
  45620. BABYLON.serializeAsColor3("emissive"),
  45621. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45622. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45623. __decorate([
  45624. BABYLON.serializeAsTexture(),
  45625. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45626. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45627. __decorate([
  45628. BABYLON.serialize(),
  45629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45630. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45631. __decorate([
  45632. BABYLON.serializeAsTexture(),
  45633. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45634. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45635. __decorate([
  45636. BABYLON.serialize(),
  45637. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45638. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45639. __decorate([
  45640. BABYLON.serialize()
  45641. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45642. __decorate([
  45643. BABYLON.serializeAsTexture(),
  45644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45645. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45646. __decorate([
  45647. BABYLON.serialize(),
  45648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45649. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45650. return PBRBaseSimpleMaterial;
  45651. }(BABYLON.PBRBaseMaterial));
  45652. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45653. })(BABYLON || (BABYLON = {}));
  45654. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45655. var BABYLON;
  45656. (function (BABYLON) {
  45657. /**
  45658. * The Physically based material of BJS.
  45659. *
  45660. * This offers the main features of a standard PBR material.
  45661. * For more information, please refer to the documentation :
  45662. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45663. */
  45664. var PBRMaterial = /** @class */ (function (_super) {
  45665. __extends(PBRMaterial, _super);
  45666. /**
  45667. * Instantiates a new PBRMaterial instance.
  45668. *
  45669. * @param name The material name
  45670. * @param scene The scene the material will be use in.
  45671. */
  45672. function PBRMaterial(name, scene) {
  45673. var _this = _super.call(this, name, scene) || this;
  45674. /**
  45675. * Intensity of the direct lights e.g. the four lights available in your scene.
  45676. * This impacts both the direct diffuse and specular highlights.
  45677. */
  45678. _this.directIntensity = 1.0;
  45679. /**
  45680. * Intensity of the emissive part of the material.
  45681. * This helps controlling the emissive effect without modifying the emissive color.
  45682. */
  45683. _this.emissiveIntensity = 1.0;
  45684. /**
  45685. * Intensity of the environment e.g. how much the environment will light the object
  45686. * either through harmonics for rough material or through the refelction for shiny ones.
  45687. */
  45688. _this.environmentIntensity = 1.0;
  45689. /**
  45690. * This is a special control allowing the reduction of the specular highlights coming from the
  45691. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45692. */
  45693. _this.specularIntensity = 1.0;
  45694. /**
  45695. * Debug Control allowing disabling the bump map on this material.
  45696. */
  45697. _this.disableBumpMap = false;
  45698. /**
  45699. * AKA Occlusion Texture Intensity in other nomenclature.
  45700. */
  45701. _this.ambientTextureStrength = 1.0;
  45702. /**
  45703. * The color of a material in ambient lighting.
  45704. */
  45705. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45706. /**
  45707. * AKA Diffuse Color in other nomenclature.
  45708. */
  45709. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45710. /**
  45711. * AKA Specular Color in other nomenclature.
  45712. */
  45713. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45714. /**
  45715. * The color reflected from the material.
  45716. */
  45717. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45718. /**
  45719. * The color emitted from the material.
  45720. */
  45721. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45722. /**
  45723. * AKA Glossiness in other nomenclature.
  45724. */
  45725. _this.microSurface = 1.0;
  45726. /**
  45727. * source material index of refraction (IOR)' / 'destination material IOR.
  45728. */
  45729. _this.indexOfRefraction = 0.66;
  45730. /**
  45731. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45732. */
  45733. _this.invertRefractionY = false;
  45734. /**
  45735. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45736. * Materials half opaque for instance using refraction could benefit from this control.
  45737. */
  45738. _this.linkRefractionWithTransparency = false;
  45739. _this.useLightmapAsShadowmap = false;
  45740. /**
  45741. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45742. */
  45743. _this.useAlphaFromAlbedoTexture = false;
  45744. /**
  45745. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45746. */
  45747. _this.forceAlphaTest = false;
  45748. /**
  45749. * Defines the alpha limits in alpha test mode.
  45750. */
  45751. _this.alphaCutOff = 0.4;
  45752. /**
  45753. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45754. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45755. */
  45756. _this.useSpecularOverAlpha = true;
  45757. /**
  45758. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45759. */
  45760. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45761. /**
  45762. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45763. */
  45764. _this.useRoughnessFromMetallicTextureAlpha = true;
  45765. /**
  45766. * Specifies if the metallic texture contains the roughness information in its green channel.
  45767. */
  45768. _this.useRoughnessFromMetallicTextureGreen = false;
  45769. /**
  45770. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45771. */
  45772. _this.useMetallnessFromMetallicTextureBlue = false;
  45773. /**
  45774. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45775. */
  45776. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45777. /**
  45778. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45779. */
  45780. _this.useAmbientInGrayScale = false;
  45781. /**
  45782. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45783. * The material will try to infer what glossiness each pixel should be.
  45784. */
  45785. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45786. /**
  45787. * BJS is using an harcoded light falloff based on a manually sets up range.
  45788. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45789. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45790. */
  45791. _this.usePhysicalLightFalloff = true;
  45792. /**
  45793. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45794. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45795. */
  45796. _this.useRadianceOverAlpha = true;
  45797. /**
  45798. * Allows using an object space normal map (instead of tangent space).
  45799. */
  45800. _this.useObjectSpaceNormalMap = false;
  45801. /**
  45802. * Allows using the bump map in parallax mode.
  45803. */
  45804. _this.useParallax = false;
  45805. /**
  45806. * Allows using the bump map in parallax occlusion mode.
  45807. */
  45808. _this.useParallaxOcclusion = false;
  45809. /**
  45810. * Controls the scale bias of the parallax mode.
  45811. */
  45812. _this.parallaxScaleBias = 0.05;
  45813. /**
  45814. * If sets to true, disables all the lights affecting the material.
  45815. */
  45816. _this.disableLighting = false;
  45817. /**
  45818. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45819. */
  45820. _this.forceIrradianceInFragment = false;
  45821. /**
  45822. * Number of Simultaneous lights allowed on the material.
  45823. */
  45824. _this.maxSimultaneousLights = 4;
  45825. /**
  45826. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45827. */
  45828. _this.invertNormalMapX = false;
  45829. /**
  45830. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45831. */
  45832. _this.invertNormalMapY = false;
  45833. /**
  45834. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45835. */
  45836. _this.twoSidedLighting = false;
  45837. /**
  45838. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45839. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45840. */
  45841. _this.useAlphaFresnel = false;
  45842. /**
  45843. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45844. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45845. */
  45846. _this.useLinearAlphaFresnel = false;
  45847. /**
  45848. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45849. * And/Or occlude the blended part.
  45850. */
  45851. _this.environmentBRDFTexture = null;
  45852. /**
  45853. * Force normal to face away from face.
  45854. */
  45855. _this.forceNormalForward = false;
  45856. /**
  45857. * Enables specular anti aliasing in the PBR shader.
  45858. * It will both interacts on the Geometry for analytical and IBL lighting.
  45859. * It also prefilter the roughness map based on the bump values.
  45860. */
  45861. _this.enableSpecularAntiAliasing = false;
  45862. /**
  45863. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45864. * makes the reflect vector face the model (under horizon).
  45865. */
  45866. _this.useHorizonOcclusion = true;
  45867. /**
  45868. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45869. * too much the area relying on ambient texture to define their ambient occlusion.
  45870. */
  45871. _this.useRadianceOcclusion = true;
  45872. /**
  45873. * If set to true, no lighting calculations will be applied.
  45874. */
  45875. _this.unlit = false;
  45876. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45877. return _this;
  45878. }
  45879. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45880. /**
  45881. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45882. */
  45883. get: function () {
  45884. return this._PBRMATERIAL_OPAQUE;
  45885. },
  45886. enumerable: true,
  45887. configurable: true
  45888. });
  45889. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45890. /**
  45891. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45892. */
  45893. get: function () {
  45894. return this._PBRMATERIAL_ALPHATEST;
  45895. },
  45896. enumerable: true,
  45897. configurable: true
  45898. });
  45899. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45900. /**
  45901. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45902. */
  45903. get: function () {
  45904. return this._PBRMATERIAL_ALPHABLEND;
  45905. },
  45906. enumerable: true,
  45907. configurable: true
  45908. });
  45909. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45910. /**
  45911. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45912. * They are also discarded below the alpha cutoff threshold to improve performances.
  45913. */
  45914. get: function () {
  45915. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45916. },
  45917. enumerable: true,
  45918. configurable: true
  45919. });
  45920. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45921. /**
  45922. * Gets the image processing configuration used either in this material.
  45923. */
  45924. get: function () {
  45925. return this._imageProcessingConfiguration;
  45926. },
  45927. /**
  45928. * Sets the Default image processing configuration used either in the this material.
  45929. *
  45930. * If sets to null, the scene one is in use.
  45931. */
  45932. set: function (value) {
  45933. this._attachImageProcessingConfiguration(value);
  45934. // Ensure the effect will be rebuilt.
  45935. this._markAllSubMeshesAsTexturesDirty();
  45936. },
  45937. enumerable: true,
  45938. configurable: true
  45939. });
  45940. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45941. /**
  45942. * Gets wether the color curves effect is enabled.
  45943. */
  45944. get: function () {
  45945. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45946. },
  45947. /**
  45948. * Sets wether the color curves effect is enabled.
  45949. */
  45950. set: function (value) {
  45951. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45952. },
  45953. enumerable: true,
  45954. configurable: true
  45955. });
  45956. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45957. /**
  45958. * Gets wether the color grading effect is enabled.
  45959. */
  45960. get: function () {
  45961. return this.imageProcessingConfiguration.colorGradingEnabled;
  45962. },
  45963. /**
  45964. * Gets wether the color grading effect is enabled.
  45965. */
  45966. set: function (value) {
  45967. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45968. },
  45969. enumerable: true,
  45970. configurable: true
  45971. });
  45972. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45973. /**
  45974. * Gets wether tonemapping is enabled or not.
  45975. */
  45976. get: function () {
  45977. return this._imageProcessingConfiguration.toneMappingEnabled;
  45978. },
  45979. /**
  45980. * Sets wether tonemapping is enabled or not
  45981. */
  45982. set: function (value) {
  45983. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45984. },
  45985. enumerable: true,
  45986. configurable: true
  45987. });
  45988. ;
  45989. ;
  45990. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45991. /**
  45992. * The camera exposure used on this material.
  45993. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45994. * This corresponds to a photographic exposure.
  45995. */
  45996. get: function () {
  45997. return this._imageProcessingConfiguration.exposure;
  45998. },
  45999. /**
  46000. * The camera exposure used on this material.
  46001. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46002. * This corresponds to a photographic exposure.
  46003. */
  46004. set: function (value) {
  46005. this._imageProcessingConfiguration.exposure = value;
  46006. },
  46007. enumerable: true,
  46008. configurable: true
  46009. });
  46010. ;
  46011. ;
  46012. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46013. /**
  46014. * Gets The camera contrast used on this material.
  46015. */
  46016. get: function () {
  46017. return this._imageProcessingConfiguration.contrast;
  46018. },
  46019. /**
  46020. * Sets The camera contrast used on this material.
  46021. */
  46022. set: function (value) {
  46023. this._imageProcessingConfiguration.contrast = value;
  46024. },
  46025. enumerable: true,
  46026. configurable: true
  46027. });
  46028. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46029. /**
  46030. * Gets the Color Grading 2D Lookup Texture.
  46031. */
  46032. get: function () {
  46033. return this._imageProcessingConfiguration.colorGradingTexture;
  46034. },
  46035. /**
  46036. * Sets the Color Grading 2D Lookup Texture.
  46037. */
  46038. set: function (value) {
  46039. this._imageProcessingConfiguration.colorGradingTexture = value;
  46040. },
  46041. enumerable: true,
  46042. configurable: true
  46043. });
  46044. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46045. /**
  46046. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46047. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46048. * 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;
  46049. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46050. */
  46051. get: function () {
  46052. return this._imageProcessingConfiguration.colorCurves;
  46053. },
  46054. /**
  46055. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46056. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46057. * 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;
  46058. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46059. */
  46060. set: function (value) {
  46061. this._imageProcessingConfiguration.colorCurves = value;
  46062. },
  46063. enumerable: true,
  46064. configurable: true
  46065. });
  46066. /**
  46067. * Returns the name of this material class.
  46068. */
  46069. PBRMaterial.prototype.getClassName = function () {
  46070. return "PBRMaterial";
  46071. };
  46072. /**
  46073. * Returns an array of the actively used textures.
  46074. * @returns - Array of BaseTextures
  46075. */
  46076. PBRMaterial.prototype.getActiveTextures = function () {
  46077. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46078. if (this._albedoTexture) {
  46079. activeTextures.push(this._albedoTexture);
  46080. }
  46081. if (this._ambientTexture) {
  46082. activeTextures.push(this._ambientTexture);
  46083. }
  46084. if (this._opacityTexture) {
  46085. activeTextures.push(this._opacityTexture);
  46086. }
  46087. if (this._reflectionTexture) {
  46088. activeTextures.push(this._reflectionTexture);
  46089. }
  46090. if (this._emissiveTexture) {
  46091. activeTextures.push(this._emissiveTexture);
  46092. }
  46093. if (this._reflectivityTexture) {
  46094. activeTextures.push(this._reflectivityTexture);
  46095. }
  46096. if (this._metallicTexture) {
  46097. activeTextures.push(this._metallicTexture);
  46098. }
  46099. if (this._microSurfaceTexture) {
  46100. activeTextures.push(this._microSurfaceTexture);
  46101. }
  46102. if (this._bumpTexture) {
  46103. activeTextures.push(this._bumpTexture);
  46104. }
  46105. if (this._lightmapTexture) {
  46106. activeTextures.push(this._lightmapTexture);
  46107. }
  46108. if (this._refractionTexture) {
  46109. activeTextures.push(this._refractionTexture);
  46110. }
  46111. return activeTextures;
  46112. };
  46113. /**
  46114. * Checks to see if a texture is used in the material.
  46115. * @param texture - Base texture to use.
  46116. * @returns - Boolean specifying if a texture is used in the material.
  46117. */
  46118. PBRMaterial.prototype.hasTexture = function (texture) {
  46119. if (_super.prototype.hasTexture.call(this, texture)) {
  46120. return true;
  46121. }
  46122. if (this._albedoTexture === texture) {
  46123. return true;
  46124. }
  46125. if (this._ambientTexture === texture) {
  46126. return true;
  46127. }
  46128. if (this._opacityTexture === texture) {
  46129. return true;
  46130. }
  46131. if (this._reflectionTexture === texture) {
  46132. return true;
  46133. }
  46134. if (this._reflectivityTexture === texture) {
  46135. return true;
  46136. }
  46137. if (this._metallicTexture === texture) {
  46138. return true;
  46139. }
  46140. if (this._microSurfaceTexture === texture) {
  46141. return true;
  46142. }
  46143. if (this._bumpTexture === texture) {
  46144. return true;
  46145. }
  46146. if (this._lightmapTexture === texture) {
  46147. return true;
  46148. }
  46149. if (this._refractionTexture === texture) {
  46150. return true;
  46151. }
  46152. return false;
  46153. };
  46154. /**
  46155. * Makes a duplicate of the current material.
  46156. * @param name - name to use for the new material.
  46157. */
  46158. PBRMaterial.prototype.clone = function (name) {
  46159. var _this = this;
  46160. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46161. clone.id = name;
  46162. clone.name = name;
  46163. return clone;
  46164. };
  46165. /**
  46166. * Serializes this PBR Material.
  46167. * @returns - An object with the serialized material.
  46168. */
  46169. PBRMaterial.prototype.serialize = function () {
  46170. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46171. serializationObject.customType = "BABYLON.PBRMaterial";
  46172. return serializationObject;
  46173. };
  46174. // Statics
  46175. /**
  46176. * Parses a PBR Material from a serialized object.
  46177. * @param source - Serialized object.
  46178. * @param scene - BJS scene instance.
  46179. * @param rootUrl - url for the scene object
  46180. * @returns - PBRMaterial
  46181. */
  46182. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46183. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46184. };
  46185. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46186. /**
  46187. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46188. */
  46189. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46190. /**
  46191. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46192. */
  46193. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46194. /**
  46195. * 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.
  46196. * They are also discarded below the alpha cutoff threshold to improve performances.
  46197. */
  46198. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46199. __decorate([
  46200. BABYLON.serialize(),
  46201. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46202. ], PBRMaterial.prototype, "directIntensity", void 0);
  46203. __decorate([
  46204. BABYLON.serialize(),
  46205. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46206. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46207. __decorate([
  46208. BABYLON.serialize(),
  46209. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46210. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46211. __decorate([
  46212. BABYLON.serialize(),
  46213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46214. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46215. __decorate([
  46216. BABYLON.serialize(),
  46217. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46218. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46219. __decorate([
  46220. BABYLON.serializeAsTexture(),
  46221. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46222. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46223. __decorate([
  46224. BABYLON.serializeAsTexture(),
  46225. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46226. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46227. __decorate([
  46228. BABYLON.serialize(),
  46229. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46230. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46231. __decorate([
  46232. BABYLON.serializeAsTexture(),
  46233. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46234. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46235. __decorate([
  46236. BABYLON.serializeAsTexture(),
  46237. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46238. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46239. __decorate([
  46240. BABYLON.serializeAsTexture(),
  46241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46242. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46243. __decorate([
  46244. BABYLON.serializeAsTexture(),
  46245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46246. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46247. __decorate([
  46248. BABYLON.serializeAsTexture(),
  46249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46250. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46251. __decorate([
  46252. BABYLON.serialize(),
  46253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46254. ], PBRMaterial.prototype, "metallic", void 0);
  46255. __decorate([
  46256. BABYLON.serialize(),
  46257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46258. ], PBRMaterial.prototype, "roughness", void 0);
  46259. __decorate([
  46260. BABYLON.serializeAsTexture(),
  46261. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46262. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46263. __decorate([
  46264. BABYLON.serializeAsTexture(),
  46265. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46266. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46267. __decorate([
  46268. BABYLON.serializeAsTexture(),
  46269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46270. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46271. __decorate([
  46272. BABYLON.serializeAsTexture(),
  46273. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46274. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46275. __decorate([
  46276. BABYLON.serializeAsColor3("ambient"),
  46277. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46278. ], PBRMaterial.prototype, "ambientColor", void 0);
  46279. __decorate([
  46280. BABYLON.serializeAsColor3("albedo"),
  46281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46282. ], PBRMaterial.prototype, "albedoColor", void 0);
  46283. __decorate([
  46284. BABYLON.serializeAsColor3("reflectivity"),
  46285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46286. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46287. __decorate([
  46288. BABYLON.serializeAsColor3("reflection"),
  46289. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46290. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46291. __decorate([
  46292. BABYLON.serializeAsColor3("emissive"),
  46293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46294. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46295. __decorate([
  46296. BABYLON.serialize(),
  46297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46298. ], PBRMaterial.prototype, "microSurface", void 0);
  46299. __decorate([
  46300. BABYLON.serialize(),
  46301. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46302. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46303. __decorate([
  46304. BABYLON.serialize(),
  46305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46306. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46307. __decorate([
  46308. BABYLON.serialize(),
  46309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46310. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46311. __decorate([
  46312. BABYLON.serialize(),
  46313. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46314. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46315. __decorate([
  46316. BABYLON.serialize(),
  46317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46318. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46319. __decorate([
  46320. BABYLON.serialize(),
  46321. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46322. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46323. __decorate([
  46324. BABYLON.serialize(),
  46325. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46326. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46327. __decorate([
  46328. BABYLON.serialize(),
  46329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46330. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46331. __decorate([
  46332. BABYLON.serialize(),
  46333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46334. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46335. __decorate([
  46336. BABYLON.serialize(),
  46337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46338. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46339. __decorate([
  46340. BABYLON.serialize(),
  46341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46342. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46343. __decorate([
  46344. BABYLON.serialize(),
  46345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46346. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46347. __decorate([
  46348. BABYLON.serialize(),
  46349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46350. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46351. __decorate([
  46352. BABYLON.serialize(),
  46353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46354. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46355. __decorate([
  46356. BABYLON.serialize(),
  46357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46358. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46359. __decorate([
  46360. BABYLON.serialize(),
  46361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46362. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46363. __decorate([
  46364. BABYLON.serialize(),
  46365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46366. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46367. __decorate([
  46368. BABYLON.serialize(),
  46369. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46370. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46371. __decorate([
  46372. BABYLON.serialize(),
  46373. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46374. ], PBRMaterial.prototype, "useParallax", void 0);
  46375. __decorate([
  46376. BABYLON.serialize(),
  46377. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46378. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46379. __decorate([
  46380. BABYLON.serialize(),
  46381. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46382. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46383. __decorate([
  46384. BABYLON.serialize(),
  46385. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46386. ], PBRMaterial.prototype, "disableLighting", void 0);
  46387. __decorate([
  46388. BABYLON.serialize(),
  46389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46390. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46391. __decorate([
  46392. BABYLON.serialize(),
  46393. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46394. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46395. __decorate([
  46396. BABYLON.serialize(),
  46397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46398. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46399. __decorate([
  46400. BABYLON.serialize(),
  46401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46402. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46403. __decorate([
  46404. BABYLON.serialize(),
  46405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46406. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46407. __decorate([
  46408. BABYLON.serialize(),
  46409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46410. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46411. __decorate([
  46412. BABYLON.serialize(),
  46413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46414. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46415. __decorate([
  46416. BABYLON.serializeAsTexture(),
  46417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46418. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46419. __decorate([
  46420. BABYLON.serialize(),
  46421. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46422. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46423. __decorate([
  46424. BABYLON.serialize(),
  46425. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46426. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46427. __decorate([
  46428. BABYLON.serialize(),
  46429. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46430. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46431. __decorate([
  46432. BABYLON.serialize(),
  46433. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46434. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46435. __decorate([
  46436. BABYLON.serialize(),
  46437. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46438. ], PBRMaterial.prototype, "unlit", void 0);
  46439. return PBRMaterial;
  46440. }(BABYLON.PBRBaseMaterial));
  46441. BABYLON.PBRMaterial = PBRMaterial;
  46442. })(BABYLON || (BABYLON = {}));
  46443. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46444. var BABYLON;
  46445. (function (BABYLON) {
  46446. /**
  46447. * The PBR material of BJS following the metal roughness convention.
  46448. *
  46449. * This fits to the PBR convention in the GLTF definition:
  46450. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46451. */
  46452. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46453. __extends(PBRMetallicRoughnessMaterial, _super);
  46454. /**
  46455. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46456. *
  46457. * @param name The material name
  46458. * @param scene The scene the material will be use in.
  46459. */
  46460. function PBRMetallicRoughnessMaterial(name, scene) {
  46461. var _this = _super.call(this, name, scene) || this;
  46462. _this._useRoughnessFromMetallicTextureAlpha = false;
  46463. _this._useRoughnessFromMetallicTextureGreen = true;
  46464. _this._useMetallnessFromMetallicTextureBlue = true;
  46465. _this.metallic = 1.0;
  46466. _this.roughness = 1.0;
  46467. return _this;
  46468. }
  46469. /**
  46470. * Return the currrent class name of the material.
  46471. */
  46472. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46473. return "PBRMetallicRoughnessMaterial";
  46474. };
  46475. /**
  46476. * Return the active textures of the material.
  46477. */
  46478. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46479. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46480. if (this.baseTexture) {
  46481. activeTextures.push(this.baseTexture);
  46482. }
  46483. if (this.metallicRoughnessTexture) {
  46484. activeTextures.push(this.metallicRoughnessTexture);
  46485. }
  46486. return activeTextures;
  46487. };
  46488. /**
  46489. * Checks to see if a texture is used in the material.
  46490. * @param texture - Base texture to use.
  46491. * @returns - Boolean specifying if a texture is used in the material.
  46492. */
  46493. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46494. if (_super.prototype.hasTexture.call(this, texture)) {
  46495. return true;
  46496. }
  46497. if (this.baseTexture === texture) {
  46498. return true;
  46499. }
  46500. if (this.metallicRoughnessTexture === texture) {
  46501. return true;
  46502. }
  46503. return false;
  46504. };
  46505. /**
  46506. * Makes a duplicate of the current material.
  46507. * @param name - name to use for the new material.
  46508. */
  46509. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46510. var _this = this;
  46511. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46512. clone.id = name;
  46513. clone.name = name;
  46514. return clone;
  46515. };
  46516. /**
  46517. * Serialize the material to a parsable JSON object.
  46518. */
  46519. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46520. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46521. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46522. return serializationObject;
  46523. };
  46524. /**
  46525. * Parses a JSON object correponding to the serialize function.
  46526. */
  46527. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46528. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46529. };
  46530. __decorate([
  46531. BABYLON.serializeAsColor3(),
  46532. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46533. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46534. __decorate([
  46535. BABYLON.serializeAsTexture(),
  46536. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46537. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46538. __decorate([
  46539. BABYLON.serialize(),
  46540. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46541. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46542. __decorate([
  46543. BABYLON.serialize(),
  46544. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46545. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46546. __decorate([
  46547. BABYLON.serializeAsTexture(),
  46548. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46549. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46550. return PBRMetallicRoughnessMaterial;
  46551. }(BABYLON.PBRBaseSimpleMaterial));
  46552. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46553. })(BABYLON || (BABYLON = {}));
  46554. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46555. var BABYLON;
  46556. (function (BABYLON) {
  46557. /**
  46558. * The PBR material of BJS following the specular glossiness convention.
  46559. *
  46560. * This fits to the PBR convention in the GLTF definition:
  46561. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46562. */
  46563. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46564. __extends(PBRSpecularGlossinessMaterial, _super);
  46565. /**
  46566. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46567. *
  46568. * @param name The material name
  46569. * @param scene The scene the material will be use in.
  46570. */
  46571. function PBRSpecularGlossinessMaterial(name, scene) {
  46572. var _this = _super.call(this, name, scene) || this;
  46573. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46574. return _this;
  46575. }
  46576. /**
  46577. * Return the currrent class name of the material.
  46578. */
  46579. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46580. return "PBRSpecularGlossinessMaterial";
  46581. };
  46582. /**
  46583. * Return the active textures of the material.
  46584. */
  46585. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46586. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46587. if (this.diffuseTexture) {
  46588. activeTextures.push(this.diffuseTexture);
  46589. }
  46590. if (this.specularGlossinessTexture) {
  46591. activeTextures.push(this.specularGlossinessTexture);
  46592. }
  46593. return activeTextures;
  46594. };
  46595. /**
  46596. * Checks to see if a texture is used in the material.
  46597. * @param texture - Base texture to use.
  46598. * @returns - Boolean specifying if a texture is used in the material.
  46599. */
  46600. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46601. if (_super.prototype.hasTexture.call(this, texture)) {
  46602. return true;
  46603. }
  46604. if (this.diffuseTexture === texture) {
  46605. return true;
  46606. }
  46607. if (this.specularGlossinessTexture === texture) {
  46608. return true;
  46609. }
  46610. return false;
  46611. };
  46612. /**
  46613. * Makes a duplicate of the current material.
  46614. * @param name - name to use for the new material.
  46615. */
  46616. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46617. var _this = this;
  46618. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46619. clone.id = name;
  46620. clone.name = name;
  46621. return clone;
  46622. };
  46623. /**
  46624. * Serialize the material to a parsable JSON object.
  46625. */
  46626. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46627. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46628. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46629. return serializationObject;
  46630. };
  46631. /**
  46632. * Parses a JSON object correponding to the serialize function.
  46633. */
  46634. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46635. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46636. };
  46637. __decorate([
  46638. BABYLON.serializeAsColor3("diffuse"),
  46639. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46640. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46641. __decorate([
  46642. BABYLON.serializeAsTexture(),
  46643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46644. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46645. __decorate([
  46646. BABYLON.serializeAsColor3("specular"),
  46647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46648. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46649. __decorate([
  46650. BABYLON.serialize(),
  46651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46652. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46653. __decorate([
  46654. BABYLON.serializeAsTexture(),
  46655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46656. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46657. return PBRSpecularGlossinessMaterial;
  46658. }(BABYLON.PBRBaseSimpleMaterial));
  46659. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46660. })(BABYLON || (BABYLON = {}));
  46661. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46662. var BABYLON;
  46663. (function (BABYLON) {
  46664. BABYLON.CameraInputTypes = {};
  46665. var CameraInputsManager = /** @class */ (function () {
  46666. function CameraInputsManager(camera) {
  46667. this.attached = {};
  46668. this.camera = camera;
  46669. this.checkInputs = function () { };
  46670. }
  46671. /**
  46672. * Add an input method to a camera.
  46673. * builtin inputs example: camera.inputs.addGamepad();
  46674. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46675. * @param input camera input method
  46676. */
  46677. CameraInputsManager.prototype.add = function (input) {
  46678. var type = input.getSimpleName();
  46679. if (this.attached[type]) {
  46680. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46681. return;
  46682. }
  46683. this.attached[type] = input;
  46684. input.camera = this.camera;
  46685. //for checkInputs, we are dynamically creating a function
  46686. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46687. if (input.checkInputs) {
  46688. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46689. }
  46690. if (this.attachedElement) {
  46691. input.attachControl(this.attachedElement);
  46692. }
  46693. };
  46694. /**
  46695. * Remove a specific input method from a camera
  46696. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46697. * @param inputToRemove camera input method
  46698. */
  46699. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46700. for (var cam in this.attached) {
  46701. var input = this.attached[cam];
  46702. if (input === inputToRemove) {
  46703. input.detachControl(this.attachedElement);
  46704. input.camera = null;
  46705. delete this.attached[cam];
  46706. this.rebuildInputCheck();
  46707. }
  46708. }
  46709. };
  46710. CameraInputsManager.prototype.removeByType = function (inputType) {
  46711. for (var cam in this.attached) {
  46712. var input = this.attached[cam];
  46713. if (input.getClassName() === inputType) {
  46714. input.detachControl(this.attachedElement);
  46715. input.camera = null;
  46716. delete this.attached[cam];
  46717. this.rebuildInputCheck();
  46718. }
  46719. }
  46720. };
  46721. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46722. var current = this.checkInputs;
  46723. return function () {
  46724. current();
  46725. fn();
  46726. };
  46727. };
  46728. CameraInputsManager.prototype.attachInput = function (input) {
  46729. if (this.attachedElement) {
  46730. input.attachControl(this.attachedElement, this.noPreventDefault);
  46731. }
  46732. };
  46733. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46734. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46735. if (this.attachedElement) {
  46736. return;
  46737. }
  46738. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46739. this.attachedElement = element;
  46740. this.noPreventDefault = noPreventDefault;
  46741. for (var cam in this.attached) {
  46742. this.attached[cam].attachControl(element, noPreventDefault);
  46743. }
  46744. };
  46745. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46746. if (disconnect === void 0) { disconnect = false; }
  46747. if (this.attachedElement !== element) {
  46748. return;
  46749. }
  46750. for (var cam in this.attached) {
  46751. this.attached[cam].detachControl(element);
  46752. if (disconnect) {
  46753. this.attached[cam].camera = null;
  46754. }
  46755. }
  46756. this.attachedElement = null;
  46757. };
  46758. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46759. this.checkInputs = function () { };
  46760. for (var cam in this.attached) {
  46761. var input = this.attached[cam];
  46762. if (input.checkInputs) {
  46763. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46764. }
  46765. }
  46766. };
  46767. /**
  46768. * Remove all attached input methods from a camera
  46769. */
  46770. CameraInputsManager.prototype.clear = function () {
  46771. if (this.attachedElement) {
  46772. this.detachElement(this.attachedElement, true);
  46773. }
  46774. this.attached = {};
  46775. this.attachedElement = null;
  46776. this.checkInputs = function () { };
  46777. };
  46778. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46779. var inputs = {};
  46780. for (var cam in this.attached) {
  46781. var input = this.attached[cam];
  46782. var res = BABYLON.SerializationHelper.Serialize(input);
  46783. inputs[input.getClassName()] = res;
  46784. }
  46785. serializedCamera.inputsmgr = inputs;
  46786. };
  46787. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46788. var parsedInputs = parsedCamera.inputsmgr;
  46789. if (parsedInputs) {
  46790. this.clear();
  46791. for (var n in parsedInputs) {
  46792. var construct = BABYLON.CameraInputTypes[n];
  46793. if (construct) {
  46794. var parsedinput = parsedInputs[n];
  46795. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46796. this.add(input);
  46797. }
  46798. }
  46799. }
  46800. else {
  46801. //2016-03-08 this part is for managing backward compatibility
  46802. for (var n in this.attached) {
  46803. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46804. if (construct) {
  46805. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46806. this.remove(this.attached[n]);
  46807. this.add(input);
  46808. }
  46809. }
  46810. }
  46811. };
  46812. return CameraInputsManager;
  46813. }());
  46814. BABYLON.CameraInputsManager = CameraInputsManager;
  46815. })(BABYLON || (BABYLON = {}));
  46816. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46817. var BABYLON;
  46818. (function (BABYLON) {
  46819. var TargetCamera = /** @class */ (function (_super) {
  46820. __extends(TargetCamera, _super);
  46821. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46822. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46823. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46824. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46825. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46826. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46827. _this.speed = 2.0;
  46828. _this.noRotationConstraint = false;
  46829. _this.lockedTarget = null;
  46830. _this._currentTarget = BABYLON.Vector3.Zero();
  46831. _this._viewMatrix = BABYLON.Matrix.Zero();
  46832. _this._camMatrix = BABYLON.Matrix.Zero();
  46833. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46834. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46835. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46836. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46837. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46838. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46839. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46840. return _this;
  46841. }
  46842. TargetCamera.prototype.getFrontPosition = function (distance) {
  46843. this.getWorldMatrix();
  46844. var direction = this.getTarget().subtract(this.position);
  46845. direction.normalize();
  46846. direction.scaleInPlace(distance);
  46847. return this.globalPosition.add(direction);
  46848. };
  46849. TargetCamera.prototype._getLockedTargetPosition = function () {
  46850. if (!this.lockedTarget) {
  46851. return null;
  46852. }
  46853. if (this.lockedTarget.absolutePosition) {
  46854. this.lockedTarget.computeWorldMatrix();
  46855. }
  46856. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46857. };
  46858. TargetCamera.prototype.storeState = function () {
  46859. this._storedPosition = this.position.clone();
  46860. this._storedRotation = this.rotation.clone();
  46861. if (this.rotationQuaternion) {
  46862. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46863. }
  46864. return _super.prototype.storeState.call(this);
  46865. };
  46866. /**
  46867. * Restored camera state. You must call storeState() first
  46868. */
  46869. TargetCamera.prototype._restoreStateValues = function () {
  46870. if (!_super.prototype._restoreStateValues.call(this)) {
  46871. return false;
  46872. }
  46873. this.position = this._storedPosition.clone();
  46874. this.rotation = this._storedRotation.clone();
  46875. if (this.rotationQuaternion) {
  46876. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46877. }
  46878. this.cameraDirection.copyFromFloats(0, 0, 0);
  46879. this.cameraRotation.copyFromFloats(0, 0);
  46880. return true;
  46881. };
  46882. // Cache
  46883. TargetCamera.prototype._initCache = function () {
  46884. _super.prototype._initCache.call(this);
  46885. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46886. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46887. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46888. };
  46889. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46890. if (!ignoreParentClass) {
  46891. _super.prototype._updateCache.call(this);
  46892. }
  46893. var lockedTargetPosition = this._getLockedTargetPosition();
  46894. if (!lockedTargetPosition) {
  46895. this._cache.lockedTarget = null;
  46896. }
  46897. else {
  46898. if (!this._cache.lockedTarget) {
  46899. this._cache.lockedTarget = lockedTargetPosition.clone();
  46900. }
  46901. else {
  46902. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46903. }
  46904. }
  46905. this._cache.rotation.copyFrom(this.rotation);
  46906. if (this.rotationQuaternion)
  46907. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46908. };
  46909. // Synchronized
  46910. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46911. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46912. return false;
  46913. }
  46914. var lockedTargetPosition = this._getLockedTargetPosition();
  46915. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46916. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46917. };
  46918. // Methods
  46919. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46920. var engine = this.getEngine();
  46921. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46922. };
  46923. // Target
  46924. TargetCamera.prototype.setTarget = function (target) {
  46925. this.upVector.normalize();
  46926. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46927. this._camMatrix.invert();
  46928. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46929. var vDir = target.subtract(this.position);
  46930. if (vDir.x >= 0.0) {
  46931. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46932. }
  46933. else {
  46934. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46935. }
  46936. this.rotation.z = 0;
  46937. if (isNaN(this.rotation.x)) {
  46938. this.rotation.x = 0;
  46939. }
  46940. if (isNaN(this.rotation.y)) {
  46941. this.rotation.y = 0;
  46942. }
  46943. if (isNaN(this.rotation.z)) {
  46944. this.rotation.z = 0;
  46945. }
  46946. if (this.rotationQuaternion) {
  46947. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46948. }
  46949. };
  46950. /**
  46951. * Return the current target position of the camera. This value is expressed in local space.
  46952. */
  46953. TargetCamera.prototype.getTarget = function () {
  46954. return this._currentTarget;
  46955. };
  46956. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46957. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46958. };
  46959. TargetCamera.prototype._updatePosition = function () {
  46960. if (this.parent) {
  46961. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46962. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46963. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46964. return;
  46965. }
  46966. this.position.addInPlace(this.cameraDirection);
  46967. };
  46968. TargetCamera.prototype._checkInputs = function () {
  46969. var needToMove = this._decideIfNeedsToMove();
  46970. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46971. // Move
  46972. if (needToMove) {
  46973. this._updatePosition();
  46974. }
  46975. // Rotate
  46976. if (needToRotate) {
  46977. this.rotation.x += this.cameraRotation.x;
  46978. this.rotation.y += this.cameraRotation.y;
  46979. //rotate, if quaternion is set and rotation was used
  46980. if (this.rotationQuaternion) {
  46981. var len = this.rotation.lengthSquared();
  46982. if (len) {
  46983. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46984. }
  46985. }
  46986. if (!this.noRotationConstraint) {
  46987. var limit = (Math.PI / 2) * 0.95;
  46988. if (this.rotation.x > limit)
  46989. this.rotation.x = limit;
  46990. if (this.rotation.x < -limit)
  46991. this.rotation.x = -limit;
  46992. }
  46993. }
  46994. // Inertia
  46995. if (needToMove) {
  46996. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46997. this.cameraDirection.x = 0;
  46998. }
  46999. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47000. this.cameraDirection.y = 0;
  47001. }
  47002. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47003. this.cameraDirection.z = 0;
  47004. }
  47005. this.cameraDirection.scaleInPlace(this.inertia);
  47006. }
  47007. if (needToRotate) {
  47008. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47009. this.cameraRotation.x = 0;
  47010. }
  47011. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47012. this.cameraRotation.y = 0;
  47013. }
  47014. this.cameraRotation.scaleInPlace(this.inertia);
  47015. }
  47016. _super.prototype._checkInputs.call(this);
  47017. };
  47018. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47019. if (this.rotationQuaternion) {
  47020. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47021. }
  47022. else {
  47023. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47024. }
  47025. //update the up vector!
  47026. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47027. };
  47028. TargetCamera.prototype._getViewMatrix = function () {
  47029. if (this.lockedTarget) {
  47030. this.setTarget(this._getLockedTargetPosition());
  47031. }
  47032. // Compute
  47033. this._updateCameraRotationMatrix();
  47034. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47035. // Computing target and final matrix
  47036. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47037. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47038. return this._viewMatrix;
  47039. };
  47040. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47041. if (this.parent) {
  47042. var parentWorldMatrix = this.parent.getWorldMatrix();
  47043. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47044. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47045. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47046. this._markSyncedWithParent();
  47047. }
  47048. else {
  47049. this._globalPosition.copyFrom(this.position);
  47050. this._globalCurrentTarget.copyFrom(target);
  47051. this._globalCurrentUpVector.copyFrom(up);
  47052. }
  47053. if (this.getScene().useRightHandedSystem) {
  47054. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47055. }
  47056. else {
  47057. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47058. }
  47059. };
  47060. /**
  47061. * @override
  47062. * Override Camera.createRigCamera
  47063. */
  47064. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47065. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47066. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47067. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47068. if (!this.rotationQuaternion) {
  47069. this.rotationQuaternion = new BABYLON.Quaternion();
  47070. }
  47071. rigCamera._cameraRigParams = {};
  47072. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47073. }
  47074. return rigCamera;
  47075. }
  47076. return null;
  47077. };
  47078. /**
  47079. * @override
  47080. * Override Camera._updateRigCameras
  47081. */
  47082. TargetCamera.prototype._updateRigCameras = function () {
  47083. var camLeft = this._rigCameras[0];
  47084. var camRight = this._rigCameras[1];
  47085. switch (this.cameraRigMode) {
  47086. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47087. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47088. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47089. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47090. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47091. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47092. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47093. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47094. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47095. camLeft.setTarget(this.getTarget());
  47096. camRight.setTarget(this.getTarget());
  47097. break;
  47098. case BABYLON.Camera.RIG_MODE_VR:
  47099. if (camLeft.rotationQuaternion) {
  47100. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47101. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47102. }
  47103. else {
  47104. camLeft.rotation.copyFrom(this.rotation);
  47105. camRight.rotation.copyFrom(this.rotation);
  47106. }
  47107. camLeft.position.copyFrom(this.position);
  47108. camRight.position.copyFrom(this.position);
  47109. break;
  47110. }
  47111. _super.prototype._updateRigCameras.call(this);
  47112. };
  47113. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47114. if (!this._rigCamTransformMatrix) {
  47115. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47116. }
  47117. var target = this.getTarget();
  47118. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47119. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47120. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47121. };
  47122. TargetCamera.prototype.getClassName = function () {
  47123. return "TargetCamera";
  47124. };
  47125. __decorate([
  47126. BABYLON.serializeAsVector3()
  47127. ], TargetCamera.prototype, "rotation", void 0);
  47128. __decorate([
  47129. BABYLON.serialize()
  47130. ], TargetCamera.prototype, "speed", void 0);
  47131. __decorate([
  47132. BABYLON.serializeAsMeshReference("lockedTargetId")
  47133. ], TargetCamera.prototype, "lockedTarget", void 0);
  47134. return TargetCamera;
  47135. }(BABYLON.Camera));
  47136. BABYLON.TargetCamera = TargetCamera;
  47137. })(BABYLON || (BABYLON = {}));
  47138. //# sourceMappingURL=babylon.targetCamera.js.map
  47139. var BABYLON;
  47140. (function (BABYLON) {
  47141. var FreeCameraMouseInput = /** @class */ (function () {
  47142. function FreeCameraMouseInput(touchEnabled) {
  47143. if (touchEnabled === void 0) { touchEnabled = true; }
  47144. this.touchEnabled = touchEnabled;
  47145. this.buttons = [0, 1, 2];
  47146. this.angularSensibility = 2000.0;
  47147. this.previousPosition = null;
  47148. }
  47149. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47150. var _this = this;
  47151. var engine = this.camera.getEngine();
  47152. if (!this._pointerInput) {
  47153. this._pointerInput = function (p, s) {
  47154. var evt = p.event;
  47155. if (engine.isInVRExclusivePointerMode) {
  47156. return;
  47157. }
  47158. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47159. return;
  47160. }
  47161. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47162. return;
  47163. }
  47164. var srcElement = (evt.srcElement || evt.target);
  47165. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47166. try {
  47167. srcElement.setPointerCapture(evt.pointerId);
  47168. }
  47169. catch (e) {
  47170. //Nothing to do with the error. Execution will continue.
  47171. }
  47172. _this.previousPosition = {
  47173. x: evt.clientX,
  47174. y: evt.clientY
  47175. };
  47176. if (!noPreventDefault) {
  47177. evt.preventDefault();
  47178. element.focus();
  47179. }
  47180. }
  47181. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47182. try {
  47183. srcElement.releasePointerCapture(evt.pointerId);
  47184. }
  47185. catch (e) {
  47186. //Nothing to do with the error.
  47187. }
  47188. _this.previousPosition = null;
  47189. if (!noPreventDefault) {
  47190. evt.preventDefault();
  47191. }
  47192. }
  47193. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47194. if (!_this.previousPosition || engine.isPointerLock) {
  47195. return;
  47196. }
  47197. var offsetX = evt.clientX - _this.previousPosition.x;
  47198. if (_this.camera.getScene().useRightHandedSystem)
  47199. offsetX *= -1;
  47200. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47201. offsetX *= -1;
  47202. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47203. var offsetY = evt.clientY - _this.previousPosition.y;
  47204. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47205. _this.previousPosition = {
  47206. x: evt.clientX,
  47207. y: evt.clientY
  47208. };
  47209. if (!noPreventDefault) {
  47210. evt.preventDefault();
  47211. }
  47212. }
  47213. };
  47214. }
  47215. this._onMouseMove = function (evt) {
  47216. if (!engine.isPointerLock) {
  47217. return;
  47218. }
  47219. if (engine.isInVRExclusivePointerMode) {
  47220. return;
  47221. }
  47222. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47223. if (_this.camera.getScene().useRightHandedSystem)
  47224. offsetX *= -1;
  47225. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47226. offsetX *= -1;
  47227. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47228. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47229. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47230. _this.previousPosition = null;
  47231. if (!noPreventDefault) {
  47232. evt.preventDefault();
  47233. }
  47234. };
  47235. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47236. element.addEventListener("mousemove", this._onMouseMove, false);
  47237. };
  47238. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47239. if (this._observer && element) {
  47240. this.camera.getScene().onPointerObservable.remove(this._observer);
  47241. if (this._onMouseMove) {
  47242. element.removeEventListener("mousemove", this._onMouseMove);
  47243. }
  47244. this._observer = null;
  47245. this._onMouseMove = null;
  47246. this.previousPosition = null;
  47247. }
  47248. };
  47249. FreeCameraMouseInput.prototype.getClassName = function () {
  47250. return "FreeCameraMouseInput";
  47251. };
  47252. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47253. return "mouse";
  47254. };
  47255. __decorate([
  47256. BABYLON.serialize()
  47257. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47258. __decorate([
  47259. BABYLON.serialize()
  47260. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47261. return FreeCameraMouseInput;
  47262. }());
  47263. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47264. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47265. })(BABYLON || (BABYLON = {}));
  47266. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47267. var BABYLON;
  47268. (function (BABYLON) {
  47269. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47270. function FreeCameraKeyboardMoveInput() {
  47271. this._keys = new Array();
  47272. this.keysUp = [38];
  47273. this.keysDown = [40];
  47274. this.keysLeft = [37];
  47275. this.keysRight = [39];
  47276. }
  47277. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47278. var _this = this;
  47279. if (this._onCanvasBlurObserver) {
  47280. return;
  47281. }
  47282. this._scene = this.camera.getScene();
  47283. this._engine = this._scene.getEngine();
  47284. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47285. _this._keys = [];
  47286. });
  47287. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47288. var evt = info.event;
  47289. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47290. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47291. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47292. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47293. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47294. var index = _this._keys.indexOf(evt.keyCode);
  47295. if (index === -1) {
  47296. _this._keys.push(evt.keyCode);
  47297. }
  47298. if (!noPreventDefault) {
  47299. evt.preventDefault();
  47300. }
  47301. }
  47302. }
  47303. else {
  47304. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47305. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47306. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47307. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47308. var index = _this._keys.indexOf(evt.keyCode);
  47309. if (index >= 0) {
  47310. _this._keys.splice(index, 1);
  47311. }
  47312. if (!noPreventDefault) {
  47313. evt.preventDefault();
  47314. }
  47315. }
  47316. }
  47317. });
  47318. };
  47319. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47320. if (this._scene) {
  47321. if (this._onKeyboardObserver) {
  47322. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47323. }
  47324. if (this._onCanvasBlurObserver) {
  47325. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47326. }
  47327. this._onKeyboardObserver = null;
  47328. this._onCanvasBlurObserver = null;
  47329. }
  47330. this._keys = [];
  47331. };
  47332. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47333. if (this._onKeyboardObserver) {
  47334. var camera = this.camera;
  47335. // Keyboard
  47336. for (var index = 0; index < this._keys.length; index++) {
  47337. var keyCode = this._keys[index];
  47338. var speed = camera._computeLocalCameraSpeed();
  47339. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47340. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47341. }
  47342. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47343. camera._localDirection.copyFromFloats(0, 0, speed);
  47344. }
  47345. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47346. camera._localDirection.copyFromFloats(speed, 0, 0);
  47347. }
  47348. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47349. camera._localDirection.copyFromFloats(0, 0, -speed);
  47350. }
  47351. if (camera.getScene().useRightHandedSystem) {
  47352. camera._localDirection.z *= -1;
  47353. }
  47354. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47355. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47356. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47357. }
  47358. }
  47359. };
  47360. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47361. return "FreeCameraKeyboardMoveInput";
  47362. };
  47363. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47364. this._keys = [];
  47365. };
  47366. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47367. return "keyboard";
  47368. };
  47369. __decorate([
  47370. BABYLON.serialize()
  47371. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47372. __decorate([
  47373. BABYLON.serialize()
  47374. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47375. __decorate([
  47376. BABYLON.serialize()
  47377. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47378. __decorate([
  47379. BABYLON.serialize()
  47380. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47381. return FreeCameraKeyboardMoveInput;
  47382. }());
  47383. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47384. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47385. })(BABYLON || (BABYLON = {}));
  47386. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47387. var BABYLON;
  47388. (function (BABYLON) {
  47389. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47390. __extends(FreeCameraInputsManager, _super);
  47391. function FreeCameraInputsManager(camera) {
  47392. return _super.call(this, camera) || this;
  47393. }
  47394. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47395. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47396. return this;
  47397. };
  47398. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47399. if (touchEnabled === void 0) { touchEnabled = true; }
  47400. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47401. return this;
  47402. };
  47403. FreeCameraInputsManager.prototype.addGamepad = function () {
  47404. this.add(new BABYLON.FreeCameraGamepadInput());
  47405. return this;
  47406. };
  47407. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47408. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47409. return this;
  47410. };
  47411. FreeCameraInputsManager.prototype.addTouch = function () {
  47412. this.add(new BABYLON.FreeCameraTouchInput());
  47413. return this;
  47414. };
  47415. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47416. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47417. return this;
  47418. };
  47419. return FreeCameraInputsManager;
  47420. }(BABYLON.CameraInputsManager));
  47421. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47422. })(BABYLON || (BABYLON = {}));
  47423. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47424. var BABYLON;
  47425. (function (BABYLON) {
  47426. var FreeCamera = /** @class */ (function (_super) {
  47427. __extends(FreeCamera, _super);
  47428. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47429. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47430. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47431. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47432. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47433. _this.checkCollisions = false;
  47434. _this.applyGravity = false;
  47435. _this._needMoveForGravity = false;
  47436. _this._oldPosition = BABYLON.Vector3.Zero();
  47437. _this._diffPosition = BABYLON.Vector3.Zero();
  47438. _this._newPosition = BABYLON.Vector3.Zero();
  47439. // Collisions
  47440. _this._collisionMask = -1;
  47441. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47442. if (collidedMesh === void 0) { collidedMesh = null; }
  47443. //TODO move this to the collision coordinator!
  47444. if (_this.getScene().workerCollisions)
  47445. newPosition.multiplyInPlace(_this._collider._radius);
  47446. var updatePosition = function (newPos) {
  47447. _this._newPosition.copyFrom(newPos);
  47448. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47449. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47450. _this.position.addInPlace(_this._diffPosition);
  47451. if (_this.onCollide && collidedMesh) {
  47452. _this.onCollide(collidedMesh);
  47453. }
  47454. }
  47455. };
  47456. updatePosition(newPosition);
  47457. };
  47458. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47459. _this.inputs.addKeyboard().addMouse();
  47460. return _this;
  47461. }
  47462. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47463. //-- begin properties for backward compatibility for inputs
  47464. /**
  47465. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47466. * Higher values reduce sensitivity.
  47467. */
  47468. get: function () {
  47469. var mouse = this.inputs.attached["mouse"];
  47470. if (mouse)
  47471. return mouse.angularSensibility;
  47472. return 0;
  47473. },
  47474. /**
  47475. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47476. * Higher values reduce sensitivity.
  47477. */
  47478. set: function (value) {
  47479. var mouse = this.inputs.attached["mouse"];
  47480. if (mouse)
  47481. mouse.angularSensibility = value;
  47482. },
  47483. enumerable: true,
  47484. configurable: true
  47485. });
  47486. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47487. get: function () {
  47488. var keyboard = this.inputs.attached["keyboard"];
  47489. if (keyboard)
  47490. return keyboard.keysUp;
  47491. return [];
  47492. },
  47493. set: function (value) {
  47494. var keyboard = this.inputs.attached["keyboard"];
  47495. if (keyboard)
  47496. keyboard.keysUp = value;
  47497. },
  47498. enumerable: true,
  47499. configurable: true
  47500. });
  47501. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47502. get: function () {
  47503. var keyboard = this.inputs.attached["keyboard"];
  47504. if (keyboard)
  47505. return keyboard.keysDown;
  47506. return [];
  47507. },
  47508. set: function (value) {
  47509. var keyboard = this.inputs.attached["keyboard"];
  47510. if (keyboard)
  47511. keyboard.keysDown = value;
  47512. },
  47513. enumerable: true,
  47514. configurable: true
  47515. });
  47516. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47517. get: function () {
  47518. var keyboard = this.inputs.attached["keyboard"];
  47519. if (keyboard)
  47520. return keyboard.keysLeft;
  47521. return [];
  47522. },
  47523. set: function (value) {
  47524. var keyboard = this.inputs.attached["keyboard"];
  47525. if (keyboard)
  47526. keyboard.keysLeft = value;
  47527. },
  47528. enumerable: true,
  47529. configurable: true
  47530. });
  47531. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47532. get: function () {
  47533. var keyboard = this.inputs.attached["keyboard"];
  47534. if (keyboard)
  47535. return keyboard.keysRight;
  47536. return [];
  47537. },
  47538. set: function (value) {
  47539. var keyboard = this.inputs.attached["keyboard"];
  47540. if (keyboard)
  47541. keyboard.keysRight = value;
  47542. },
  47543. enumerable: true,
  47544. configurable: true
  47545. });
  47546. // Controls
  47547. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47548. this.inputs.attachElement(element, noPreventDefault);
  47549. };
  47550. FreeCamera.prototype.detachControl = function (element) {
  47551. this.inputs.detachElement(element);
  47552. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47553. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47554. };
  47555. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47556. get: function () {
  47557. return this._collisionMask;
  47558. },
  47559. set: function (mask) {
  47560. this._collisionMask = !isNaN(mask) ? mask : -1;
  47561. },
  47562. enumerable: true,
  47563. configurable: true
  47564. });
  47565. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47566. var globalPosition;
  47567. if (this.parent) {
  47568. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47569. }
  47570. else {
  47571. globalPosition = this.position;
  47572. }
  47573. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47574. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47575. if (!this._collider) {
  47576. this._collider = new BABYLON.Collider();
  47577. }
  47578. this._collider._radius = this.ellipsoid;
  47579. this._collider.collisionMask = this._collisionMask;
  47580. //no need for clone, as long as gravity is not on.
  47581. var actualDisplacement = displacement;
  47582. //add gravity to the direction to prevent the dual-collision checking
  47583. if (this.applyGravity) {
  47584. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47585. actualDisplacement = displacement.add(this.getScene().gravity);
  47586. }
  47587. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47588. };
  47589. FreeCamera.prototype._checkInputs = function () {
  47590. if (!this._localDirection) {
  47591. this._localDirection = BABYLON.Vector3.Zero();
  47592. this._transformedDirection = BABYLON.Vector3.Zero();
  47593. }
  47594. this.inputs.checkInputs();
  47595. _super.prototype._checkInputs.call(this);
  47596. };
  47597. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47598. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47599. };
  47600. FreeCamera.prototype._updatePosition = function () {
  47601. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47602. this._collideWithWorld(this.cameraDirection);
  47603. }
  47604. else {
  47605. _super.prototype._updatePosition.call(this);
  47606. }
  47607. };
  47608. FreeCamera.prototype.dispose = function () {
  47609. this.inputs.clear();
  47610. _super.prototype.dispose.call(this);
  47611. };
  47612. FreeCamera.prototype.getClassName = function () {
  47613. return "FreeCamera";
  47614. };
  47615. __decorate([
  47616. BABYLON.serializeAsVector3()
  47617. ], FreeCamera.prototype, "ellipsoid", void 0);
  47618. __decorate([
  47619. BABYLON.serializeAsVector3()
  47620. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47621. __decorate([
  47622. BABYLON.serialize()
  47623. ], FreeCamera.prototype, "checkCollisions", void 0);
  47624. __decorate([
  47625. BABYLON.serialize()
  47626. ], FreeCamera.prototype, "applyGravity", void 0);
  47627. return FreeCamera;
  47628. }(BABYLON.TargetCamera));
  47629. BABYLON.FreeCamera = FreeCamera;
  47630. })(BABYLON || (BABYLON = {}));
  47631. //# sourceMappingURL=babylon.freeCamera.js.map
  47632. var BABYLON;
  47633. (function (BABYLON) {
  47634. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47635. function ArcRotateCameraKeyboardMoveInput() {
  47636. this._keys = new Array();
  47637. this.keysUp = [38];
  47638. this.keysDown = [40];
  47639. this.keysLeft = [37];
  47640. this.keysRight = [39];
  47641. this.keysReset = [220];
  47642. this.panningSensibility = 50.0;
  47643. this.zoomingSensibility = 25.0;
  47644. this.useAltToZoom = true;
  47645. }
  47646. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47647. var _this = this;
  47648. if (this._onCanvasBlurObserver) {
  47649. return;
  47650. }
  47651. this._scene = this.camera.getScene();
  47652. this._engine = this._scene.getEngine();
  47653. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47654. _this._keys = [];
  47655. });
  47656. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47657. var evt = info.event;
  47658. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47659. _this._ctrlPressed = evt.ctrlKey;
  47660. _this._altPressed = evt.altKey;
  47661. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47662. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47663. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47664. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47665. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47666. var index = _this._keys.indexOf(evt.keyCode);
  47667. if (index === -1) {
  47668. _this._keys.push(evt.keyCode);
  47669. }
  47670. if (evt.preventDefault) {
  47671. if (!noPreventDefault) {
  47672. evt.preventDefault();
  47673. }
  47674. }
  47675. }
  47676. }
  47677. else {
  47678. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47679. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47680. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47681. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47682. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47683. var index = _this._keys.indexOf(evt.keyCode);
  47684. if (index >= 0) {
  47685. _this._keys.splice(index, 1);
  47686. }
  47687. if (evt.preventDefault) {
  47688. if (!noPreventDefault) {
  47689. evt.preventDefault();
  47690. }
  47691. }
  47692. }
  47693. }
  47694. });
  47695. };
  47696. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47697. if (this._scene) {
  47698. if (this._onKeyboardObserver) {
  47699. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47700. }
  47701. if (this._onCanvasBlurObserver) {
  47702. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47703. }
  47704. this._onKeyboardObserver = null;
  47705. this._onCanvasBlurObserver = null;
  47706. }
  47707. this._keys = [];
  47708. };
  47709. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47710. if (this._onKeyboardObserver) {
  47711. var camera = this.camera;
  47712. for (var index = 0; index < this._keys.length; index++) {
  47713. var keyCode = this._keys[index];
  47714. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47715. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47716. camera.inertialPanningX -= 1 / this.panningSensibility;
  47717. }
  47718. else {
  47719. camera.inertialAlphaOffset -= 0.01;
  47720. }
  47721. }
  47722. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47723. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47724. camera.inertialPanningY += 1 / this.panningSensibility;
  47725. }
  47726. else if (this._altPressed && this.useAltToZoom) {
  47727. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47728. }
  47729. else {
  47730. camera.inertialBetaOffset -= 0.01;
  47731. }
  47732. }
  47733. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47734. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47735. camera.inertialPanningX += 1 / this.panningSensibility;
  47736. }
  47737. else {
  47738. camera.inertialAlphaOffset += 0.01;
  47739. }
  47740. }
  47741. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47742. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47743. camera.inertialPanningY -= 1 / this.panningSensibility;
  47744. }
  47745. else if (this._altPressed && this.useAltToZoom) {
  47746. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47747. }
  47748. else {
  47749. camera.inertialBetaOffset += 0.01;
  47750. }
  47751. }
  47752. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47753. camera.restoreState();
  47754. }
  47755. }
  47756. }
  47757. };
  47758. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47759. return "ArcRotateCameraKeyboardMoveInput";
  47760. };
  47761. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47762. return "keyboard";
  47763. };
  47764. __decorate([
  47765. BABYLON.serialize()
  47766. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47767. __decorate([
  47768. BABYLON.serialize()
  47769. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47770. __decorate([
  47771. BABYLON.serialize()
  47772. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47773. __decorate([
  47774. BABYLON.serialize()
  47775. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47776. __decorate([
  47777. BABYLON.serialize()
  47778. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47779. __decorate([
  47780. BABYLON.serialize()
  47781. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47782. __decorate([
  47783. BABYLON.serialize()
  47784. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47785. __decorate([
  47786. BABYLON.serialize()
  47787. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47788. return ArcRotateCameraKeyboardMoveInput;
  47789. }());
  47790. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47791. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47792. })(BABYLON || (BABYLON = {}));
  47793. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47794. var BABYLON;
  47795. (function (BABYLON) {
  47796. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47797. function ArcRotateCameraMouseWheelInput() {
  47798. this.wheelPrecision = 3.0;
  47799. /**
  47800. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47801. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47802. */
  47803. this.wheelDeltaPercentage = 0;
  47804. }
  47805. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47806. var _this = this;
  47807. this._wheel = function (p, s) {
  47808. //sanity check - this should be a PointerWheel event.
  47809. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47810. return;
  47811. var event = p.event;
  47812. var delta = 0;
  47813. if (event.wheelDelta) {
  47814. if (_this.wheelDeltaPercentage) {
  47815. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47816. if (event.wheelDelta > 0) {
  47817. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47818. }
  47819. else {
  47820. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47821. }
  47822. }
  47823. else {
  47824. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47825. }
  47826. }
  47827. else if (event.detail) {
  47828. delta = -event.detail / _this.wheelPrecision;
  47829. }
  47830. if (delta)
  47831. _this.camera.inertialRadiusOffset += delta;
  47832. if (event.preventDefault) {
  47833. if (!noPreventDefault) {
  47834. event.preventDefault();
  47835. }
  47836. }
  47837. };
  47838. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47839. };
  47840. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47841. if (this._observer && element) {
  47842. this.camera.getScene().onPointerObservable.remove(this._observer);
  47843. this._observer = null;
  47844. this._wheel = null;
  47845. }
  47846. };
  47847. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47848. return "ArcRotateCameraMouseWheelInput";
  47849. };
  47850. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47851. return "mousewheel";
  47852. };
  47853. __decorate([
  47854. BABYLON.serialize()
  47855. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47856. __decorate([
  47857. BABYLON.serialize()
  47858. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47859. return ArcRotateCameraMouseWheelInput;
  47860. }());
  47861. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47862. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47863. })(BABYLON || (BABYLON = {}));
  47864. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47865. var BABYLON;
  47866. (function (BABYLON) {
  47867. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47868. function ArcRotateCameraPointersInput() {
  47869. this.buttons = [0, 1, 2];
  47870. this.angularSensibilityX = 1000.0;
  47871. this.angularSensibilityY = 1000.0;
  47872. this.pinchPrecision = 12.0;
  47873. /**
  47874. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47875. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47876. */
  47877. this.pinchDeltaPercentage = 0;
  47878. this.panningSensibility = 1000.0;
  47879. this.multiTouchPanning = true;
  47880. this.multiTouchPanAndZoom = true;
  47881. this._isPanClick = false;
  47882. this.pinchInwards = true;
  47883. }
  47884. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47885. var _this = this;
  47886. var engine = this.camera.getEngine();
  47887. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47888. var pointA = null;
  47889. var pointB = null;
  47890. var previousPinchSquaredDistance = 0;
  47891. var initialDistance = 0;
  47892. var twoFingerActivityCount = 0;
  47893. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47894. this._pointerInput = function (p, s) {
  47895. var evt = p.event;
  47896. var isTouch = p.event.pointerType === "touch";
  47897. if (engine.isInVRExclusivePointerMode) {
  47898. return;
  47899. }
  47900. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47901. return;
  47902. }
  47903. var srcElement = (evt.srcElement || evt.target);
  47904. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47905. try {
  47906. srcElement.setPointerCapture(evt.pointerId);
  47907. }
  47908. catch (e) {
  47909. //Nothing to do with the error. Execution will continue.
  47910. }
  47911. // Manage panning with pan button click
  47912. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47913. // manage pointers
  47914. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47915. if (pointA === null) {
  47916. pointA = cacheSoloPointer;
  47917. }
  47918. else if (pointB === null) {
  47919. pointB = cacheSoloPointer;
  47920. }
  47921. if (!noPreventDefault) {
  47922. evt.preventDefault();
  47923. element.focus();
  47924. }
  47925. }
  47926. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47927. _this.camera.restoreState();
  47928. }
  47929. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47930. try {
  47931. srcElement.releasePointerCapture(evt.pointerId);
  47932. }
  47933. catch (e) {
  47934. //Nothing to do with the error.
  47935. }
  47936. cacheSoloPointer = null;
  47937. previousPinchSquaredDistance = 0;
  47938. previousMultiTouchPanPosition.isPaning = false;
  47939. previousMultiTouchPanPosition.isPinching = false;
  47940. twoFingerActivityCount = 0;
  47941. initialDistance = 0;
  47942. if (!isTouch) {
  47943. pointB = null; // Mouse and pen are mono pointer
  47944. }
  47945. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47946. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47947. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47948. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47949. if (engine._badOS) {
  47950. pointA = pointB = null;
  47951. }
  47952. else {
  47953. //only remove the impacted pointer in case of multitouch allowing on most
  47954. //platforms switching from rotate to zoom and pan seamlessly.
  47955. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47956. pointA = pointB;
  47957. pointB = null;
  47958. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47959. }
  47960. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47961. pointB = null;
  47962. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47963. }
  47964. else {
  47965. pointA = pointB = null;
  47966. }
  47967. }
  47968. if (!noPreventDefault) {
  47969. evt.preventDefault();
  47970. }
  47971. }
  47972. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47973. if (!noPreventDefault) {
  47974. evt.preventDefault();
  47975. }
  47976. // One button down
  47977. if (pointA && pointB === null && cacheSoloPointer) {
  47978. if (_this.panningSensibility !== 0 &&
  47979. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47980. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47981. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47982. }
  47983. else {
  47984. var offsetX = evt.clientX - cacheSoloPointer.x;
  47985. var offsetY = evt.clientY - cacheSoloPointer.y;
  47986. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47987. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47988. }
  47989. cacheSoloPointer.x = evt.clientX;
  47990. cacheSoloPointer.y = evt.clientY;
  47991. }
  47992. // Two buttons down: pinch/pan
  47993. else if (pointA && pointB) {
  47994. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47995. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47996. ed.x = evt.clientX;
  47997. ed.y = evt.clientY;
  47998. var direction = _this.pinchInwards ? 1 : -1;
  47999. var distX = pointA.x - pointB.x;
  48000. var distY = pointA.y - pointB.y;
  48001. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48002. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48003. if (previousPinchSquaredDistance === 0) {
  48004. initialDistance = pinchDistance;
  48005. previousPinchSquaredDistance = pinchSquaredDistance;
  48006. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48007. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48008. return;
  48009. }
  48010. if (_this.multiTouchPanAndZoom) {
  48011. if (_this.pinchDeltaPercentage) {
  48012. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48013. }
  48014. else {
  48015. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48016. (_this.pinchPrecision *
  48017. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48018. direction);
  48019. }
  48020. if (_this.panningSensibility !== 0) {
  48021. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48022. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48023. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48024. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48025. previousMultiTouchPanPosition.x = pointersCenterX;
  48026. previousMultiTouchPanPosition.y = pointersCenterY;
  48027. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48028. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48029. }
  48030. }
  48031. else {
  48032. twoFingerActivityCount++;
  48033. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48034. if (_this.pinchDeltaPercentage) {
  48035. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48036. }
  48037. else {
  48038. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48039. (_this.pinchPrecision *
  48040. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48041. direction);
  48042. }
  48043. previousMultiTouchPanPosition.isPaning = false;
  48044. previousMultiTouchPanPosition.isPinching = true;
  48045. }
  48046. else {
  48047. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48048. if (!previousMultiTouchPanPosition.isPaning) {
  48049. previousMultiTouchPanPosition.isPaning = true;
  48050. previousMultiTouchPanPosition.isPinching = false;
  48051. previousMultiTouchPanPosition.x = ed.x;
  48052. previousMultiTouchPanPosition.y = ed.y;
  48053. return;
  48054. }
  48055. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48056. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48057. }
  48058. }
  48059. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48060. previousMultiTouchPanPosition.x = ed.x;
  48061. previousMultiTouchPanPosition.y = ed.y;
  48062. }
  48063. }
  48064. previousPinchSquaredDistance = pinchSquaredDistance;
  48065. }
  48066. }
  48067. };
  48068. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48069. this._onContextMenu = function (evt) {
  48070. evt.preventDefault();
  48071. };
  48072. if (!this.camera._useCtrlForPanning) {
  48073. element.addEventListener("contextmenu", this._onContextMenu, false);
  48074. }
  48075. this._onLostFocus = function () {
  48076. //this._keys = [];
  48077. pointA = pointB = null;
  48078. previousPinchSquaredDistance = 0;
  48079. previousMultiTouchPanPosition.isPaning = false;
  48080. previousMultiTouchPanPosition.isPinching = false;
  48081. twoFingerActivityCount = 0;
  48082. cacheSoloPointer = null;
  48083. initialDistance = 0;
  48084. };
  48085. this._onMouseMove = function (evt) {
  48086. if (!engine.isPointerLock) {
  48087. return;
  48088. }
  48089. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48090. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48091. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48092. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48093. if (!noPreventDefault) {
  48094. evt.preventDefault();
  48095. }
  48096. };
  48097. this._onGestureStart = function (e) {
  48098. if (window.MSGesture === undefined) {
  48099. return;
  48100. }
  48101. if (!_this._MSGestureHandler) {
  48102. _this._MSGestureHandler = new MSGesture();
  48103. _this._MSGestureHandler.target = element;
  48104. }
  48105. _this._MSGestureHandler.addPointer(e.pointerId);
  48106. };
  48107. this._onGesture = function (e) {
  48108. _this.camera.radius *= e.scale;
  48109. if (e.preventDefault) {
  48110. if (!noPreventDefault) {
  48111. e.stopPropagation();
  48112. e.preventDefault();
  48113. }
  48114. }
  48115. };
  48116. element.addEventListener("mousemove", this._onMouseMove, false);
  48117. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48118. element.addEventListener("MSGestureChange", this._onGesture, false);
  48119. BABYLON.Tools.RegisterTopRootEvents([
  48120. { name: "blur", handler: this._onLostFocus }
  48121. ]);
  48122. };
  48123. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48124. if (this._onLostFocus) {
  48125. BABYLON.Tools.UnregisterTopRootEvents([
  48126. { name: "blur", handler: this._onLostFocus }
  48127. ]);
  48128. }
  48129. if (element && this._observer) {
  48130. this.camera.getScene().onPointerObservable.remove(this._observer);
  48131. this._observer = null;
  48132. if (this._onContextMenu) {
  48133. element.removeEventListener("contextmenu", this._onContextMenu);
  48134. }
  48135. if (this._onMouseMove) {
  48136. element.removeEventListener("mousemove", this._onMouseMove);
  48137. }
  48138. if (this._onGestureStart) {
  48139. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48140. }
  48141. if (this._onGesture) {
  48142. element.removeEventListener("MSGestureChange", this._onGesture);
  48143. }
  48144. this._isPanClick = false;
  48145. this.pinchInwards = true;
  48146. this._onMouseMove = null;
  48147. this._onGestureStart = null;
  48148. this._onGesture = null;
  48149. this._MSGestureHandler = null;
  48150. this._onLostFocus = null;
  48151. this._onContextMenu = null;
  48152. }
  48153. };
  48154. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48155. return "ArcRotateCameraPointersInput";
  48156. };
  48157. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48158. return "pointers";
  48159. };
  48160. __decorate([
  48161. BABYLON.serialize()
  48162. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48163. __decorate([
  48164. BABYLON.serialize()
  48165. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48166. __decorate([
  48167. BABYLON.serialize()
  48168. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48169. __decorate([
  48170. BABYLON.serialize()
  48171. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48172. __decorate([
  48173. BABYLON.serialize()
  48174. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48175. __decorate([
  48176. BABYLON.serialize()
  48177. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48178. __decorate([
  48179. BABYLON.serialize()
  48180. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48181. __decorate([
  48182. BABYLON.serialize()
  48183. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48184. return ArcRotateCameraPointersInput;
  48185. }());
  48186. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48187. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48188. })(BABYLON || (BABYLON = {}));
  48189. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48190. var BABYLON;
  48191. (function (BABYLON) {
  48192. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48193. __extends(ArcRotateCameraInputsManager, _super);
  48194. function ArcRotateCameraInputsManager(camera) {
  48195. return _super.call(this, camera) || this;
  48196. }
  48197. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48198. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48199. return this;
  48200. };
  48201. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48202. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48203. return this;
  48204. };
  48205. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48206. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48207. return this;
  48208. };
  48209. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48210. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48211. return this;
  48212. };
  48213. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48214. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48215. return this;
  48216. };
  48217. return ArcRotateCameraInputsManager;
  48218. }(BABYLON.CameraInputsManager));
  48219. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48220. })(BABYLON || (BABYLON = {}));
  48221. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48222. var BABYLON;
  48223. (function (BABYLON) {
  48224. var ArcRotateCamera = /** @class */ (function (_super) {
  48225. __extends(ArcRotateCamera, _super);
  48226. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48227. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48228. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48229. _this.inertialAlphaOffset = 0;
  48230. _this.inertialBetaOffset = 0;
  48231. _this.inertialRadiusOffset = 0;
  48232. _this.lowerAlphaLimit = null;
  48233. _this.upperAlphaLimit = null;
  48234. _this.lowerBetaLimit = 0.01;
  48235. _this.upperBetaLimit = Math.PI;
  48236. _this.lowerRadiusLimit = null;
  48237. _this.upperRadiusLimit = null;
  48238. _this.inertialPanningX = 0;
  48239. _this.inertialPanningY = 0;
  48240. _this.pinchToPanMaxDistance = 20;
  48241. _this.panningDistanceLimit = null;
  48242. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48243. _this.panningInertia = 0.9;
  48244. //-- end properties for backward compatibility for inputs
  48245. _this.zoomOnFactor = 1;
  48246. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48247. _this.allowUpsideDown = true;
  48248. _this._viewMatrix = new BABYLON.Matrix();
  48249. // Panning
  48250. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48251. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48252. _this.checkCollisions = false;
  48253. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48254. _this._previousPosition = BABYLON.Vector3.Zero();
  48255. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48256. _this._newPosition = BABYLON.Vector3.Zero();
  48257. _this._computationVector = BABYLON.Vector3.Zero();
  48258. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48259. if (collidedMesh === void 0) { collidedMesh = null; }
  48260. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48261. newPosition.multiplyInPlace(_this._collider._radius);
  48262. }
  48263. if (!collidedMesh) {
  48264. _this._previousPosition.copyFrom(_this.position);
  48265. }
  48266. else {
  48267. _this.setPosition(newPosition);
  48268. if (_this.onCollide) {
  48269. _this.onCollide(collidedMesh);
  48270. }
  48271. }
  48272. // Recompute because of constraints
  48273. var cosa = Math.cos(_this.alpha);
  48274. var sina = Math.sin(_this.alpha);
  48275. var cosb = Math.cos(_this.beta);
  48276. var sinb = Math.sin(_this.beta);
  48277. if (sinb === 0) {
  48278. sinb = 0.0001;
  48279. }
  48280. var target = _this._getTargetPosition();
  48281. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48282. target.addToRef(_this._computationVector, _this._newPosition);
  48283. _this.position.copyFrom(_this._newPosition);
  48284. var up = _this.upVector;
  48285. if (_this.allowUpsideDown && _this.beta < 0) {
  48286. up = up.clone();
  48287. up = up.negate();
  48288. }
  48289. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  48290. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48291. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48292. _this._collisionTriggered = false;
  48293. };
  48294. _this._target = BABYLON.Vector3.Zero();
  48295. if (target) {
  48296. _this.setTarget(target);
  48297. }
  48298. _this.alpha = alpha;
  48299. _this.beta = beta;
  48300. _this.radius = radius;
  48301. _this.getViewMatrix();
  48302. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48303. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48304. return _this;
  48305. }
  48306. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48307. get: function () {
  48308. return this._target;
  48309. },
  48310. set: function (value) {
  48311. this.setTarget(value);
  48312. },
  48313. enumerable: true,
  48314. configurable: true
  48315. });
  48316. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48317. //-- begin properties for backward compatibility for inputs
  48318. get: function () {
  48319. var pointers = this.inputs.attached["pointers"];
  48320. if (pointers)
  48321. return pointers.angularSensibilityX;
  48322. return 0;
  48323. },
  48324. set: function (value) {
  48325. var pointers = this.inputs.attached["pointers"];
  48326. if (pointers) {
  48327. pointers.angularSensibilityX = value;
  48328. }
  48329. },
  48330. enumerable: true,
  48331. configurable: true
  48332. });
  48333. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48334. get: function () {
  48335. var pointers = this.inputs.attached["pointers"];
  48336. if (pointers)
  48337. return pointers.angularSensibilityY;
  48338. return 0;
  48339. },
  48340. set: function (value) {
  48341. var pointers = this.inputs.attached["pointers"];
  48342. if (pointers) {
  48343. pointers.angularSensibilityY = value;
  48344. }
  48345. },
  48346. enumerable: true,
  48347. configurable: true
  48348. });
  48349. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48350. get: function () {
  48351. var pointers = this.inputs.attached["pointers"];
  48352. if (pointers)
  48353. return pointers.pinchPrecision;
  48354. return 0;
  48355. },
  48356. set: function (value) {
  48357. var pointers = this.inputs.attached["pointers"];
  48358. if (pointers) {
  48359. pointers.pinchPrecision = value;
  48360. }
  48361. },
  48362. enumerable: true,
  48363. configurable: true
  48364. });
  48365. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48366. get: function () {
  48367. var pointers = this.inputs.attached["pointers"];
  48368. if (pointers)
  48369. return pointers.pinchDeltaPercentage;
  48370. return 0;
  48371. },
  48372. set: function (value) {
  48373. var pointers = this.inputs.attached["pointers"];
  48374. if (pointers) {
  48375. pointers.pinchDeltaPercentage = value;
  48376. }
  48377. },
  48378. enumerable: true,
  48379. configurable: true
  48380. });
  48381. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48382. get: function () {
  48383. var pointers = this.inputs.attached["pointers"];
  48384. if (pointers)
  48385. return pointers.panningSensibility;
  48386. return 0;
  48387. },
  48388. set: function (value) {
  48389. var pointers = this.inputs.attached["pointers"];
  48390. if (pointers) {
  48391. pointers.panningSensibility = value;
  48392. }
  48393. },
  48394. enumerable: true,
  48395. configurable: true
  48396. });
  48397. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48398. get: function () {
  48399. var keyboard = this.inputs.attached["keyboard"];
  48400. if (keyboard)
  48401. return keyboard.keysUp;
  48402. return [];
  48403. },
  48404. set: function (value) {
  48405. var keyboard = this.inputs.attached["keyboard"];
  48406. if (keyboard)
  48407. keyboard.keysUp = value;
  48408. },
  48409. enumerable: true,
  48410. configurable: true
  48411. });
  48412. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48413. get: function () {
  48414. var keyboard = this.inputs.attached["keyboard"];
  48415. if (keyboard)
  48416. return keyboard.keysDown;
  48417. return [];
  48418. },
  48419. set: function (value) {
  48420. var keyboard = this.inputs.attached["keyboard"];
  48421. if (keyboard)
  48422. keyboard.keysDown = value;
  48423. },
  48424. enumerable: true,
  48425. configurable: true
  48426. });
  48427. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48428. get: function () {
  48429. var keyboard = this.inputs.attached["keyboard"];
  48430. if (keyboard)
  48431. return keyboard.keysLeft;
  48432. return [];
  48433. },
  48434. set: function (value) {
  48435. var keyboard = this.inputs.attached["keyboard"];
  48436. if (keyboard)
  48437. keyboard.keysLeft = value;
  48438. },
  48439. enumerable: true,
  48440. configurable: true
  48441. });
  48442. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48443. get: function () {
  48444. var keyboard = this.inputs.attached["keyboard"];
  48445. if (keyboard)
  48446. return keyboard.keysRight;
  48447. return [];
  48448. },
  48449. set: function (value) {
  48450. var keyboard = this.inputs.attached["keyboard"];
  48451. if (keyboard)
  48452. keyboard.keysRight = value;
  48453. },
  48454. enumerable: true,
  48455. configurable: true
  48456. });
  48457. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48458. get: function () {
  48459. var mousewheel = this.inputs.attached["mousewheel"];
  48460. if (mousewheel)
  48461. return mousewheel.wheelPrecision;
  48462. return 0;
  48463. },
  48464. set: function (value) {
  48465. var mousewheel = this.inputs.attached["mousewheel"];
  48466. if (mousewheel)
  48467. mousewheel.wheelPrecision = value;
  48468. },
  48469. enumerable: true,
  48470. configurable: true
  48471. });
  48472. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48473. get: function () {
  48474. var mousewheel = this.inputs.attached["mousewheel"];
  48475. if (mousewheel)
  48476. return mousewheel.wheelDeltaPercentage;
  48477. return 0;
  48478. },
  48479. set: function (value) {
  48480. var mousewheel = this.inputs.attached["mousewheel"];
  48481. if (mousewheel)
  48482. mousewheel.wheelDeltaPercentage = value;
  48483. },
  48484. enumerable: true,
  48485. configurable: true
  48486. });
  48487. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48488. get: function () {
  48489. return this._bouncingBehavior;
  48490. },
  48491. enumerable: true,
  48492. configurable: true
  48493. });
  48494. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48495. get: function () {
  48496. return this._bouncingBehavior != null;
  48497. },
  48498. set: function (value) {
  48499. if (value === this.useBouncingBehavior) {
  48500. return;
  48501. }
  48502. if (value) {
  48503. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48504. this.addBehavior(this._bouncingBehavior);
  48505. }
  48506. else if (this._bouncingBehavior) {
  48507. this.removeBehavior(this._bouncingBehavior);
  48508. this._bouncingBehavior = null;
  48509. }
  48510. },
  48511. enumerable: true,
  48512. configurable: true
  48513. });
  48514. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48515. get: function () {
  48516. return this._framingBehavior;
  48517. },
  48518. enumerable: true,
  48519. configurable: true
  48520. });
  48521. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48522. get: function () {
  48523. return this._framingBehavior != null;
  48524. },
  48525. set: function (value) {
  48526. if (value === this.useFramingBehavior) {
  48527. return;
  48528. }
  48529. if (value) {
  48530. this._framingBehavior = new BABYLON.FramingBehavior();
  48531. this.addBehavior(this._framingBehavior);
  48532. }
  48533. else if (this._framingBehavior) {
  48534. this.removeBehavior(this._framingBehavior);
  48535. this._framingBehavior = null;
  48536. }
  48537. },
  48538. enumerable: true,
  48539. configurable: true
  48540. });
  48541. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48542. get: function () {
  48543. return this._autoRotationBehavior;
  48544. },
  48545. enumerable: true,
  48546. configurable: true
  48547. });
  48548. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48549. get: function () {
  48550. return this._autoRotationBehavior != null;
  48551. },
  48552. set: function (value) {
  48553. if (value === this.useAutoRotationBehavior) {
  48554. return;
  48555. }
  48556. if (value) {
  48557. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48558. this.addBehavior(this._autoRotationBehavior);
  48559. }
  48560. else if (this._autoRotationBehavior) {
  48561. this.removeBehavior(this._autoRotationBehavior);
  48562. this._autoRotationBehavior = null;
  48563. }
  48564. },
  48565. enumerable: true,
  48566. configurable: true
  48567. });
  48568. // Cache
  48569. ArcRotateCamera.prototype._initCache = function () {
  48570. _super.prototype._initCache.call(this);
  48571. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48572. this._cache.alpha = undefined;
  48573. this._cache.beta = undefined;
  48574. this._cache.radius = undefined;
  48575. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48576. };
  48577. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48578. if (!ignoreParentClass) {
  48579. _super.prototype._updateCache.call(this);
  48580. }
  48581. this._cache._target.copyFrom(this._getTargetPosition());
  48582. this._cache.alpha = this.alpha;
  48583. this._cache.beta = this.beta;
  48584. this._cache.radius = this.radius;
  48585. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48586. };
  48587. ArcRotateCamera.prototype._getTargetPosition = function () {
  48588. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48589. var pos = this._targetHost.getAbsolutePosition();
  48590. if (this._targetBoundingCenter) {
  48591. pos.addToRef(this._targetBoundingCenter, this._target);
  48592. }
  48593. else {
  48594. this._target.copyFrom(pos);
  48595. }
  48596. }
  48597. var lockedTargetPosition = this._getLockedTargetPosition();
  48598. if (lockedTargetPosition) {
  48599. return lockedTargetPosition;
  48600. }
  48601. return this._target;
  48602. };
  48603. ArcRotateCamera.prototype.storeState = function () {
  48604. this._storedAlpha = this.alpha;
  48605. this._storedBeta = this.beta;
  48606. this._storedRadius = this.radius;
  48607. this._storedTarget = this._getTargetPosition().clone();
  48608. return _super.prototype.storeState.call(this);
  48609. };
  48610. /**
  48611. * Restored camera state. You must call storeState() first
  48612. */
  48613. ArcRotateCamera.prototype._restoreStateValues = function () {
  48614. if (!_super.prototype._restoreStateValues.call(this)) {
  48615. return false;
  48616. }
  48617. this.alpha = this._storedAlpha;
  48618. this.beta = this._storedBeta;
  48619. this.radius = this._storedRadius;
  48620. this.setTarget(this._storedTarget.clone());
  48621. this.inertialAlphaOffset = 0;
  48622. this.inertialBetaOffset = 0;
  48623. this.inertialRadiusOffset = 0;
  48624. this.inertialPanningX = 0;
  48625. this.inertialPanningY = 0;
  48626. return true;
  48627. };
  48628. // Synchronized
  48629. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48630. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48631. return false;
  48632. return this._cache._target.equals(this._getTargetPosition())
  48633. && this._cache.alpha === this.alpha
  48634. && this._cache.beta === this.beta
  48635. && this._cache.radius === this.radius
  48636. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48637. };
  48638. // Methods
  48639. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48640. var _this = this;
  48641. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48642. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48643. this._useCtrlForPanning = useCtrlForPanning;
  48644. this._panningMouseButton = panningMouseButton;
  48645. this.inputs.attachElement(element, noPreventDefault);
  48646. this._reset = function () {
  48647. _this.inertialAlphaOffset = 0;
  48648. _this.inertialBetaOffset = 0;
  48649. _this.inertialRadiusOffset = 0;
  48650. _this.inertialPanningX = 0;
  48651. _this.inertialPanningY = 0;
  48652. };
  48653. };
  48654. ArcRotateCamera.prototype.detachControl = function (element) {
  48655. this.inputs.detachElement(element);
  48656. if (this._reset) {
  48657. this._reset();
  48658. }
  48659. };
  48660. ArcRotateCamera.prototype._checkInputs = function () {
  48661. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48662. if (this._collisionTriggered) {
  48663. return;
  48664. }
  48665. this.inputs.checkInputs();
  48666. // Inertia
  48667. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48668. var inertialAlphaOffset = this.inertialAlphaOffset;
  48669. if (this.beta <= 0)
  48670. inertialAlphaOffset *= -1;
  48671. if (this.getScene().useRightHandedSystem)
  48672. inertialAlphaOffset *= -1;
  48673. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48674. inertialAlphaOffset *= -1;
  48675. this.alpha += inertialAlphaOffset;
  48676. this.beta += this.inertialBetaOffset;
  48677. this.radius -= this.inertialRadiusOffset;
  48678. this.inertialAlphaOffset *= this.inertia;
  48679. this.inertialBetaOffset *= this.inertia;
  48680. this.inertialRadiusOffset *= this.inertia;
  48681. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48682. this.inertialAlphaOffset = 0;
  48683. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48684. this.inertialBetaOffset = 0;
  48685. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48686. this.inertialRadiusOffset = 0;
  48687. }
  48688. // Panning inertia
  48689. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48690. if (!this._localDirection) {
  48691. this._localDirection = BABYLON.Vector3.Zero();
  48692. this._transformedDirection = BABYLON.Vector3.Zero();
  48693. }
  48694. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48695. this._localDirection.multiplyInPlace(this.panningAxis);
  48696. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48697. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48698. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48699. if (!this.panningAxis.y) {
  48700. this._transformedDirection.y = 0;
  48701. }
  48702. if (!this._targetHost) {
  48703. if (this.panningDistanceLimit) {
  48704. this._transformedDirection.addInPlace(this._target);
  48705. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48706. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48707. this._target.copyFrom(this._transformedDirection);
  48708. }
  48709. }
  48710. else {
  48711. this._target.addInPlace(this._transformedDirection);
  48712. }
  48713. }
  48714. this.inertialPanningX *= this.panningInertia;
  48715. this.inertialPanningY *= this.panningInertia;
  48716. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48717. this.inertialPanningX = 0;
  48718. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48719. this.inertialPanningY = 0;
  48720. }
  48721. // Limits
  48722. this._checkLimits();
  48723. _super.prototype._checkInputs.call(this);
  48724. };
  48725. ArcRotateCamera.prototype._checkLimits = function () {
  48726. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48727. if (this.allowUpsideDown && this.beta > Math.PI) {
  48728. this.beta = this.beta - (2 * Math.PI);
  48729. }
  48730. }
  48731. else {
  48732. if (this.beta < this.lowerBetaLimit) {
  48733. this.beta = this.lowerBetaLimit;
  48734. }
  48735. }
  48736. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48737. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48738. this.beta = this.beta + (2 * Math.PI);
  48739. }
  48740. }
  48741. else {
  48742. if (this.beta > this.upperBetaLimit) {
  48743. this.beta = this.upperBetaLimit;
  48744. }
  48745. }
  48746. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48747. this.alpha = this.lowerAlphaLimit;
  48748. }
  48749. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48750. this.alpha = this.upperAlphaLimit;
  48751. }
  48752. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48753. this.radius = this.lowerRadiusLimit;
  48754. }
  48755. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48756. this.radius = this.upperRadiusLimit;
  48757. }
  48758. };
  48759. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48760. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48761. this.radius = this._computationVector.length();
  48762. if (this.radius === 0) {
  48763. this.radius = 0.0001; // Just to avoid division by zero
  48764. }
  48765. // Alpha
  48766. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48767. if (this._computationVector.z < 0) {
  48768. this.alpha = 2 * Math.PI - this.alpha;
  48769. }
  48770. // Beta
  48771. this.beta = Math.acos(this._computationVector.y / this.radius);
  48772. this._checkLimits();
  48773. };
  48774. ArcRotateCamera.prototype.setPosition = function (position) {
  48775. if (this.position.equals(position)) {
  48776. return;
  48777. }
  48778. this.position.copyFrom(position);
  48779. this.rebuildAnglesAndRadius();
  48780. };
  48781. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48782. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48783. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48784. if (target.getBoundingInfo) {
  48785. if (toBoundingCenter) {
  48786. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48787. }
  48788. else {
  48789. this._targetBoundingCenter = null;
  48790. }
  48791. this._targetHost = target;
  48792. this._target = this._getTargetPosition();
  48793. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48794. }
  48795. else {
  48796. var newTarget = target;
  48797. var currentTarget = this._getTargetPosition();
  48798. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48799. return;
  48800. }
  48801. this._targetHost = null;
  48802. this._target = newTarget;
  48803. this._targetBoundingCenter = null;
  48804. this.onMeshTargetChangedObservable.notifyObservers(null);
  48805. }
  48806. this.rebuildAnglesAndRadius();
  48807. };
  48808. ArcRotateCamera.prototype._getViewMatrix = function () {
  48809. // Compute
  48810. var cosa = Math.cos(this.alpha);
  48811. var sina = Math.sin(this.alpha);
  48812. var cosb = Math.cos(this.beta);
  48813. var sinb = Math.sin(this.beta);
  48814. if (sinb === 0) {
  48815. sinb = 0.0001;
  48816. }
  48817. var target = this._getTargetPosition();
  48818. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48819. target.addToRef(this._computationVector, this._newPosition);
  48820. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48821. if (!this._collider) {
  48822. this._collider = new BABYLON.Collider();
  48823. }
  48824. this._collider._radius = this.collisionRadius;
  48825. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48826. this._collisionTriggered = true;
  48827. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48828. }
  48829. else {
  48830. this.position.copyFrom(this._newPosition);
  48831. var up = this.upVector;
  48832. if (this.allowUpsideDown && sinb < 0) {
  48833. up = up.clone();
  48834. up = up.negate();
  48835. }
  48836. this._computeViewMatrix(this.position, target, up);
  48837. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48838. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48839. }
  48840. this._currentTarget = target;
  48841. return this._viewMatrix;
  48842. };
  48843. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48844. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48845. meshes = meshes || this.getScene().meshes;
  48846. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48847. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48848. this.radius = distance * this.zoomOnFactor;
  48849. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48850. };
  48851. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48852. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48853. var meshesOrMinMaxVector;
  48854. var distance;
  48855. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48856. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48857. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48858. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48859. }
  48860. else { //minMaxVector and distance
  48861. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48862. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48863. distance = minMaxVectorAndDistance.distance;
  48864. }
  48865. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48866. if (!doNotUpdateMaxZ) {
  48867. this.maxZ = distance * 2;
  48868. }
  48869. };
  48870. /**
  48871. * @override
  48872. * Override Camera.createRigCamera
  48873. */
  48874. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48875. var alphaShift = 0;
  48876. switch (this.cameraRigMode) {
  48877. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48878. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48879. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48880. case BABYLON.Camera.RIG_MODE_VR:
  48881. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48882. break;
  48883. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48884. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48885. break;
  48886. }
  48887. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48888. rigCam._cameraRigParams = {};
  48889. return rigCam;
  48890. };
  48891. /**
  48892. * @override
  48893. * Override Camera._updateRigCameras
  48894. */
  48895. ArcRotateCamera.prototype._updateRigCameras = function () {
  48896. var camLeft = this._rigCameras[0];
  48897. var camRight = this._rigCameras[1];
  48898. camLeft.beta = camRight.beta = this.beta;
  48899. camLeft.radius = camRight.radius = this.radius;
  48900. switch (this.cameraRigMode) {
  48901. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48902. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48903. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48904. case BABYLON.Camera.RIG_MODE_VR:
  48905. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48906. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48907. break;
  48908. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48909. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48910. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48911. break;
  48912. }
  48913. _super.prototype._updateRigCameras.call(this);
  48914. };
  48915. ArcRotateCamera.prototype.dispose = function () {
  48916. this.inputs.clear();
  48917. _super.prototype.dispose.call(this);
  48918. };
  48919. ArcRotateCamera.prototype.getClassName = function () {
  48920. return "ArcRotateCamera";
  48921. };
  48922. __decorate([
  48923. BABYLON.serialize()
  48924. ], ArcRotateCamera.prototype, "alpha", void 0);
  48925. __decorate([
  48926. BABYLON.serialize()
  48927. ], ArcRotateCamera.prototype, "beta", void 0);
  48928. __decorate([
  48929. BABYLON.serialize()
  48930. ], ArcRotateCamera.prototype, "radius", void 0);
  48931. __decorate([
  48932. BABYLON.serializeAsVector3("target")
  48933. ], ArcRotateCamera.prototype, "_target", void 0);
  48934. __decorate([
  48935. BABYLON.serialize()
  48936. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48937. __decorate([
  48938. BABYLON.serialize()
  48939. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48940. __decorate([
  48941. BABYLON.serialize()
  48942. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48943. __decorate([
  48944. BABYLON.serialize()
  48945. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48946. __decorate([
  48947. BABYLON.serialize()
  48948. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48949. __decorate([
  48950. BABYLON.serialize()
  48951. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48952. __decorate([
  48953. BABYLON.serialize()
  48954. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48955. __decorate([
  48956. BABYLON.serialize()
  48957. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48958. __decorate([
  48959. BABYLON.serialize()
  48960. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48961. __decorate([
  48962. BABYLON.serialize()
  48963. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48964. __decorate([
  48965. BABYLON.serialize()
  48966. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48967. __decorate([
  48968. BABYLON.serialize()
  48969. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48970. __decorate([
  48971. BABYLON.serialize()
  48972. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48973. __decorate([
  48974. BABYLON.serializeAsVector3()
  48975. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48976. __decorate([
  48977. BABYLON.serialize()
  48978. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48979. __decorate([
  48980. BABYLON.serialize()
  48981. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48982. __decorate([
  48983. BABYLON.serialize()
  48984. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48985. return ArcRotateCamera;
  48986. }(BABYLON.TargetCamera));
  48987. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48988. })(BABYLON || (BABYLON = {}));
  48989. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48990. var BABYLON;
  48991. (function (BABYLON) {
  48992. /**
  48993. * The HemisphericLight simulates the ambient environment light,
  48994. * so the passed direction is the light reflection direction, not the incoming direction.
  48995. */
  48996. var HemisphericLight = /** @class */ (function (_super) {
  48997. __extends(HemisphericLight, _super);
  48998. /**
  48999. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49000. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49001. * The HemisphericLight can't cast shadows.
  49002. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49003. * @param name The friendly name of the light
  49004. * @param direction The direction of the light reflection
  49005. * @param scene The scene the light belongs to
  49006. */
  49007. function HemisphericLight(name, direction, scene) {
  49008. var _this = _super.call(this, name, scene) || this;
  49009. /**
  49010. * The groundColor is the light in the opposite direction to the one specified during creation.
  49011. * 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.
  49012. */
  49013. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49014. _this.direction = direction || BABYLON.Vector3.Up();
  49015. return _this;
  49016. }
  49017. HemisphericLight.prototype._buildUniformLayout = function () {
  49018. this._uniformBuffer.addUniform("vLightData", 4);
  49019. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49020. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49021. this._uniformBuffer.addUniform("vLightGround", 3);
  49022. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49023. this._uniformBuffer.addUniform("depthValues", 2);
  49024. this._uniformBuffer.create();
  49025. };
  49026. /**
  49027. * Returns the string "HemisphericLight".
  49028. * @return The class name
  49029. */
  49030. HemisphericLight.prototype.getClassName = function () {
  49031. return "HemisphericLight";
  49032. };
  49033. /**
  49034. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49035. * Returns the updated direction.
  49036. * @param target The target the direction should point to
  49037. * @return The computed direction
  49038. */
  49039. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49040. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49041. return this.direction;
  49042. };
  49043. /**
  49044. * Returns the shadow generator associated to the light.
  49045. * @returns Always null for hemispheric lights because it does not support shadows.
  49046. */
  49047. HemisphericLight.prototype.getShadowGenerator = function () {
  49048. return null;
  49049. };
  49050. /**
  49051. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49052. * @param effect The effect to update
  49053. * @param lightIndex The index of the light in the effect to update
  49054. * @returns The hemispheric light
  49055. */
  49056. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49057. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49058. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49059. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49060. return this;
  49061. };
  49062. /**
  49063. * @hidden internal use only.
  49064. */
  49065. HemisphericLight.prototype._getWorldMatrix = function () {
  49066. if (!this._worldMatrix) {
  49067. this._worldMatrix = BABYLON.Matrix.Identity();
  49068. }
  49069. return this._worldMatrix;
  49070. };
  49071. /**
  49072. * Returns the integer 3.
  49073. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49074. */
  49075. HemisphericLight.prototype.getTypeID = function () {
  49076. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49077. };
  49078. __decorate([
  49079. BABYLON.serializeAsColor3()
  49080. ], HemisphericLight.prototype, "groundColor", void 0);
  49081. __decorate([
  49082. BABYLON.serializeAsVector3()
  49083. ], HemisphericLight.prototype, "direction", void 0);
  49084. return HemisphericLight;
  49085. }(BABYLON.Light));
  49086. BABYLON.HemisphericLight = HemisphericLight;
  49087. })(BABYLON || (BABYLON = {}));
  49088. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49089. var BABYLON;
  49090. (function (BABYLON) {
  49091. /**
  49092. * Base implementation IShadowLight
  49093. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49094. */
  49095. var ShadowLight = /** @class */ (function (_super) {
  49096. __extends(ShadowLight, _super);
  49097. function ShadowLight() {
  49098. var _this = _super !== null && _super.apply(this, arguments) || this;
  49099. _this._needProjectionMatrixCompute = true;
  49100. return _this;
  49101. }
  49102. ShadowLight.prototype._setPosition = function (value) {
  49103. this._position = value;
  49104. };
  49105. Object.defineProperty(ShadowLight.prototype, "position", {
  49106. /**
  49107. * Sets the position the shadow will be casted from. Also use as the light position for both
  49108. * point and spot lights.
  49109. */
  49110. get: function () {
  49111. return this._position;
  49112. },
  49113. /**
  49114. * Sets the position the shadow will be casted from. Also use as the light position for both
  49115. * point and spot lights.
  49116. */
  49117. set: function (value) {
  49118. this._setPosition(value);
  49119. },
  49120. enumerable: true,
  49121. configurable: true
  49122. });
  49123. ShadowLight.prototype._setDirection = function (value) {
  49124. this._direction = value;
  49125. };
  49126. Object.defineProperty(ShadowLight.prototype, "direction", {
  49127. /**
  49128. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49129. * Also use as the light direction on spot and directional lights.
  49130. */
  49131. get: function () {
  49132. return this._direction;
  49133. },
  49134. /**
  49135. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49136. * Also use as the light direction on spot and directional lights.
  49137. */
  49138. set: function (value) {
  49139. this._setDirection(value);
  49140. },
  49141. enumerable: true,
  49142. configurable: true
  49143. });
  49144. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49145. /**
  49146. * Gets the shadow projection clipping minimum z value.
  49147. */
  49148. get: function () {
  49149. return this._shadowMinZ;
  49150. },
  49151. /**
  49152. * Sets the shadow projection clipping minimum z value.
  49153. */
  49154. set: function (value) {
  49155. this._shadowMinZ = value;
  49156. this.forceProjectionMatrixCompute();
  49157. },
  49158. enumerable: true,
  49159. configurable: true
  49160. });
  49161. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49162. /**
  49163. * Sets the shadow projection clipping maximum z value.
  49164. */
  49165. get: function () {
  49166. return this._shadowMaxZ;
  49167. },
  49168. /**
  49169. * Gets the shadow projection clipping maximum z value.
  49170. */
  49171. set: function (value) {
  49172. this._shadowMaxZ = value;
  49173. this.forceProjectionMatrixCompute();
  49174. },
  49175. enumerable: true,
  49176. configurable: true
  49177. });
  49178. /**
  49179. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49180. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49181. */
  49182. ShadowLight.prototype.computeTransformedInformation = function () {
  49183. if (this.parent && this.parent.getWorldMatrix) {
  49184. if (!this.transformedPosition) {
  49185. this.transformedPosition = BABYLON.Vector3.Zero();
  49186. }
  49187. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49188. // In case the direction is present.
  49189. if (this.direction) {
  49190. if (!this.transformedDirection) {
  49191. this.transformedDirection = BABYLON.Vector3.Zero();
  49192. }
  49193. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49194. }
  49195. return true;
  49196. }
  49197. return false;
  49198. };
  49199. /**
  49200. * Return the depth scale used for the shadow map.
  49201. * @returns the depth scale.
  49202. */
  49203. ShadowLight.prototype.getDepthScale = function () {
  49204. return 50.0;
  49205. };
  49206. /**
  49207. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49208. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49209. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49210. */
  49211. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49212. return this.transformedDirection ? this.transformedDirection : this.direction;
  49213. };
  49214. /**
  49215. * Returns the ShadowLight absolute position in the World.
  49216. * @returns the position vector in world space
  49217. */
  49218. ShadowLight.prototype.getAbsolutePosition = function () {
  49219. return this.transformedPosition ? this.transformedPosition : this.position;
  49220. };
  49221. /**
  49222. * Sets the ShadowLight direction toward the passed target.
  49223. * @param target The point tot target in local space
  49224. * @returns the updated ShadowLight direction
  49225. */
  49226. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49227. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49228. return this.direction;
  49229. };
  49230. /**
  49231. * Returns the light rotation in euler definition.
  49232. * @returns the x y z rotation in local space.
  49233. */
  49234. ShadowLight.prototype.getRotation = function () {
  49235. this.direction.normalize();
  49236. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49237. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49238. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49239. };
  49240. /**
  49241. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49242. * @returns true if a cube texture needs to be use
  49243. */
  49244. ShadowLight.prototype.needCube = function () {
  49245. return false;
  49246. };
  49247. /**
  49248. * Detects if the projection matrix requires to be recomputed this frame.
  49249. * @returns true if it requires to be recomputed otherwise, false.
  49250. */
  49251. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49252. return this._needProjectionMatrixCompute;
  49253. };
  49254. /**
  49255. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49256. */
  49257. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49258. this._needProjectionMatrixCompute = true;
  49259. };
  49260. /**
  49261. * Get the world matrix of the sahdow lights.
  49262. * @hidden Internal Use Only
  49263. */
  49264. ShadowLight.prototype._getWorldMatrix = function () {
  49265. if (!this._worldMatrix) {
  49266. this._worldMatrix = BABYLON.Matrix.Identity();
  49267. }
  49268. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49269. return this._worldMatrix;
  49270. };
  49271. /**
  49272. * Gets the minZ used for shadow according to both the scene and the light.
  49273. * @param activeCamera The camera we are returning the min for
  49274. * @returns the depth min z
  49275. */
  49276. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49277. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49278. };
  49279. /**
  49280. * Gets the maxZ used for shadow according to both the scene and the light.
  49281. * @param activeCamera The camera we are returning the max for
  49282. * @returns the depth max z
  49283. */
  49284. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49285. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49286. };
  49287. /**
  49288. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49289. * @param matrix The materix to updated with the projection information
  49290. * @param viewMatrix The transform matrix of the light
  49291. * @param renderList The list of mesh to render in the map
  49292. * @returns The current light
  49293. */
  49294. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49295. if (this.customProjectionMatrixBuilder) {
  49296. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49297. }
  49298. else {
  49299. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49300. }
  49301. return this;
  49302. };
  49303. __decorate([
  49304. BABYLON.serializeAsVector3()
  49305. ], ShadowLight.prototype, "position", null);
  49306. __decorate([
  49307. BABYLON.serializeAsVector3()
  49308. ], ShadowLight.prototype, "direction", null);
  49309. __decorate([
  49310. BABYLON.serialize()
  49311. ], ShadowLight.prototype, "shadowMinZ", null);
  49312. __decorate([
  49313. BABYLON.serialize()
  49314. ], ShadowLight.prototype, "shadowMaxZ", null);
  49315. return ShadowLight;
  49316. }(BABYLON.Light));
  49317. BABYLON.ShadowLight = ShadowLight;
  49318. })(BABYLON || (BABYLON = {}));
  49319. //# sourceMappingURL=babylon.shadowLight.js.map
  49320. var BABYLON;
  49321. (function (BABYLON) {
  49322. /**
  49323. * A point light is a light defined by an unique point in world space.
  49324. * The light is emitted in every direction from this point.
  49325. * A good example of a point light is a standard light bulb.
  49326. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49327. */
  49328. var PointLight = /** @class */ (function (_super) {
  49329. __extends(PointLight, _super);
  49330. /**
  49331. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49332. * A PointLight emits the light in every direction.
  49333. * It can cast shadows.
  49334. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49335. * ```javascript
  49336. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49337. * ```
  49338. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49339. * @param name The light friendly name
  49340. * @param position The position of the point light in the scene
  49341. * @param scene The scene the lights belongs to
  49342. */
  49343. function PointLight(name, position, scene) {
  49344. var _this = _super.call(this, name, scene) || this;
  49345. _this._shadowAngle = Math.PI / 2;
  49346. _this.position = position;
  49347. return _this;
  49348. }
  49349. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49350. /**
  49351. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49352. * This specifies what angle the shadow will use to be created.
  49353. *
  49354. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49355. */
  49356. get: function () {
  49357. return this._shadowAngle;
  49358. },
  49359. /**
  49360. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49361. * This specifies what angle the shadow will use to be created.
  49362. *
  49363. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49364. */
  49365. set: function (value) {
  49366. this._shadowAngle = value;
  49367. this.forceProjectionMatrixCompute();
  49368. },
  49369. enumerable: true,
  49370. configurable: true
  49371. });
  49372. Object.defineProperty(PointLight.prototype, "direction", {
  49373. /**
  49374. * Gets the direction if it has been set.
  49375. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49376. */
  49377. get: function () {
  49378. return this._direction;
  49379. },
  49380. /**
  49381. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49382. */
  49383. set: function (value) {
  49384. var previousNeedCube = this.needCube();
  49385. this._direction = value;
  49386. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49387. this._shadowGenerator.recreateShadowMap();
  49388. }
  49389. },
  49390. enumerable: true,
  49391. configurable: true
  49392. });
  49393. /**
  49394. * Returns the string "PointLight"
  49395. * @returns the class name
  49396. */
  49397. PointLight.prototype.getClassName = function () {
  49398. return "PointLight";
  49399. };
  49400. /**
  49401. * Returns the integer 0.
  49402. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49403. */
  49404. PointLight.prototype.getTypeID = function () {
  49405. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49406. };
  49407. /**
  49408. * Specifies wether or not the shadowmap should be a cube texture.
  49409. * @returns true if the shadowmap needs to be a cube texture.
  49410. */
  49411. PointLight.prototype.needCube = function () {
  49412. return !this.direction;
  49413. };
  49414. /**
  49415. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49416. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49417. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49418. */
  49419. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49420. if (this.direction) {
  49421. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49422. }
  49423. else {
  49424. switch (faceIndex) {
  49425. case 0:
  49426. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49427. case 1:
  49428. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49429. case 2:
  49430. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49431. case 3:
  49432. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49433. case 4:
  49434. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49435. case 5:
  49436. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49437. }
  49438. }
  49439. return BABYLON.Vector3.Zero();
  49440. };
  49441. /**
  49442. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49443. * - fov = PI / 2
  49444. * - aspect ratio : 1.0
  49445. * - z-near and far equal to the active camera minZ and maxZ.
  49446. * Returns the PointLight.
  49447. */
  49448. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49449. var activeCamera = this.getScene().activeCamera;
  49450. if (!activeCamera) {
  49451. return;
  49452. }
  49453. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49454. };
  49455. PointLight.prototype._buildUniformLayout = function () {
  49456. this._uniformBuffer.addUniform("vLightData", 4);
  49457. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49458. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49459. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49460. this._uniformBuffer.addUniform("depthValues", 2);
  49461. this._uniformBuffer.create();
  49462. };
  49463. /**
  49464. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49465. * @param effect The effect to update
  49466. * @param lightIndex The index of the light in the effect to update
  49467. * @returns The point light
  49468. */
  49469. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49470. if (this.computeTransformedInformation()) {
  49471. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49472. return this;
  49473. }
  49474. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49475. return this;
  49476. };
  49477. __decorate([
  49478. BABYLON.serialize()
  49479. ], PointLight.prototype, "shadowAngle", null);
  49480. return PointLight;
  49481. }(BABYLON.ShadowLight));
  49482. BABYLON.PointLight = PointLight;
  49483. })(BABYLON || (BABYLON = {}));
  49484. //# sourceMappingURL=babylon.pointLight.js.map
  49485. var BABYLON;
  49486. (function (BABYLON) {
  49487. /**
  49488. * A directional light is defined by a direction (what a surprise!).
  49489. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49490. * 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.
  49491. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49492. */
  49493. var DirectionalLight = /** @class */ (function (_super) {
  49494. __extends(DirectionalLight, _super);
  49495. /**
  49496. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49497. * The directional light is emitted from everywhere in the given direction.
  49498. * It can cast shawdows.
  49499. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49500. * @param name The friendly name of the light
  49501. * @param direction The direction of the light
  49502. * @param scene The scene the light belongs to
  49503. */
  49504. function DirectionalLight(name, direction, scene) {
  49505. var _this = _super.call(this, name, scene) || this;
  49506. _this._shadowFrustumSize = 0;
  49507. _this._shadowOrthoScale = 0.1;
  49508. /**
  49509. * Automatically compute the projection matrix to best fit (including all the casters)
  49510. * on each frame.
  49511. */
  49512. _this.autoUpdateExtends = true;
  49513. // Cache
  49514. _this._orthoLeft = Number.MAX_VALUE;
  49515. _this._orthoRight = Number.MIN_VALUE;
  49516. _this._orthoTop = Number.MIN_VALUE;
  49517. _this._orthoBottom = Number.MAX_VALUE;
  49518. _this.position = direction.scale(-1.0);
  49519. _this.direction = direction;
  49520. return _this;
  49521. }
  49522. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49523. /**
  49524. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49525. */
  49526. get: function () {
  49527. return this._shadowFrustumSize;
  49528. },
  49529. /**
  49530. * Specifies a fix frustum size for the shadow generation.
  49531. */
  49532. set: function (value) {
  49533. this._shadowFrustumSize = value;
  49534. this.forceProjectionMatrixCompute();
  49535. },
  49536. enumerable: true,
  49537. configurable: true
  49538. });
  49539. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49540. /**
  49541. * Gets the shadow projection scale against the optimal computed one.
  49542. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49543. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49544. */
  49545. get: function () {
  49546. return this._shadowOrthoScale;
  49547. },
  49548. /**
  49549. * Sets the shadow projection scale against the optimal computed one.
  49550. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49551. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49552. */
  49553. set: function (value) {
  49554. this._shadowOrthoScale = value;
  49555. this.forceProjectionMatrixCompute();
  49556. },
  49557. enumerable: true,
  49558. configurable: true
  49559. });
  49560. /**
  49561. * Returns the string "DirectionalLight".
  49562. * @return The class name
  49563. */
  49564. DirectionalLight.prototype.getClassName = function () {
  49565. return "DirectionalLight";
  49566. };
  49567. /**
  49568. * Returns the integer 1.
  49569. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49570. */
  49571. DirectionalLight.prototype.getTypeID = function () {
  49572. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49573. };
  49574. /**
  49575. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49576. * Returns the DirectionalLight Shadow projection matrix.
  49577. */
  49578. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49579. if (this.shadowFrustumSize > 0) {
  49580. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49581. }
  49582. else {
  49583. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49584. }
  49585. };
  49586. /**
  49587. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49588. * Returns the DirectionalLight Shadow projection matrix.
  49589. */
  49590. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49591. var activeCamera = this.getScene().activeCamera;
  49592. if (!activeCamera) {
  49593. return;
  49594. }
  49595. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49596. };
  49597. /**
  49598. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49599. * Returns the DirectionalLight Shadow projection matrix.
  49600. */
  49601. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49602. var activeCamera = this.getScene().activeCamera;
  49603. if (!activeCamera) {
  49604. return;
  49605. }
  49606. // Check extends
  49607. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49608. var tempVector3 = BABYLON.Vector3.Zero();
  49609. this._orthoLeft = Number.MAX_VALUE;
  49610. this._orthoRight = Number.MIN_VALUE;
  49611. this._orthoTop = Number.MIN_VALUE;
  49612. this._orthoBottom = Number.MAX_VALUE;
  49613. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49614. var mesh = renderList[meshIndex];
  49615. if (!mesh) {
  49616. continue;
  49617. }
  49618. var boundingInfo = mesh.getBoundingInfo();
  49619. var boundingBox = boundingInfo.boundingBox;
  49620. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49621. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49622. if (tempVector3.x < this._orthoLeft)
  49623. this._orthoLeft = tempVector3.x;
  49624. if (tempVector3.y < this._orthoBottom)
  49625. this._orthoBottom = tempVector3.y;
  49626. if (tempVector3.x > this._orthoRight)
  49627. this._orthoRight = tempVector3.x;
  49628. if (tempVector3.y > this._orthoTop)
  49629. this._orthoTop = tempVector3.y;
  49630. }
  49631. }
  49632. }
  49633. var xOffset = this._orthoRight - this._orthoLeft;
  49634. var yOffset = this._orthoTop - this._orthoBottom;
  49635. 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);
  49636. };
  49637. DirectionalLight.prototype._buildUniformLayout = function () {
  49638. this._uniformBuffer.addUniform("vLightData", 4);
  49639. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49640. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49641. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49642. this._uniformBuffer.addUniform("depthValues", 2);
  49643. this._uniformBuffer.create();
  49644. };
  49645. /**
  49646. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49647. * @param effect The effect to update
  49648. * @param lightIndex The index of the light in the effect to update
  49649. * @returns The directional light
  49650. */
  49651. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49652. if (this.computeTransformedInformation()) {
  49653. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49654. return this;
  49655. }
  49656. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49657. return this;
  49658. };
  49659. /**
  49660. * Gets the minZ used for shadow according to both the scene and the light.
  49661. *
  49662. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49663. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49664. * @param activeCamera The camera we are returning the min for
  49665. * @returns the depth min z
  49666. */
  49667. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49668. return 1;
  49669. };
  49670. /**
  49671. * Gets the maxZ used for shadow according to both the scene and the light.
  49672. *
  49673. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49674. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49675. * @param activeCamera The camera we are returning the max for
  49676. * @returns the depth max z
  49677. */
  49678. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49679. return 1;
  49680. };
  49681. __decorate([
  49682. BABYLON.serialize()
  49683. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49684. __decorate([
  49685. BABYLON.serialize()
  49686. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49687. __decorate([
  49688. BABYLON.serialize()
  49689. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49690. return DirectionalLight;
  49691. }(BABYLON.ShadowLight));
  49692. BABYLON.DirectionalLight = DirectionalLight;
  49693. })(BABYLON || (BABYLON = {}));
  49694. //# sourceMappingURL=babylon.directionalLight.js.map
  49695. var BABYLON;
  49696. (function (BABYLON) {
  49697. /**
  49698. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49699. * These values define a cone of light starting from the position, emitting toward the direction.
  49700. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49701. * and the exponent defines the speed of the decay of the light with distance (reach).
  49702. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49703. */
  49704. var SpotLight = /** @class */ (function (_super) {
  49705. __extends(SpotLight, _super);
  49706. /**
  49707. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49708. * It can cast shadows.
  49709. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49710. * @param name The light friendly name
  49711. * @param position The position of the spot light in the scene
  49712. * @param direction The direction of the light in the scene
  49713. * @param angle The cone angle of the light in Radians
  49714. * @param exponent The light decay speed with the distance from the emission spot
  49715. * @param scene The scene the lights belongs to
  49716. */
  49717. function SpotLight(name, position, direction, angle, exponent, scene) {
  49718. var _this = _super.call(this, name, scene) || this;
  49719. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49720. _this._projectionTextureLightNear = 1e-6;
  49721. _this._projectionTextureLightFar = 1000.0;
  49722. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49723. _this._projectionTextureViewLightDirty = true;
  49724. _this._projectionTextureProjectionLightDirty = true;
  49725. _this._projectionTextureDirty = true;
  49726. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49727. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49728. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49729. _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);
  49730. _this.position = position;
  49731. _this.direction = direction;
  49732. _this.angle = angle;
  49733. _this.exponent = exponent;
  49734. return _this;
  49735. }
  49736. Object.defineProperty(SpotLight.prototype, "angle", {
  49737. /**
  49738. * Gets the cone angle of the spot light in Radians.
  49739. */
  49740. get: function () {
  49741. return this._angle;
  49742. },
  49743. /**
  49744. * Sets the cone angle of the spot light in Radians.
  49745. */
  49746. set: function (value) {
  49747. this._angle = value;
  49748. this._projectionTextureProjectionLightDirty = true;
  49749. this.forceProjectionMatrixCompute();
  49750. },
  49751. enumerable: true,
  49752. configurable: true
  49753. });
  49754. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49755. /**
  49756. * Allows scaling the angle of the light for shadow generation only.
  49757. */
  49758. get: function () {
  49759. return this._shadowAngleScale;
  49760. },
  49761. /**
  49762. * Allows scaling the angle of the light for shadow generation only.
  49763. */
  49764. set: function (value) {
  49765. this._shadowAngleScale = value;
  49766. this.forceProjectionMatrixCompute();
  49767. },
  49768. enumerable: true,
  49769. configurable: true
  49770. });
  49771. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49772. /**
  49773. * Allows reading the projecton texture
  49774. */
  49775. get: function () {
  49776. return this._projectionTextureMatrix;
  49777. },
  49778. enumerable: true,
  49779. configurable: true
  49780. });
  49781. ;
  49782. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49783. /**
  49784. * Gets the near clip of the Spotlight for texture projection.
  49785. */
  49786. get: function () {
  49787. return this._projectionTextureLightNear;
  49788. },
  49789. /**
  49790. * Sets the near clip of the Spotlight for texture projection.
  49791. */
  49792. set: function (value) {
  49793. this._projectionTextureLightNear = value;
  49794. this._projectionTextureProjectionLightDirty = true;
  49795. },
  49796. enumerable: true,
  49797. configurable: true
  49798. });
  49799. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49800. /**
  49801. * Gets the far clip of the Spotlight for texture projection.
  49802. */
  49803. get: function () {
  49804. return this._projectionTextureLightFar;
  49805. },
  49806. /**
  49807. * Sets the far clip of the Spotlight for texture projection.
  49808. */
  49809. set: function (value) {
  49810. this._projectionTextureLightFar = value;
  49811. this._projectionTextureProjectionLightDirty = true;
  49812. },
  49813. enumerable: true,
  49814. configurable: true
  49815. });
  49816. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49817. /**
  49818. * Gets the Up vector of the Spotlight for texture projection.
  49819. */
  49820. get: function () {
  49821. return this._projectionTextureUpDirection;
  49822. },
  49823. /**
  49824. * Sets the Up vector of the Spotlight for texture projection.
  49825. */
  49826. set: function (value) {
  49827. this._projectionTextureUpDirection = value;
  49828. this._projectionTextureProjectionLightDirty = true;
  49829. },
  49830. enumerable: true,
  49831. configurable: true
  49832. });
  49833. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49834. /**
  49835. * Gets the projection texture of the light.
  49836. */
  49837. get: function () {
  49838. return this._projectionTexture;
  49839. },
  49840. /**
  49841. * Sets the projection texture of the light.
  49842. */
  49843. set: function (value) {
  49844. this._projectionTexture = value;
  49845. this._projectionTextureDirty = true;
  49846. },
  49847. enumerable: true,
  49848. configurable: true
  49849. });
  49850. /**
  49851. * Returns the string "SpotLight".
  49852. * @returns the class name
  49853. */
  49854. SpotLight.prototype.getClassName = function () {
  49855. return "SpotLight";
  49856. };
  49857. /**
  49858. * Returns the integer 2.
  49859. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49860. */
  49861. SpotLight.prototype.getTypeID = function () {
  49862. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49863. };
  49864. /**
  49865. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49866. */
  49867. SpotLight.prototype._setDirection = function (value) {
  49868. _super.prototype._setDirection.call(this, value);
  49869. this._projectionTextureViewLightDirty = true;
  49870. };
  49871. /**
  49872. * Overrides the position setter to recompute the projection texture view light Matrix.
  49873. */
  49874. SpotLight.prototype._setPosition = function (value) {
  49875. _super.prototype._setPosition.call(this, value);
  49876. this._projectionTextureViewLightDirty = true;
  49877. };
  49878. /**
  49879. * 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.
  49880. * Returns the SpotLight.
  49881. */
  49882. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49883. var activeCamera = this.getScene().activeCamera;
  49884. if (!activeCamera) {
  49885. return;
  49886. }
  49887. this._shadowAngleScale = this._shadowAngleScale || 1;
  49888. var angle = this._shadowAngleScale * this._angle;
  49889. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49890. };
  49891. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49892. this._projectionTextureViewLightDirty = false;
  49893. this._projectionTextureDirty = true;
  49894. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49895. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49896. };
  49897. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49898. this._projectionTextureProjectionLightDirty = false;
  49899. this._projectionTextureDirty = true;
  49900. var light_far = this.projectionTextureLightFar;
  49901. var light_near = this.projectionTextureLightNear;
  49902. var P = light_far / (light_far - light_near);
  49903. var Q = -P * light_near;
  49904. var S = 1.0 / Math.tan(this._angle / 2.0);
  49905. var A = 1.0;
  49906. 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);
  49907. };
  49908. /**
  49909. * Main function for light texture projection matrix computing.
  49910. */
  49911. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49912. this._projectionTextureDirty = false;
  49913. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49914. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49915. };
  49916. SpotLight.prototype._buildUniformLayout = function () {
  49917. this._uniformBuffer.addUniform("vLightData", 4);
  49918. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49919. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49920. this._uniformBuffer.addUniform("vLightDirection", 3);
  49921. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49922. this._uniformBuffer.addUniform("depthValues", 2);
  49923. this._uniformBuffer.create();
  49924. };
  49925. /**
  49926. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49927. * @param effect The effect to update
  49928. * @param lightIndex The index of the light in the effect to update
  49929. * @returns The spot light
  49930. */
  49931. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49932. var normalizeDirection;
  49933. if (this.computeTransformedInformation()) {
  49934. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49935. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49936. }
  49937. else {
  49938. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49939. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49940. }
  49941. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49942. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49943. if (this._projectionTextureViewLightDirty) {
  49944. this._computeProjectionTextureViewLightMatrix();
  49945. }
  49946. if (this._projectionTextureProjectionLightDirty) {
  49947. this._computeProjectionTextureProjectionLightMatrix();
  49948. }
  49949. if (this._projectionTextureDirty) {
  49950. this._computeProjectionTextureMatrix();
  49951. }
  49952. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49953. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49954. }
  49955. return this;
  49956. };
  49957. /**
  49958. * Disposes the light and the associated resources.
  49959. */
  49960. SpotLight.prototype.dispose = function () {
  49961. _super.prototype.dispose.call(this);
  49962. if (this._projectionTexture) {
  49963. this._projectionTexture.dispose();
  49964. }
  49965. };
  49966. __decorate([
  49967. BABYLON.serialize()
  49968. ], SpotLight.prototype, "angle", null);
  49969. __decorate([
  49970. BABYLON.serialize()
  49971. ], SpotLight.prototype, "shadowAngleScale", null);
  49972. __decorate([
  49973. BABYLON.serialize()
  49974. ], SpotLight.prototype, "exponent", void 0);
  49975. __decorate([
  49976. BABYLON.serialize()
  49977. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49978. __decorate([
  49979. BABYLON.serialize()
  49980. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49981. __decorate([
  49982. BABYLON.serialize()
  49983. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49984. __decorate([
  49985. BABYLON.serializeAsTexture("projectedLightTexture")
  49986. ], SpotLight.prototype, "_projectionTexture", void 0);
  49987. return SpotLight;
  49988. }(BABYLON.ShadowLight));
  49989. BABYLON.SpotLight = SpotLight;
  49990. })(BABYLON || (BABYLON = {}));
  49991. //# sourceMappingURL=babylon.spotLight.js.map
  49992. var BABYLON;
  49993. (function (BABYLON) {
  49994. /**
  49995. * Class used to override all child animations of a given target
  49996. */
  49997. var AnimationPropertiesOverride = /** @class */ (function () {
  49998. function AnimationPropertiesOverride() {
  49999. /**
  50000. * Gets or sets a value indicating if animation blending must be used
  50001. */
  50002. this.enableBlending = false;
  50003. /**
  50004. * Gets or sets the blending speed to use when enableBlending is true
  50005. */
  50006. this.blendingSpeed = 0.01;
  50007. /**
  50008. * Gets or sets the default loop mode to use
  50009. */
  50010. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50011. }
  50012. return AnimationPropertiesOverride;
  50013. }());
  50014. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50015. })(BABYLON || (BABYLON = {}));
  50016. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50017. var BABYLON;
  50018. (function (BABYLON) {
  50019. /**
  50020. * Represents the range of an animation
  50021. */
  50022. var AnimationRange = /** @class */ (function () {
  50023. /**
  50024. * Initializes the range of an animation
  50025. * @param name The name of the animation range
  50026. * @param from The starting frame of the animation
  50027. * @param to The ending frame of the animation
  50028. */
  50029. function AnimationRange(
  50030. /**The name of the animation range**/
  50031. name,
  50032. /**The starting frame of the animation */
  50033. from,
  50034. /**The ending frame of the animation*/
  50035. to) {
  50036. this.name = name;
  50037. this.from = from;
  50038. this.to = to;
  50039. }
  50040. /**
  50041. * Makes a copy of the animation range
  50042. * @returns A copy of the animation range
  50043. */
  50044. AnimationRange.prototype.clone = function () {
  50045. return new AnimationRange(this.name, this.from, this.to);
  50046. };
  50047. return AnimationRange;
  50048. }());
  50049. BABYLON.AnimationRange = AnimationRange;
  50050. /**
  50051. * Composed of a frame, and an action function
  50052. */
  50053. var AnimationEvent = /** @class */ (function () {
  50054. /**
  50055. * Initializes the animation event
  50056. * @param frame The frame for which the event is triggered
  50057. * @param action The event to perform when triggered
  50058. * @param onlyOnce Specifies if the event should be triggered only once
  50059. */
  50060. function AnimationEvent(
  50061. /** The frame for which the event is triggered **/
  50062. frame,
  50063. /** The event to perform when triggered **/
  50064. action,
  50065. /** Specifies if the event should be triggered only once**/
  50066. onlyOnce) {
  50067. this.frame = frame;
  50068. this.action = action;
  50069. this.onlyOnce = onlyOnce;
  50070. /**
  50071. * Specifies if the animation event is done
  50072. */
  50073. this.isDone = false;
  50074. }
  50075. return AnimationEvent;
  50076. }());
  50077. BABYLON.AnimationEvent = AnimationEvent;
  50078. /**
  50079. * A cursor which tracks a point on a path
  50080. */
  50081. var PathCursor = /** @class */ (function () {
  50082. /**
  50083. * Initializes the path cursor
  50084. * @param path The path to track
  50085. */
  50086. function PathCursor(path) {
  50087. this.path = path;
  50088. /**
  50089. * Stores path cursor callbacks for when an onchange event is triggered
  50090. */
  50091. this._onchange = new Array();
  50092. /**
  50093. * The value of the path cursor
  50094. */
  50095. this.value = 0;
  50096. /**
  50097. * The animation array of the path cursor
  50098. */
  50099. this.animations = new Array();
  50100. }
  50101. /**
  50102. * Gets the cursor point on the path
  50103. * @returns A point on the path cursor at the cursor location
  50104. */
  50105. PathCursor.prototype.getPoint = function () {
  50106. var point = this.path.getPointAtLengthPosition(this.value);
  50107. return new BABYLON.Vector3(point.x, 0, point.y);
  50108. };
  50109. /**
  50110. * Moves the cursor ahead by the step amount
  50111. * @param step The amount to move the cursor forward
  50112. * @returns This path cursor
  50113. */
  50114. PathCursor.prototype.moveAhead = function (step) {
  50115. if (step === void 0) { step = 0.002; }
  50116. this.move(step);
  50117. return this;
  50118. };
  50119. /**
  50120. * Moves the cursor behind by the step amount
  50121. * @param step The amount to move the cursor back
  50122. * @returns This path cursor
  50123. */
  50124. PathCursor.prototype.moveBack = function (step) {
  50125. if (step === void 0) { step = 0.002; }
  50126. this.move(-step);
  50127. return this;
  50128. };
  50129. /**
  50130. * Moves the cursor by the step amount
  50131. * If the step amount is greater than one, an exception is thrown
  50132. * @param step The amount to move the cursor
  50133. * @returns This path cursor
  50134. */
  50135. PathCursor.prototype.move = function (step) {
  50136. if (Math.abs(step) > 1) {
  50137. throw "step size should be less than 1.";
  50138. }
  50139. this.value += step;
  50140. this.ensureLimits();
  50141. this.raiseOnChange();
  50142. return this;
  50143. };
  50144. /**
  50145. * Ensures that the value is limited between zero and one
  50146. * @returns This path cursor
  50147. */
  50148. PathCursor.prototype.ensureLimits = function () {
  50149. while (this.value > 1) {
  50150. this.value -= 1;
  50151. }
  50152. while (this.value < 0) {
  50153. this.value += 1;
  50154. }
  50155. return this;
  50156. };
  50157. /**
  50158. * Runs onchange callbacks on change (used by the animation engine)
  50159. * @returns This path cursor
  50160. */
  50161. PathCursor.prototype.raiseOnChange = function () {
  50162. var _this = this;
  50163. this._onchange.forEach(function (f) { return f(_this); });
  50164. return this;
  50165. };
  50166. /**
  50167. * Executes a function on change
  50168. * @param f A path cursor onchange callback
  50169. * @returns This path cursor
  50170. */
  50171. PathCursor.prototype.onchange = function (f) {
  50172. this._onchange.push(f);
  50173. return this;
  50174. };
  50175. return PathCursor;
  50176. }());
  50177. BABYLON.PathCursor = PathCursor;
  50178. /**
  50179. * Enum for the animation key frame interpolation type
  50180. */
  50181. var AnimationKeyInterpolation;
  50182. (function (AnimationKeyInterpolation) {
  50183. /**
  50184. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50185. */
  50186. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50187. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50188. /**
  50189. * Class used to store any kind of animation
  50190. */
  50191. var Animation = /** @class */ (function () {
  50192. /**
  50193. * Initializes the animation
  50194. * @param name Name of the animation
  50195. * @param targetProperty Property to animate
  50196. * @param framePerSecond The frames per second of the animation
  50197. * @param dataType The data type of the animation
  50198. * @param loopMode The loop mode of the animation
  50199. * @param enableBlendings Specifies if blending should be enabled
  50200. */
  50201. function Animation(
  50202. /**Name of the animation */
  50203. name,
  50204. /**Property to animate */
  50205. targetProperty,
  50206. /**The frames per second of the animation */
  50207. framePerSecond,
  50208. /**The data type of the animation */
  50209. dataType,
  50210. /**The loop mode of the animation */
  50211. loopMode,
  50212. /**Specifies if blending should be enabled */
  50213. enableBlending) {
  50214. this.name = name;
  50215. this.targetProperty = targetProperty;
  50216. this.framePerSecond = framePerSecond;
  50217. this.dataType = dataType;
  50218. this.loopMode = loopMode;
  50219. this.enableBlending = enableBlending;
  50220. /**
  50221. * @hidden Internal use only
  50222. */
  50223. this._runtimeAnimations = new Array();
  50224. /**
  50225. * The set of event that will be linked to this animation
  50226. */
  50227. this._events = new Array();
  50228. /**
  50229. * Stores the blending speed of the animation
  50230. */
  50231. this.blendingSpeed = 0.01;
  50232. /**
  50233. * Stores the animation ranges for the animation
  50234. */
  50235. this._ranges = {};
  50236. this.targetPropertyPath = targetProperty.split(".");
  50237. this.dataType = dataType;
  50238. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50239. }
  50240. /**
  50241. * @hidden Internal use
  50242. */
  50243. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50244. var dataType = undefined;
  50245. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50246. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50247. }
  50248. else if (from instanceof BABYLON.Quaternion) {
  50249. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50250. }
  50251. else if (from instanceof BABYLON.Vector3) {
  50252. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50253. }
  50254. else if (from instanceof BABYLON.Vector2) {
  50255. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50256. }
  50257. else if (from instanceof BABYLON.Color3) {
  50258. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50259. }
  50260. else if (from instanceof BABYLON.Size) {
  50261. dataType = Animation.ANIMATIONTYPE_SIZE;
  50262. }
  50263. if (dataType == undefined) {
  50264. return null;
  50265. }
  50266. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50267. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50268. animation.setKeys(keys);
  50269. if (easingFunction !== undefined) {
  50270. animation.setEasingFunction(easingFunction);
  50271. }
  50272. return animation;
  50273. };
  50274. /**
  50275. * Sets up an animation
  50276. * @param property The property to animate
  50277. * @param animationType The animation type to apply
  50278. * @param framePerSecond The frames per second of the animation
  50279. * @param easingFunction The easing function used in the animation
  50280. * @returns The created animation
  50281. */
  50282. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50283. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50284. animation.setEasingFunction(easingFunction);
  50285. return animation;
  50286. };
  50287. /**
  50288. * Create and start an animation on a node
  50289. * @param name defines the name of the global animation that will be run on all nodes
  50290. * @param node defines the root node where the animation will take place
  50291. * @param targetProperty defines property to animate
  50292. * @param framePerSecond defines the number of frame per second yo use
  50293. * @param totalFrame defines the number of frames in total
  50294. * @param from defines the initial value
  50295. * @param to defines the final value
  50296. * @param loopMode defines which loop mode you want to use (off by default)
  50297. * @param easingFunction defines the easing function to use (linear by default)
  50298. * @param onAnimationEnd defines the callback to call when animation end
  50299. * @returns the animatable created for this animation
  50300. */
  50301. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50302. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50303. if (!animation) {
  50304. return null;
  50305. }
  50306. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50307. };
  50308. /**
  50309. * Create and start an animation on a node and its descendants
  50310. * @param name defines the name of the global animation that will be run on all nodes
  50311. * @param node defines the root node where the animation will take place
  50312. * @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
  50313. * @param targetProperty defines property to animate
  50314. * @param framePerSecond defines the number of frame per second to use
  50315. * @param totalFrame defines the number of frames in total
  50316. * @param from defines the initial value
  50317. * @param to defines the final value
  50318. * @param loopMode defines which loop mode you want to use (off by default)
  50319. * @param easingFunction defines the easing function to use (linear by default)
  50320. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50321. * @returns the list of animatables created for all nodes
  50322. * @example https://www.babylonjs-playground.com/#MH0VLI
  50323. */
  50324. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50325. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50326. if (!animation) {
  50327. return null;
  50328. }
  50329. var scene = node.getScene();
  50330. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50331. };
  50332. /**
  50333. * Creates a new animation, merges it with the existing animations and starts it
  50334. * @param name Name of the animation
  50335. * @param node Node which contains the scene that begins the animations
  50336. * @param targetProperty Specifies which property to animate
  50337. * @param framePerSecond The frames per second of the animation
  50338. * @param totalFrame The total number of frames
  50339. * @param from The frame at the beginning of the animation
  50340. * @param to The frame at the end of the animation
  50341. * @param loopMode Specifies the loop mode of the animation
  50342. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50343. * @param onAnimationEnd Callback to run once the animation is complete
  50344. * @returns Nullable animation
  50345. */
  50346. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50347. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50348. if (!animation) {
  50349. return null;
  50350. }
  50351. node.animations.push(animation);
  50352. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50353. };
  50354. /**
  50355. * Transition property of the Camera to the target Value
  50356. * @param property The property to transition
  50357. * @param targetValue The target Value of the property
  50358. * @param host The object where the property to animate belongs
  50359. * @param scene Scene used to run the animation
  50360. * @param frameRate Framerate (in frame/s) to use
  50361. * @param transition The transition type we want to use
  50362. * @param duration The duration of the animation, in milliseconds
  50363. * @param onAnimationEnd Callback trigger at the end of the animation
  50364. * @returns Nullable animation
  50365. */
  50366. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50367. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50368. if (duration <= 0) {
  50369. host[property] = targetValue;
  50370. if (onAnimationEnd) {
  50371. onAnimationEnd();
  50372. }
  50373. return null;
  50374. }
  50375. var endFrame = frameRate * (duration / 1000);
  50376. transition.setKeys([{
  50377. frame: 0,
  50378. value: host[property].clone ? host[property].clone() : host[property]
  50379. },
  50380. {
  50381. frame: endFrame,
  50382. value: targetValue
  50383. }]);
  50384. if (!host.animations) {
  50385. host.animations = [];
  50386. }
  50387. host.animations.push(transition);
  50388. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50389. animation.onAnimationEnd = onAnimationEnd;
  50390. return animation;
  50391. };
  50392. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50393. /**
  50394. * Return the array of runtime animations currently using this animation
  50395. */
  50396. get: function () {
  50397. return this._runtimeAnimations;
  50398. },
  50399. enumerable: true,
  50400. configurable: true
  50401. });
  50402. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50403. /**
  50404. * Specifies if any of the runtime animations are currently running
  50405. */
  50406. get: function () {
  50407. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50408. var runtimeAnimation = _a[_i];
  50409. if (!runtimeAnimation.isStopped) {
  50410. return true;
  50411. }
  50412. }
  50413. return false;
  50414. },
  50415. enumerable: true,
  50416. configurable: true
  50417. });
  50418. // Methods
  50419. /**
  50420. * Converts the animation to a string
  50421. * @param fullDetails support for multiple levels of logging within scene loading
  50422. * @returns String form of the animation
  50423. */
  50424. Animation.prototype.toString = function (fullDetails) {
  50425. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50426. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50427. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50428. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50429. if (fullDetails) {
  50430. ret += ", Ranges: {";
  50431. var first = true;
  50432. for (var name in this._ranges) {
  50433. if (first) {
  50434. ret += ", ";
  50435. first = false;
  50436. }
  50437. ret += name;
  50438. }
  50439. ret += "}";
  50440. }
  50441. return ret;
  50442. };
  50443. /**
  50444. * Add an event to this animation
  50445. * @param event Event to add
  50446. */
  50447. Animation.prototype.addEvent = function (event) {
  50448. this._events.push(event);
  50449. };
  50450. /**
  50451. * Remove all events found at the given frame
  50452. * @param frame The frame to remove events from
  50453. */
  50454. Animation.prototype.removeEvents = function (frame) {
  50455. for (var index = 0; index < this._events.length; index++) {
  50456. if (this._events[index].frame === frame) {
  50457. this._events.splice(index, 1);
  50458. index--;
  50459. }
  50460. }
  50461. };
  50462. /**
  50463. * Retrieves all the events from the animation
  50464. * @returns Events from the animation
  50465. */
  50466. Animation.prototype.getEvents = function () {
  50467. return this._events;
  50468. };
  50469. /**
  50470. * Creates an animation range
  50471. * @param name Name of the animation range
  50472. * @param from Starting frame of the animation range
  50473. * @param to Ending frame of the animation
  50474. */
  50475. Animation.prototype.createRange = function (name, from, to) {
  50476. // check name not already in use; could happen for bones after serialized
  50477. if (!this._ranges[name]) {
  50478. this._ranges[name] = new AnimationRange(name, from, to);
  50479. }
  50480. };
  50481. /**
  50482. * Deletes an animation range by name
  50483. * @param name Name of the animation range to delete
  50484. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50485. */
  50486. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50487. if (deleteFrames === void 0) { deleteFrames = true; }
  50488. var range = this._ranges[name];
  50489. if (!range) {
  50490. return;
  50491. }
  50492. if (deleteFrames) {
  50493. var from = range.from;
  50494. var to = range.to;
  50495. // this loop MUST go high to low for multiple splices to work
  50496. for (var key = this._keys.length - 1; key >= 0; key--) {
  50497. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50498. this._keys.splice(key, 1);
  50499. }
  50500. }
  50501. }
  50502. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50503. };
  50504. /**
  50505. * Gets the animation range by name, or null if not defined
  50506. * @param name Name of the animation range
  50507. * @returns Nullable animation range
  50508. */
  50509. Animation.prototype.getRange = function (name) {
  50510. return this._ranges[name];
  50511. };
  50512. /**
  50513. * Gets the key frames from the animation
  50514. * @returns The key frames of the animation
  50515. */
  50516. Animation.prototype.getKeys = function () {
  50517. return this._keys;
  50518. };
  50519. /**
  50520. * Gets the highest frame rate of the animation
  50521. * @returns Highest frame rate of the animation
  50522. */
  50523. Animation.prototype.getHighestFrame = function () {
  50524. var ret = 0;
  50525. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50526. if (ret < this._keys[key].frame) {
  50527. ret = this._keys[key].frame;
  50528. }
  50529. }
  50530. return ret;
  50531. };
  50532. /**
  50533. * Gets the easing function of the animation
  50534. * @returns Easing function of the animation
  50535. */
  50536. Animation.prototype.getEasingFunction = function () {
  50537. return this._easingFunction;
  50538. };
  50539. /**
  50540. * Sets the easing function of the animation
  50541. * @param easingFunction A custom mathematical formula for animation
  50542. */
  50543. Animation.prototype.setEasingFunction = function (easingFunction) {
  50544. this._easingFunction = easingFunction;
  50545. };
  50546. /**
  50547. * Interpolates a scalar linearly
  50548. * @param startValue Start value of the animation curve
  50549. * @param endValue End value of the animation curve
  50550. * @param gradient Scalar amount to interpolate
  50551. * @returns Interpolated scalar value
  50552. */
  50553. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50554. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50555. };
  50556. /**
  50557. * Interpolates a scalar cubically
  50558. * @param startValue Start value of the animation curve
  50559. * @param outTangent End tangent of the animation
  50560. * @param endValue End value of the animation curve
  50561. * @param inTangent Start tangent of the animation curve
  50562. * @param gradient Scalar amount to interpolate
  50563. * @returns Interpolated scalar value
  50564. */
  50565. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50566. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50567. };
  50568. /**
  50569. * Interpolates a quaternion using a spherical linear interpolation
  50570. * @param startValue Start value of the animation curve
  50571. * @param endValue End value of the animation curve
  50572. * @param gradient Scalar amount to interpolate
  50573. * @returns Interpolated quaternion value
  50574. */
  50575. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50576. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50577. };
  50578. /**
  50579. * Interpolates a quaternion cubically
  50580. * @param startValue Start value of the animation curve
  50581. * @param outTangent End tangent of the animation curve
  50582. * @param endValue End value of the animation curve
  50583. * @param inTangent Start tangent of the animation curve
  50584. * @param gradient Scalar amount to interpolate
  50585. * @returns Interpolated quaternion value
  50586. */
  50587. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50588. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50589. };
  50590. /**
  50591. * Interpolates a Vector3 linearl
  50592. * @param startValue Start value of the animation curve
  50593. * @param endValue End value of the animation curve
  50594. * @param gradient Scalar amount to interpolate
  50595. * @returns Interpolated scalar value
  50596. */
  50597. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50598. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50599. };
  50600. /**
  50601. * Interpolates a Vector3 cubically
  50602. * @param startValue Start value of the animation curve
  50603. * @param outTangent End tangent of the animation
  50604. * @param endValue End value of the animation curve
  50605. * @param inTangent Start tangent of the animation curve
  50606. * @param gradient Scalar amount to interpolate
  50607. * @returns InterpolatedVector3 value
  50608. */
  50609. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50610. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50611. };
  50612. /**
  50613. * Interpolates a Vector2 linearly
  50614. * @param startValue Start value of the animation curve
  50615. * @param endValue End value of the animation curve
  50616. * @param gradient Scalar amount to interpolate
  50617. * @returns Interpolated Vector2 value
  50618. */
  50619. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50620. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50621. };
  50622. /**
  50623. * Interpolates a Vector2 cubically
  50624. * @param startValue Start value of the animation curve
  50625. * @param outTangent End tangent of the animation
  50626. * @param endValue End value of the animation curve
  50627. * @param inTangent Start tangent of the animation curve
  50628. * @param gradient Scalar amount to interpolate
  50629. * @returns Interpolated Vector2 value
  50630. */
  50631. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50632. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50633. };
  50634. /**
  50635. * Interpolates a size linearly
  50636. * @param startValue Start value of the animation curve
  50637. * @param endValue End value of the animation curve
  50638. * @param gradient Scalar amount to interpolate
  50639. * @returns Interpolated Size value
  50640. */
  50641. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50642. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50643. };
  50644. /**
  50645. * Interpolates a Color3 linearly
  50646. * @param startValue Start value of the animation curve
  50647. * @param endValue End value of the animation curve
  50648. * @param gradient Scalar amount to interpolate
  50649. * @returns Interpolated Color3 value
  50650. */
  50651. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50652. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50653. };
  50654. /**
  50655. * @hidden Internal use only
  50656. */
  50657. Animation.prototype._getKeyValue = function (value) {
  50658. if (typeof value === "function") {
  50659. return value();
  50660. }
  50661. return value;
  50662. };
  50663. /**
  50664. * @hidden Internal use only
  50665. */
  50666. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50667. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50668. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50669. }
  50670. var keys = this.getKeys();
  50671. // Try to get a hash to find the right key
  50672. 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));
  50673. if (keys[startKeyIndex].frame >= currentFrame) {
  50674. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50675. startKeyIndex--;
  50676. }
  50677. }
  50678. for (var key = startKeyIndex; key < keys.length; key++) {
  50679. var endKey = keys[key + 1];
  50680. if (endKey.frame >= currentFrame) {
  50681. var startKey = keys[key];
  50682. var startValue = this._getKeyValue(startKey.value);
  50683. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50684. return startValue;
  50685. }
  50686. var endValue = this._getKeyValue(endKey.value);
  50687. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50688. var frameDelta = endKey.frame - startKey.frame;
  50689. // gradient : percent of currentFrame between the frame inf and the frame sup
  50690. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50691. // check for easingFunction and correction of gradient
  50692. var easingFunction = this.getEasingFunction();
  50693. if (easingFunction != null) {
  50694. gradient = easingFunction.ease(gradient);
  50695. }
  50696. switch (this.dataType) {
  50697. // Float
  50698. case Animation.ANIMATIONTYPE_FLOAT:
  50699. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50700. switch (loopMode) {
  50701. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50702. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50703. return floatValue;
  50704. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50705. return offsetValue * repeatCount + floatValue;
  50706. }
  50707. break;
  50708. // Quaternion
  50709. case Animation.ANIMATIONTYPE_QUATERNION:
  50710. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50711. switch (loopMode) {
  50712. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50713. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50714. return quatValue;
  50715. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50716. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50717. }
  50718. return quatValue;
  50719. // Vector3
  50720. case Animation.ANIMATIONTYPE_VECTOR3:
  50721. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50722. switch (loopMode) {
  50723. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50724. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50725. return vec3Value;
  50726. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50727. return vec3Value.add(offsetValue.scale(repeatCount));
  50728. }
  50729. // Vector2
  50730. case Animation.ANIMATIONTYPE_VECTOR2:
  50731. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50732. switch (loopMode) {
  50733. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50734. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50735. return vec2Value;
  50736. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50737. return vec2Value.add(offsetValue.scale(repeatCount));
  50738. }
  50739. // Size
  50740. case Animation.ANIMATIONTYPE_SIZE:
  50741. switch (loopMode) {
  50742. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50743. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50744. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50745. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50746. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50747. }
  50748. // Color3
  50749. case Animation.ANIMATIONTYPE_COLOR3:
  50750. switch (loopMode) {
  50751. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50752. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50753. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50754. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50755. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50756. }
  50757. // Matrix
  50758. case Animation.ANIMATIONTYPE_MATRIX:
  50759. switch (loopMode) {
  50760. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50761. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50762. if (Animation.AllowMatricesInterpolation) {
  50763. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50764. }
  50765. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50766. return startValue;
  50767. }
  50768. default:
  50769. break;
  50770. }
  50771. break;
  50772. }
  50773. }
  50774. return this._getKeyValue(keys[keys.length - 1].value);
  50775. };
  50776. /**
  50777. * Defines the function to use to interpolate matrices
  50778. * @param startValue defines the start matrix
  50779. * @param endValue defines the end matrix
  50780. * @param gradient defines the gradient between both matrices
  50781. * @param result defines an optional target matrix where to store the interpolation
  50782. * @returns the interpolated matrix
  50783. */
  50784. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50785. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50786. if (result) {
  50787. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50788. return result;
  50789. }
  50790. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50791. }
  50792. if (result) {
  50793. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50794. return result;
  50795. }
  50796. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50797. };
  50798. /**
  50799. * Makes a copy of the animation
  50800. * @returns Cloned animation
  50801. */
  50802. Animation.prototype.clone = function () {
  50803. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50804. clone.enableBlending = this.enableBlending;
  50805. clone.blendingSpeed = this.blendingSpeed;
  50806. if (this._keys) {
  50807. clone.setKeys(this._keys);
  50808. }
  50809. if (this._ranges) {
  50810. clone._ranges = {};
  50811. for (var name in this._ranges) {
  50812. var range = this._ranges[name];
  50813. if (!range) {
  50814. continue;
  50815. }
  50816. clone._ranges[name] = range.clone();
  50817. }
  50818. }
  50819. return clone;
  50820. };
  50821. /**
  50822. * Sets the key frames of the animation
  50823. * @param values The animation key frames to set
  50824. */
  50825. Animation.prototype.setKeys = function (values) {
  50826. this._keys = values.slice(0);
  50827. };
  50828. /**
  50829. * Serializes the animation to an object
  50830. * @returns Serialized object
  50831. */
  50832. Animation.prototype.serialize = function () {
  50833. var serializationObject = {};
  50834. serializationObject.name = this.name;
  50835. serializationObject.property = this.targetProperty;
  50836. serializationObject.framePerSecond = this.framePerSecond;
  50837. serializationObject.dataType = this.dataType;
  50838. serializationObject.loopBehavior = this.loopMode;
  50839. serializationObject.enableBlending = this.enableBlending;
  50840. serializationObject.blendingSpeed = this.blendingSpeed;
  50841. var dataType = this.dataType;
  50842. serializationObject.keys = [];
  50843. var keys = this.getKeys();
  50844. for (var index = 0; index < keys.length; index++) {
  50845. var animationKey = keys[index];
  50846. var key = {};
  50847. key.frame = animationKey.frame;
  50848. switch (dataType) {
  50849. case Animation.ANIMATIONTYPE_FLOAT:
  50850. key.values = [animationKey.value];
  50851. break;
  50852. case Animation.ANIMATIONTYPE_QUATERNION:
  50853. case Animation.ANIMATIONTYPE_MATRIX:
  50854. case Animation.ANIMATIONTYPE_VECTOR3:
  50855. case Animation.ANIMATIONTYPE_COLOR3:
  50856. key.values = animationKey.value.asArray();
  50857. break;
  50858. }
  50859. serializationObject.keys.push(key);
  50860. }
  50861. serializationObject.ranges = [];
  50862. for (var name in this._ranges) {
  50863. var source = this._ranges[name];
  50864. if (!source) {
  50865. continue;
  50866. }
  50867. var range = {};
  50868. range.name = name;
  50869. range.from = source.from;
  50870. range.to = source.to;
  50871. serializationObject.ranges.push(range);
  50872. }
  50873. return serializationObject;
  50874. };
  50875. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50876. /**
  50877. * Get the float animation type
  50878. */
  50879. get: function () {
  50880. return Animation._ANIMATIONTYPE_FLOAT;
  50881. },
  50882. enumerable: true,
  50883. configurable: true
  50884. });
  50885. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50886. /**
  50887. * Get the Vector3 animation type
  50888. */
  50889. get: function () {
  50890. return Animation._ANIMATIONTYPE_VECTOR3;
  50891. },
  50892. enumerable: true,
  50893. configurable: true
  50894. });
  50895. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50896. /**
  50897. * Get the Vectpr2 animation type
  50898. */
  50899. get: function () {
  50900. return Animation._ANIMATIONTYPE_VECTOR2;
  50901. },
  50902. enumerable: true,
  50903. configurable: true
  50904. });
  50905. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50906. /**
  50907. * Get the Size animation type
  50908. */
  50909. get: function () {
  50910. return Animation._ANIMATIONTYPE_SIZE;
  50911. },
  50912. enumerable: true,
  50913. configurable: true
  50914. });
  50915. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50916. /**
  50917. * Get the Quaternion animation type
  50918. */
  50919. get: function () {
  50920. return Animation._ANIMATIONTYPE_QUATERNION;
  50921. },
  50922. enumerable: true,
  50923. configurable: true
  50924. });
  50925. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50926. /**
  50927. * Get the Matrix animation type
  50928. */
  50929. get: function () {
  50930. return Animation._ANIMATIONTYPE_MATRIX;
  50931. },
  50932. enumerable: true,
  50933. configurable: true
  50934. });
  50935. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50936. /**
  50937. * Get the Color3 animation type
  50938. */
  50939. get: function () {
  50940. return Animation._ANIMATIONTYPE_COLOR3;
  50941. },
  50942. enumerable: true,
  50943. configurable: true
  50944. });
  50945. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50946. /**
  50947. * Get the Relative Loop Mode
  50948. */
  50949. get: function () {
  50950. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50951. },
  50952. enumerable: true,
  50953. configurable: true
  50954. });
  50955. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50956. /**
  50957. * Get the Cycle Loop Mode
  50958. */
  50959. get: function () {
  50960. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50961. },
  50962. enumerable: true,
  50963. configurable: true
  50964. });
  50965. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50966. /**
  50967. * Get the Constant Loop Mode
  50968. */
  50969. get: function () {
  50970. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50971. },
  50972. enumerable: true,
  50973. configurable: true
  50974. });
  50975. /**
  50976. * Parses an animation object and creates an animation
  50977. * @param parsedAnimation Parsed animation object
  50978. * @returns Animation object
  50979. */
  50980. Animation.Parse = function (parsedAnimation) {
  50981. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50982. var dataType = parsedAnimation.dataType;
  50983. var keys = [];
  50984. var data;
  50985. var index;
  50986. if (parsedAnimation.enableBlending) {
  50987. animation.enableBlending = parsedAnimation.enableBlending;
  50988. }
  50989. if (parsedAnimation.blendingSpeed) {
  50990. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50991. }
  50992. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50993. var key = parsedAnimation.keys[index];
  50994. var inTangent;
  50995. var outTangent;
  50996. switch (dataType) {
  50997. case Animation.ANIMATIONTYPE_FLOAT:
  50998. data = key.values[0];
  50999. if (key.values.length >= 1) {
  51000. inTangent = key.values[1];
  51001. }
  51002. if (key.values.length >= 2) {
  51003. outTangent = key.values[2];
  51004. }
  51005. break;
  51006. case Animation.ANIMATIONTYPE_QUATERNION:
  51007. data = BABYLON.Quaternion.FromArray(key.values);
  51008. if (key.values.length >= 8) {
  51009. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51010. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51011. inTangent = _inTangent;
  51012. }
  51013. }
  51014. if (key.values.length >= 12) {
  51015. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51016. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51017. outTangent = _outTangent;
  51018. }
  51019. }
  51020. break;
  51021. case Animation.ANIMATIONTYPE_MATRIX:
  51022. data = BABYLON.Matrix.FromArray(key.values);
  51023. break;
  51024. case Animation.ANIMATIONTYPE_COLOR3:
  51025. data = BABYLON.Color3.FromArray(key.values);
  51026. break;
  51027. case Animation.ANIMATIONTYPE_VECTOR3:
  51028. default:
  51029. data = BABYLON.Vector3.FromArray(key.values);
  51030. break;
  51031. }
  51032. var keyData = {};
  51033. keyData.frame = key.frame;
  51034. keyData.value = data;
  51035. if (inTangent != undefined) {
  51036. keyData.inTangent = inTangent;
  51037. }
  51038. if (outTangent != undefined) {
  51039. keyData.outTangent = outTangent;
  51040. }
  51041. keys.push(keyData);
  51042. }
  51043. animation.setKeys(keys);
  51044. if (parsedAnimation.ranges) {
  51045. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51046. data = parsedAnimation.ranges[index];
  51047. animation.createRange(data.name, data.from, data.to);
  51048. }
  51049. }
  51050. return animation;
  51051. };
  51052. /**
  51053. * Appends the serialized animations from the source animations
  51054. * @param source Source containing the animations
  51055. * @param destination Target to store the animations
  51056. */
  51057. Animation.AppendSerializedAnimations = function (source, destination) {
  51058. if (source.animations) {
  51059. destination.animations = [];
  51060. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51061. var animation = source.animations[animationIndex];
  51062. destination.animations.push(animation.serialize());
  51063. }
  51064. }
  51065. };
  51066. /**
  51067. * Use matrix interpolation instead of using direct key value when animating matrices
  51068. */
  51069. Animation.AllowMatricesInterpolation = false;
  51070. /**
  51071. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51072. */
  51073. Animation.AllowMatrixDecomposeForInterpolation = true;
  51074. // Statics
  51075. /**
  51076. * Float animation type
  51077. */
  51078. Animation._ANIMATIONTYPE_FLOAT = 0;
  51079. /**
  51080. * Vector3 animation type
  51081. */
  51082. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51083. /**
  51084. * Quaternion animation type
  51085. */
  51086. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51087. /**
  51088. * Matrix animation type
  51089. */
  51090. Animation._ANIMATIONTYPE_MATRIX = 3;
  51091. /**
  51092. * Color3 animation type
  51093. */
  51094. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51095. /**
  51096. * Vector2 animation type
  51097. */
  51098. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51099. /**
  51100. * Size animation type
  51101. */
  51102. Animation._ANIMATIONTYPE_SIZE = 6;
  51103. /**
  51104. * Relative Loop Mode
  51105. */
  51106. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51107. /**
  51108. * Cycle Loop Mode
  51109. */
  51110. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51111. /**
  51112. * Constant Loop Mode
  51113. */
  51114. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51115. return Animation;
  51116. }());
  51117. BABYLON.Animation = Animation;
  51118. })(BABYLON || (BABYLON = {}));
  51119. //# sourceMappingURL=babylon.animation.js.map
  51120. var BABYLON;
  51121. (function (BABYLON) {
  51122. /**
  51123. * This class defines the direct association between an animation and a target
  51124. */
  51125. var TargetedAnimation = /** @class */ (function () {
  51126. function TargetedAnimation() {
  51127. }
  51128. return TargetedAnimation;
  51129. }());
  51130. BABYLON.TargetedAnimation = TargetedAnimation;
  51131. /**
  51132. * Use this class to create coordinated animations on multiple targets
  51133. */
  51134. var AnimationGroup = /** @class */ (function () {
  51135. function AnimationGroup(name, scene) {
  51136. if (scene === void 0) { scene = null; }
  51137. this.name = name;
  51138. this._targetedAnimations = new Array();
  51139. this._animatables = new Array();
  51140. this._from = Number.MAX_VALUE;
  51141. this._to = -Number.MAX_VALUE;
  51142. this._speedRatio = 1;
  51143. this.onAnimationEndObservable = new BABYLON.Observable();
  51144. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51145. this._scene.animationGroups.push(this);
  51146. }
  51147. Object.defineProperty(AnimationGroup.prototype, "from", {
  51148. /**
  51149. * Gets the first frame
  51150. */
  51151. get: function () {
  51152. return this._from;
  51153. },
  51154. enumerable: true,
  51155. configurable: true
  51156. });
  51157. Object.defineProperty(AnimationGroup.prototype, "to", {
  51158. /**
  51159. * Gets the last frame
  51160. */
  51161. get: function () {
  51162. return this._to;
  51163. },
  51164. enumerable: true,
  51165. configurable: true
  51166. });
  51167. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51168. /**
  51169. * Define if the animations are started
  51170. */
  51171. get: function () {
  51172. return this._isStarted;
  51173. },
  51174. enumerable: true,
  51175. configurable: true
  51176. });
  51177. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51178. /**
  51179. * Gets or sets the speed ratio to use for all animations
  51180. */
  51181. get: function () {
  51182. return this._speedRatio;
  51183. },
  51184. /**
  51185. * Gets or sets the speed ratio to use for all animations
  51186. */
  51187. set: function (value) {
  51188. if (this._speedRatio === value) {
  51189. return;
  51190. }
  51191. this._speedRatio = value;
  51192. for (var index = 0; index < this._animatables.length; index++) {
  51193. var animatable = this._animatables[index];
  51194. animatable.speedRatio = this._speedRatio;
  51195. }
  51196. },
  51197. enumerable: true,
  51198. configurable: true
  51199. });
  51200. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51201. /**
  51202. * Gets the targeted animations for this animation group
  51203. */
  51204. get: function () {
  51205. return this._targetedAnimations;
  51206. },
  51207. enumerable: true,
  51208. configurable: true
  51209. });
  51210. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51211. /**
  51212. * returning the list of animatables controlled by this animation group.
  51213. */
  51214. get: function () {
  51215. return this._animatables;
  51216. },
  51217. enumerable: true,
  51218. configurable: true
  51219. });
  51220. /**
  51221. * Add an animation (with its target) in the group
  51222. * @param animation defines the animation we want to add
  51223. * @param target defines the target of the animation
  51224. * @returns the {BABYLON.TargetedAnimation} object
  51225. */
  51226. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51227. var targetedAnimation = {
  51228. animation: animation,
  51229. target: target
  51230. };
  51231. var keys = animation.getKeys();
  51232. if (this._from > keys[0].frame) {
  51233. this._from = keys[0].frame;
  51234. }
  51235. if (this._to < keys[keys.length - 1].frame) {
  51236. this._to = keys[keys.length - 1].frame;
  51237. }
  51238. this._targetedAnimations.push(targetedAnimation);
  51239. return targetedAnimation;
  51240. };
  51241. /**
  51242. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51243. * It can add constant keys at begin or end
  51244. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  51245. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  51246. */
  51247. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51248. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  51249. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  51250. beginFrame = Math.max(beginFrame, this._from);
  51251. endFrame = Math.min(endFrame, this._to);
  51252. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51253. var targetedAnimation = this._targetedAnimations[index];
  51254. var keys = targetedAnimation.animation.getKeys();
  51255. var startKey = keys[0];
  51256. var endKey = keys[keys.length - 1];
  51257. if (startKey.frame > beginFrame) {
  51258. var newKey = {
  51259. frame: beginFrame,
  51260. value: startKey.value,
  51261. inTangent: startKey.inTangent,
  51262. outTangent: startKey.outTangent,
  51263. interpolation: startKey.interpolation
  51264. };
  51265. keys.splice(0, 0, newKey);
  51266. }
  51267. if (endKey.frame < endFrame) {
  51268. var newKey = {
  51269. frame: endFrame,
  51270. value: endKey.value,
  51271. inTangent: endKey.outTangent,
  51272. outTangent: endKey.outTangent,
  51273. interpolation: endKey.interpolation
  51274. };
  51275. keys.push(newKey);
  51276. }
  51277. }
  51278. return this;
  51279. };
  51280. /**
  51281. * Start all animations on given targets
  51282. * @param loop defines if animations must loop
  51283. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51284. * @param from defines the from key (optional)
  51285. * @param to defines the to key (optional)
  51286. * @returns the current animation group
  51287. */
  51288. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51289. var _this = this;
  51290. if (loop === void 0) { loop = false; }
  51291. if (speedRatio === void 0) { speedRatio = 1; }
  51292. if (this._isStarted || this._targetedAnimations.length === 0) {
  51293. return this;
  51294. }
  51295. var _loop_1 = function (targetedAnimation) {
  51296. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  51297. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51298. }));
  51299. };
  51300. var this_1 = this;
  51301. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51302. var targetedAnimation = _a[_i];
  51303. _loop_1(targetedAnimation);
  51304. }
  51305. this._speedRatio = speedRatio;
  51306. this._isStarted = true;
  51307. return this;
  51308. };
  51309. /**
  51310. * Pause all animations
  51311. */
  51312. AnimationGroup.prototype.pause = function () {
  51313. if (!this._isStarted) {
  51314. return this;
  51315. }
  51316. for (var index = 0; index < this._animatables.length; index++) {
  51317. var animatable = this._animatables[index];
  51318. animatable.pause();
  51319. }
  51320. return this;
  51321. };
  51322. /**
  51323. * Play all animations to initial state
  51324. * This function will start() the animations if they were not started or will restart() them if they were paused
  51325. * @param loop defines if animations must loop
  51326. */
  51327. AnimationGroup.prototype.play = function (loop) {
  51328. if (this.isStarted) {
  51329. if (loop !== undefined) {
  51330. for (var index = 0; index < this._animatables.length; index++) {
  51331. var animatable = this._animatables[index];
  51332. animatable.loopAnimation = loop;
  51333. }
  51334. }
  51335. this.restart();
  51336. }
  51337. else {
  51338. this.start(loop, this._speedRatio);
  51339. }
  51340. return this;
  51341. };
  51342. /**
  51343. * Reset all animations to initial state
  51344. */
  51345. AnimationGroup.prototype.reset = function () {
  51346. if (!this._isStarted) {
  51347. return this;
  51348. }
  51349. for (var index = 0; index < this._animatables.length; index++) {
  51350. var animatable = this._animatables[index];
  51351. animatable.reset();
  51352. }
  51353. return this;
  51354. };
  51355. /**
  51356. * Restart animations from key 0
  51357. */
  51358. AnimationGroup.prototype.restart = function () {
  51359. if (!this._isStarted) {
  51360. return this;
  51361. }
  51362. for (var index = 0; index < this._animatables.length; index++) {
  51363. var animatable = this._animatables[index];
  51364. animatable.restart();
  51365. }
  51366. return this;
  51367. };
  51368. /**
  51369. * Stop all animations
  51370. */
  51371. AnimationGroup.prototype.stop = function () {
  51372. if (!this._isStarted) {
  51373. return this;
  51374. }
  51375. for (var index = 0; index < this._animatables.length; index++) {
  51376. var animatable = this._animatables[index];
  51377. animatable.stop();
  51378. }
  51379. this._isStarted = false;
  51380. return this;
  51381. };
  51382. /**
  51383. * Set animation weight for all animatables
  51384. * @param weight defines the weight to use
  51385. * @return the animationGroup
  51386. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51387. */
  51388. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51389. for (var index = 0; index < this._animatables.length; index++) {
  51390. var animatable = this._animatables[index];
  51391. animatable.weight = weight;
  51392. }
  51393. return this;
  51394. };
  51395. /**
  51396. * Synchronize and normalize all animatables with a source animatable
  51397. * @param root defines the root animatable to synchronize with
  51398. * @return the animationGroup
  51399. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51400. */
  51401. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51402. for (var index = 0; index < this._animatables.length; index++) {
  51403. var animatable = this._animatables[index];
  51404. animatable.syncWith(root);
  51405. }
  51406. return this;
  51407. };
  51408. /**
  51409. * Goes to a specific frame in this animation group
  51410. * @param frame the frame number to go to
  51411. * @return the animationGroup
  51412. */
  51413. AnimationGroup.prototype.goToFrame = function (frame) {
  51414. if (!this._isStarted) {
  51415. return this;
  51416. }
  51417. for (var index = 0; index < this._animatables.length; index++) {
  51418. var animatable = this._animatables[index];
  51419. animatable.goToFrame(frame);
  51420. }
  51421. return this;
  51422. };
  51423. /**
  51424. * Dispose all associated resources
  51425. */
  51426. AnimationGroup.prototype.dispose = function () {
  51427. this._targetedAnimations = [];
  51428. this._animatables = [];
  51429. var index = this._scene.animationGroups.indexOf(this);
  51430. if (index > -1) {
  51431. this._scene.animationGroups.splice(index, 1);
  51432. }
  51433. };
  51434. return AnimationGroup;
  51435. }());
  51436. BABYLON.AnimationGroup = AnimationGroup;
  51437. })(BABYLON || (BABYLON = {}));
  51438. //# sourceMappingURL=babylon.animationGroup.js.map
  51439. var BABYLON;
  51440. (function (BABYLON) {
  51441. /**
  51442. * Defines a runtime animation
  51443. */
  51444. var RuntimeAnimation = /** @class */ (function () {
  51445. /**
  51446. * Create a new RuntimeAnimation object
  51447. * @param target defines the target of the animation
  51448. * @param animation defines the source animation object
  51449. * @param scene defines the hosting scene
  51450. * @param host defines the initiating Animatable
  51451. */
  51452. function RuntimeAnimation(target, animation, scene, host) {
  51453. /**
  51454. * The current frame of the runtime animation
  51455. */
  51456. this._currentFrame = 0;
  51457. /**
  51458. * The offsets cache of the runtime animation
  51459. */
  51460. this._offsetsCache = {};
  51461. /**
  51462. * The high limits cache of the runtime animation
  51463. */
  51464. this._highLimitsCache = {};
  51465. /**
  51466. * Specifies if the runtime animation has been stopped
  51467. */
  51468. this._stopped = false;
  51469. /**
  51470. * The blending factor of the runtime animation
  51471. */
  51472. this._blendingFactor = 0;
  51473. /**
  51474. * The target path of the runtime animation
  51475. */
  51476. this._targetPath = "";
  51477. /**
  51478. * The weight of the runtime animation
  51479. */
  51480. this._weight = 1.0;
  51481. /**
  51482. * The ratio offset of the runtime animation
  51483. */
  51484. this._ratioOffset = 0;
  51485. /**
  51486. * The previous delay of the runtime animation
  51487. */
  51488. this._previousDelay = 0;
  51489. /**
  51490. * The previous ratio of the runtime animation
  51491. */
  51492. this._previousRatio = 0;
  51493. this._animation = animation;
  51494. this._target = target;
  51495. this._scene = scene;
  51496. this._host = host;
  51497. animation._runtimeAnimations.push(this);
  51498. }
  51499. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51500. /**
  51501. * Gets the current frame of the runtime animation
  51502. */
  51503. get: function () {
  51504. return this._currentFrame;
  51505. },
  51506. enumerable: true,
  51507. configurable: true
  51508. });
  51509. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51510. /**
  51511. * Gets the weight of the runtime animation
  51512. */
  51513. get: function () {
  51514. return this._weight;
  51515. },
  51516. enumerable: true,
  51517. configurable: true
  51518. });
  51519. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  51520. /**
  51521. * Gets the original value of the runtime animation
  51522. */
  51523. get: function () {
  51524. return this._originalValue;
  51525. },
  51526. enumerable: true,
  51527. configurable: true
  51528. });
  51529. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51530. /**
  51531. * Gets the current value of the runtime animation
  51532. */
  51533. get: function () {
  51534. return this._currentValue;
  51535. },
  51536. enumerable: true,
  51537. configurable: true
  51538. });
  51539. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51540. /**
  51541. * Gets the target path of the runtime animation
  51542. */
  51543. get: function () {
  51544. return this._targetPath;
  51545. },
  51546. enumerable: true,
  51547. configurable: true
  51548. });
  51549. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51550. /**
  51551. * Gets the actual target of the runtime animation
  51552. */
  51553. get: function () {
  51554. return this._activeTarget;
  51555. },
  51556. enumerable: true,
  51557. configurable: true
  51558. });
  51559. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51560. /**
  51561. * Gets the animation from the runtime animation
  51562. */
  51563. get: function () {
  51564. return this._animation;
  51565. },
  51566. enumerable: true,
  51567. configurable: true
  51568. });
  51569. /**
  51570. * Resets the runtime animation to the beginning
  51571. */
  51572. RuntimeAnimation.prototype.reset = function () {
  51573. this._offsetsCache = {};
  51574. this._highLimitsCache = {};
  51575. this._currentFrame = 0;
  51576. this._blendingFactor = 0;
  51577. this._originalValue = null;
  51578. };
  51579. /**
  51580. * Specifies if the runtime animation is stopped
  51581. * @returns Boolean specifying if the runtime animation is stopped
  51582. */
  51583. RuntimeAnimation.prototype.isStopped = function () {
  51584. return this._stopped;
  51585. };
  51586. /**
  51587. * Disposes of the runtime animation
  51588. */
  51589. RuntimeAnimation.prototype.dispose = function () {
  51590. var index = this._animation.runtimeAnimations.indexOf(this);
  51591. if (index > -1) {
  51592. this._animation.runtimeAnimations.splice(index, 1);
  51593. }
  51594. };
  51595. /**
  51596. * Interpolates the animation from the current frame
  51597. * @param currentFrame The frame to interpolate the animation to
  51598. * @param repeatCount The number of times that the animation should loop
  51599. * @param loopMode The type of looping mode to use
  51600. * @param offsetValue Animation offset value
  51601. * @param highLimitValue The high limit value
  51602. * @returns The interpolated value
  51603. */
  51604. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51605. this._currentFrame = currentFrame;
  51606. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51607. this._workValue = BABYLON.Matrix.Zero();
  51608. }
  51609. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51610. };
  51611. /**
  51612. * Affect the interpolated value to the target
  51613. * @param currentValue defines the value computed by the animation
  51614. * @param weight defines the weight to apply to this value
  51615. */
  51616. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51617. if (weight === void 0) { weight = 1.0; }
  51618. if (this._target instanceof Array) {
  51619. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51620. var target = _a[_i];
  51621. this._setValue(target, currentValue, weight);
  51622. }
  51623. }
  51624. else {
  51625. this._setValue(this._target, currentValue, weight);
  51626. }
  51627. };
  51628. /**
  51629. * Sets the value of the runtime animation
  51630. * @param target The target property of the runtime animation
  51631. * @param currentValue The current value to use for the runtime animation
  51632. * @param weight The weight to use for the runtime animation (Defaults to 1.0)
  51633. */
  51634. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight) {
  51635. if (weight === void 0) { weight = 1.0; }
  51636. // Set value
  51637. var path;
  51638. var destination;
  51639. var targetPropertyPath = this._animation.targetPropertyPath;
  51640. if (targetPropertyPath.length > 1) {
  51641. var property = target[targetPropertyPath[0]];
  51642. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51643. property = property[targetPropertyPath[index]];
  51644. }
  51645. path = targetPropertyPath[targetPropertyPath.length - 1];
  51646. destination = property;
  51647. }
  51648. else {
  51649. path = targetPropertyPath[0];
  51650. destination = target;
  51651. }
  51652. this._targetPath = path;
  51653. this._activeTarget = destination;
  51654. this._weight = weight;
  51655. // Blending
  51656. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51657. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51658. if (enableBlending && this._blendingFactor <= 1.0) {
  51659. if (!this._originalBlendValue) {
  51660. var originalValue = destination[path];
  51661. if (originalValue.clone) {
  51662. this._originalBlendValue = originalValue.clone();
  51663. }
  51664. else {
  51665. this._originalBlendValue = originalValue;
  51666. }
  51667. }
  51668. }
  51669. if (weight !== -1.0) {
  51670. if (!this._originalValue) {
  51671. var originalValue = void 0;
  51672. if (destination.getRestPose && path === "_matrix") { // For bones
  51673. originalValue = destination.getRestPose();
  51674. }
  51675. else {
  51676. originalValue = destination[path];
  51677. }
  51678. if (originalValue.clone) {
  51679. this._originalValue = originalValue.clone();
  51680. }
  51681. else {
  51682. this._originalValue = originalValue;
  51683. }
  51684. }
  51685. }
  51686. if (enableBlending && this._blendingFactor <= 1.0) {
  51687. if (this._originalBlendValue.m) { // Matrix
  51688. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51689. if (this._currentValue) {
  51690. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51691. }
  51692. else {
  51693. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51694. }
  51695. }
  51696. else {
  51697. if (this._currentValue) {
  51698. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51699. }
  51700. else {
  51701. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51702. }
  51703. }
  51704. }
  51705. else {
  51706. var constructor = this._originalBlendValue.constructor;
  51707. if (constructor.Lerp) { // Lerp supported
  51708. this._currentValue = constructor.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51709. }
  51710. else if (constructor.Slerp) { // Slerp supported
  51711. this._currentValue = constructor.Slerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51712. }
  51713. else if (this._originalBlendValue.toFixed) { // Number
  51714. this._currentValue = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  51715. }
  51716. else { // Blending not supported
  51717. this._currentValue = currentValue;
  51718. }
  51719. }
  51720. this._blendingFactor += blendingSpeed;
  51721. }
  51722. else {
  51723. this._currentValue = currentValue;
  51724. }
  51725. if (weight !== -1.0) {
  51726. this._scene._registerTargetForLateAnimationBinding(this);
  51727. }
  51728. else {
  51729. destination[path] = this._currentValue;
  51730. }
  51731. if (target.markAsDirty) {
  51732. target.markAsDirty(this._animation.targetProperty);
  51733. }
  51734. };
  51735. /**
  51736. * Gets the loop pmode of the runtime animation
  51737. * @returns Loop Mode
  51738. */
  51739. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51740. if (this._target && this._target.animationPropertiesOverride) {
  51741. return this._target.animationPropertiesOverride.loopMode;
  51742. }
  51743. return this._animation.loopMode;
  51744. };
  51745. /**
  51746. * Move the current animation to a given frame
  51747. * @param frame defines the frame to move to
  51748. */
  51749. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51750. var keys = this._animation.getKeys();
  51751. if (frame < keys[0].frame) {
  51752. frame = keys[0].frame;
  51753. }
  51754. else if (frame > keys[keys.length - 1].frame) {
  51755. frame = keys[keys.length - 1].frame;
  51756. }
  51757. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51758. this.setValue(currentValue, -1);
  51759. };
  51760. /**
  51761. * @hidden Internal use only
  51762. */
  51763. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51764. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51765. this._ratioOffset = this._previousRatio - newRatio;
  51766. };
  51767. /**
  51768. * Execute the current animation
  51769. * @param delay defines the delay to add to the current frame
  51770. * @param from defines the lower bound of the animation range
  51771. * @param to defines the upper bound of the animation range
  51772. * @param loop defines if the current animation must loop
  51773. * @param speedRatio defines the current speed ratio
  51774. * @param weight defines the weight of the animation (default is -1 so no weight)
  51775. * @returns a boolean indicating if the animation has ended
  51776. */
  51777. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51778. if (weight === void 0) { weight = -1.0; }
  51779. var targetPropertyPath = this._animation.targetPropertyPath;
  51780. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51781. this._stopped = true;
  51782. return false;
  51783. }
  51784. var returnValue = true;
  51785. var keys = this._animation.getKeys();
  51786. // Adding a start key at frame 0 if missing
  51787. if (keys[0].frame !== 0) {
  51788. var newKey = { frame: 0, value: keys[0].value };
  51789. keys.splice(0, 0, newKey);
  51790. }
  51791. // Check limits
  51792. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51793. from = keys[0].frame;
  51794. }
  51795. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51796. to = keys[keys.length - 1].frame;
  51797. }
  51798. //to and from cannot be the same key
  51799. if (from === to) {
  51800. if (from > keys[0].frame) {
  51801. from--;
  51802. }
  51803. else if (to < keys[keys.length - 1].frame) {
  51804. to++;
  51805. }
  51806. }
  51807. // Compute ratio
  51808. var range = to - from;
  51809. var offsetValue;
  51810. // ratio represents the frame delta between from and to
  51811. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51812. var highLimitValue = 0;
  51813. this._previousDelay = delay;
  51814. this._previousRatio = ratio;
  51815. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  51816. returnValue = false;
  51817. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51818. }
  51819. else {
  51820. // Get max value if required
  51821. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51822. var keyOffset = to.toString() + from.toString();
  51823. if (!this._offsetsCache[keyOffset]) {
  51824. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51825. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51826. switch (this._animation.dataType) {
  51827. // Float
  51828. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51829. this._offsetsCache[keyOffset] = toValue - fromValue;
  51830. break;
  51831. // Quaternion
  51832. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51833. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51834. break;
  51835. // Vector3
  51836. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51837. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51838. // Vector2
  51839. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51840. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51841. // Size
  51842. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51843. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51844. // Color3
  51845. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51846. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51847. default:
  51848. break;
  51849. }
  51850. this._highLimitsCache[keyOffset] = toValue;
  51851. }
  51852. highLimitValue = this._highLimitsCache[keyOffset];
  51853. offsetValue = this._offsetsCache[keyOffset];
  51854. }
  51855. }
  51856. if (offsetValue === undefined) {
  51857. switch (this._animation.dataType) {
  51858. // Float
  51859. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51860. offsetValue = 0;
  51861. break;
  51862. // Quaternion
  51863. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51864. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51865. break;
  51866. // Vector3
  51867. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51868. offsetValue = BABYLON.Vector3.Zero();
  51869. break;
  51870. // Vector2
  51871. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51872. offsetValue = BABYLON.Vector2.Zero();
  51873. break;
  51874. // Size
  51875. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51876. offsetValue = BABYLON.Size.Zero();
  51877. break;
  51878. // Color3
  51879. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51880. offsetValue = BABYLON.Color3.Black();
  51881. }
  51882. }
  51883. // Compute value
  51884. var repeatCount = (ratio / range) >> 0;
  51885. var currentFrame = returnValue ? from + ratio % range : to;
  51886. // Need to normalize?
  51887. if (this._host && this._host.syncRoot) {
  51888. var syncRoot = this._host.syncRoot;
  51889. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51890. currentFrame = from + (to - from) * hostNormalizedFrame;
  51891. }
  51892. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51893. // Set value
  51894. this.setValue(currentValue, weight);
  51895. // Check events
  51896. var events = this._animation.getEvents();
  51897. for (var index = 0; index < events.length; index++) {
  51898. // Make sure current frame has passed event frame and that event frame is within the current range
  51899. // Also, handle both forward and reverse animations
  51900. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51901. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51902. var event = events[index];
  51903. if (!event.isDone) {
  51904. // If event should be done only once, remove it.
  51905. if (event.onlyOnce) {
  51906. events.splice(index, 1);
  51907. index--;
  51908. }
  51909. event.isDone = true;
  51910. event.action();
  51911. } // Don't do anything if the event has already be done.
  51912. }
  51913. else if (events[index].isDone && !events[index].onlyOnce) {
  51914. // reset event, the animation is looping
  51915. events[index].isDone = false;
  51916. }
  51917. }
  51918. if (!returnValue) {
  51919. this._stopped = true;
  51920. }
  51921. return returnValue;
  51922. };
  51923. return RuntimeAnimation;
  51924. }());
  51925. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51926. })(BABYLON || (BABYLON = {}));
  51927. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51928. var BABYLON;
  51929. (function (BABYLON) {
  51930. var Animatable = /** @class */ (function () {
  51931. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51932. if (fromFrame === void 0) { fromFrame = 0; }
  51933. if (toFrame === void 0) { toFrame = 100; }
  51934. if (loopAnimation === void 0) { loopAnimation = false; }
  51935. if (speedRatio === void 0) { speedRatio = 1.0; }
  51936. this.target = target;
  51937. this.fromFrame = fromFrame;
  51938. this.toFrame = toFrame;
  51939. this.loopAnimation = loopAnimation;
  51940. this.onAnimationEnd = onAnimationEnd;
  51941. this._localDelayOffset = null;
  51942. this._pausedDelay = null;
  51943. this._runtimeAnimations = new Array();
  51944. this._paused = false;
  51945. this._speedRatio = 1;
  51946. this._weight = -1.0;
  51947. this.animationStarted = false;
  51948. this._scene = scene;
  51949. if (animations) {
  51950. this.appendAnimations(target, animations);
  51951. }
  51952. this._speedRatio = speedRatio;
  51953. scene._activeAnimatables.push(this);
  51954. }
  51955. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51956. /**
  51957. * Gets the root Animatable used to synchronize and normalize animations
  51958. */
  51959. get: function () {
  51960. return this._syncRoot;
  51961. },
  51962. enumerable: true,
  51963. configurable: true
  51964. });
  51965. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51966. /**
  51967. * Gets the current frame of the first RuntimeAnimation
  51968. * Used to synchronize Animatables
  51969. */
  51970. get: function () {
  51971. if (this._runtimeAnimations.length === 0) {
  51972. return 0;
  51973. }
  51974. return this._runtimeAnimations[0].currentFrame;
  51975. },
  51976. enumerable: true,
  51977. configurable: true
  51978. });
  51979. Object.defineProperty(Animatable.prototype, "weight", {
  51980. /**
  51981. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51982. */
  51983. get: function () {
  51984. return this._weight;
  51985. },
  51986. set: function (value) {
  51987. if (value === -1) { // -1 is ok and means no weight
  51988. this._weight = -1;
  51989. return;
  51990. }
  51991. // Else weight must be in [0, 1] range
  51992. this._weight = Math.min(Math.max(value, 0), 1.0);
  51993. },
  51994. enumerable: true,
  51995. configurable: true
  51996. });
  51997. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51998. /**
  51999. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52000. */
  52001. get: function () {
  52002. return this._speedRatio;
  52003. },
  52004. set: function (value) {
  52005. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52006. var animation = this._runtimeAnimations[index];
  52007. animation._prepareForSpeedRatioChange(value);
  52008. }
  52009. this._speedRatio = value;
  52010. },
  52011. enumerable: true,
  52012. configurable: true
  52013. });
  52014. // Methods
  52015. /**
  52016. * Synchronize and normalize current Animatable with a source Animatable
  52017. * This is useful when using animation weights and when animations are not of the same length
  52018. * @param root defines the root Animatable to synchronize with
  52019. * @returns the current Animatable
  52020. */
  52021. Animatable.prototype.syncWith = function (root) {
  52022. this._syncRoot = root;
  52023. if (root) {
  52024. // Make sure this animatable will animate after the root
  52025. var index = this._scene._activeAnimatables.indexOf(this);
  52026. if (index > -1) {
  52027. this._scene._activeAnimatables.splice(index, 1);
  52028. this._scene._activeAnimatables.push(this);
  52029. }
  52030. }
  52031. return this;
  52032. };
  52033. Animatable.prototype.getAnimations = function () {
  52034. return this._runtimeAnimations;
  52035. };
  52036. Animatable.prototype.appendAnimations = function (target, animations) {
  52037. for (var index = 0; index < animations.length; index++) {
  52038. var animation = animations[index];
  52039. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52040. }
  52041. };
  52042. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52043. var runtimeAnimations = this._runtimeAnimations;
  52044. for (var index = 0; index < runtimeAnimations.length; index++) {
  52045. if (runtimeAnimations[index].animation.targetProperty === property) {
  52046. return runtimeAnimations[index].animation;
  52047. }
  52048. }
  52049. return null;
  52050. };
  52051. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52052. var runtimeAnimations = this._runtimeAnimations;
  52053. for (var index = 0; index < runtimeAnimations.length; index++) {
  52054. if (runtimeAnimations[index].animation.targetProperty === property) {
  52055. return runtimeAnimations[index];
  52056. }
  52057. }
  52058. return null;
  52059. };
  52060. Animatable.prototype.reset = function () {
  52061. var runtimeAnimations = this._runtimeAnimations;
  52062. for (var index = 0; index < runtimeAnimations.length; index++) {
  52063. runtimeAnimations[index].reset();
  52064. }
  52065. // Reset to original value
  52066. for (index = 0; index < runtimeAnimations.length; index++) {
  52067. var animation = runtimeAnimations[index];
  52068. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  52069. }
  52070. this._localDelayOffset = null;
  52071. this._pausedDelay = null;
  52072. };
  52073. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52074. var runtimeAnimations = this._runtimeAnimations;
  52075. for (var index = 0; index < runtimeAnimations.length; index++) {
  52076. runtimeAnimations[index].animation.enableBlending = true;
  52077. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52078. }
  52079. };
  52080. Animatable.prototype.disableBlending = function () {
  52081. var runtimeAnimations = this._runtimeAnimations;
  52082. for (var index = 0; index < runtimeAnimations.length; index++) {
  52083. runtimeAnimations[index].animation.enableBlending = false;
  52084. }
  52085. };
  52086. Animatable.prototype.goToFrame = function (frame) {
  52087. var runtimeAnimations = this._runtimeAnimations;
  52088. if (runtimeAnimations[0]) {
  52089. var fps = runtimeAnimations[0].animation.framePerSecond;
  52090. var currentFrame = runtimeAnimations[0].currentFrame;
  52091. var adjustTime = frame - currentFrame;
  52092. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52093. if (this._localDelayOffset === null) {
  52094. this._localDelayOffset = 0;
  52095. }
  52096. this._localDelayOffset -= delay;
  52097. }
  52098. for (var index = 0; index < runtimeAnimations.length; index++) {
  52099. runtimeAnimations[index].goToFrame(frame);
  52100. }
  52101. };
  52102. Animatable.prototype.pause = function () {
  52103. if (this._paused) {
  52104. return;
  52105. }
  52106. this._paused = true;
  52107. };
  52108. Animatable.prototype.restart = function () {
  52109. this._paused = false;
  52110. };
  52111. Animatable.prototype.stop = function (animationName) {
  52112. if (animationName) {
  52113. var idx = this._scene._activeAnimatables.indexOf(this);
  52114. if (idx > -1) {
  52115. var runtimeAnimations = this._runtimeAnimations;
  52116. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52117. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52118. continue;
  52119. }
  52120. runtimeAnimations[index].dispose();
  52121. runtimeAnimations.splice(index, 1);
  52122. }
  52123. if (runtimeAnimations.length == 0) {
  52124. this._scene._activeAnimatables.splice(idx, 1);
  52125. if (this.onAnimationEnd) {
  52126. this.onAnimationEnd();
  52127. }
  52128. }
  52129. }
  52130. }
  52131. else {
  52132. var index = this._scene._activeAnimatables.indexOf(this);
  52133. if (index > -1) {
  52134. this._scene._activeAnimatables.splice(index, 1);
  52135. var runtimeAnimations = this._runtimeAnimations;
  52136. for (var index = 0; index < runtimeAnimations.length; index++) {
  52137. runtimeAnimations[index].dispose();
  52138. }
  52139. if (this.onAnimationEnd) {
  52140. this.onAnimationEnd();
  52141. }
  52142. }
  52143. }
  52144. };
  52145. Animatable.prototype._animate = function (delay) {
  52146. if (this._paused) {
  52147. this.animationStarted = false;
  52148. if (this._pausedDelay === null) {
  52149. this._pausedDelay = delay;
  52150. }
  52151. return true;
  52152. }
  52153. if (this._localDelayOffset === null) {
  52154. this._localDelayOffset = delay;
  52155. this._pausedDelay = null;
  52156. }
  52157. else if (this._pausedDelay !== null) {
  52158. this._localDelayOffset += delay - this._pausedDelay;
  52159. this._pausedDelay = null;
  52160. }
  52161. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52162. return true;
  52163. }
  52164. // Animating
  52165. var running = false;
  52166. var runtimeAnimations = this._runtimeAnimations;
  52167. var index;
  52168. for (index = 0; index < runtimeAnimations.length; index++) {
  52169. var animation = runtimeAnimations[index];
  52170. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52171. running = running || isRunning;
  52172. }
  52173. this.animationStarted = running;
  52174. if (!running) {
  52175. // Remove from active animatables
  52176. index = this._scene._activeAnimatables.indexOf(this);
  52177. this._scene._activeAnimatables.splice(index, 1);
  52178. // Dispose all runtime animations
  52179. for (index = 0; index < runtimeAnimations.length; index++) {
  52180. runtimeAnimations[index].dispose();
  52181. }
  52182. }
  52183. if (!running && this.onAnimationEnd) {
  52184. this.onAnimationEnd();
  52185. this.onAnimationEnd = null;
  52186. }
  52187. return running;
  52188. };
  52189. return Animatable;
  52190. }());
  52191. BABYLON.Animatable = Animatable;
  52192. })(BABYLON || (BABYLON = {}));
  52193. //# sourceMappingURL=babylon.animatable.js.map
  52194. var BABYLON;
  52195. (function (BABYLON) {
  52196. var EasingFunction = /** @class */ (function () {
  52197. function EasingFunction() {
  52198. // Properties
  52199. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52200. }
  52201. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52202. get: function () {
  52203. return EasingFunction._EASINGMODE_EASEIN;
  52204. },
  52205. enumerable: true,
  52206. configurable: true
  52207. });
  52208. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52209. get: function () {
  52210. return EasingFunction._EASINGMODE_EASEOUT;
  52211. },
  52212. enumerable: true,
  52213. configurable: true
  52214. });
  52215. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52216. get: function () {
  52217. return EasingFunction._EASINGMODE_EASEINOUT;
  52218. },
  52219. enumerable: true,
  52220. configurable: true
  52221. });
  52222. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52223. var n = Math.min(Math.max(easingMode, 0), 2);
  52224. this._easingMode = n;
  52225. };
  52226. EasingFunction.prototype.getEasingMode = function () {
  52227. return this._easingMode;
  52228. };
  52229. EasingFunction.prototype.easeInCore = function (gradient) {
  52230. throw new Error('You must implement this method');
  52231. };
  52232. EasingFunction.prototype.ease = function (gradient) {
  52233. switch (this._easingMode) {
  52234. case EasingFunction.EASINGMODE_EASEIN:
  52235. return this.easeInCore(gradient);
  52236. case EasingFunction.EASINGMODE_EASEOUT:
  52237. return (1 - this.easeInCore(1 - gradient));
  52238. }
  52239. if (gradient >= 0.5) {
  52240. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52241. }
  52242. return (this.easeInCore(gradient * 2) * 0.5);
  52243. };
  52244. //Statics
  52245. EasingFunction._EASINGMODE_EASEIN = 0;
  52246. EasingFunction._EASINGMODE_EASEOUT = 1;
  52247. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52248. return EasingFunction;
  52249. }());
  52250. BABYLON.EasingFunction = EasingFunction;
  52251. var CircleEase = /** @class */ (function (_super) {
  52252. __extends(CircleEase, _super);
  52253. function CircleEase() {
  52254. return _super !== null && _super.apply(this, arguments) || this;
  52255. }
  52256. CircleEase.prototype.easeInCore = function (gradient) {
  52257. gradient = Math.max(0, Math.min(1, gradient));
  52258. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52259. };
  52260. return CircleEase;
  52261. }(EasingFunction));
  52262. BABYLON.CircleEase = CircleEase;
  52263. var BackEase = /** @class */ (function (_super) {
  52264. __extends(BackEase, _super);
  52265. function BackEase(amplitude) {
  52266. if (amplitude === void 0) { amplitude = 1; }
  52267. var _this = _super.call(this) || this;
  52268. _this.amplitude = amplitude;
  52269. return _this;
  52270. }
  52271. BackEase.prototype.easeInCore = function (gradient) {
  52272. var num = Math.max(0, this.amplitude);
  52273. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52274. };
  52275. return BackEase;
  52276. }(EasingFunction));
  52277. BABYLON.BackEase = BackEase;
  52278. var BounceEase = /** @class */ (function (_super) {
  52279. __extends(BounceEase, _super);
  52280. function BounceEase(bounces, bounciness) {
  52281. if (bounces === void 0) { bounces = 3; }
  52282. if (bounciness === void 0) { bounciness = 2; }
  52283. var _this = _super.call(this) || this;
  52284. _this.bounces = bounces;
  52285. _this.bounciness = bounciness;
  52286. return _this;
  52287. }
  52288. BounceEase.prototype.easeInCore = function (gradient) {
  52289. var y = Math.max(0.0, this.bounces);
  52290. var bounciness = this.bounciness;
  52291. if (bounciness <= 1.0) {
  52292. bounciness = 1.001;
  52293. }
  52294. var num9 = Math.pow(bounciness, y);
  52295. var num5 = 1.0 - bounciness;
  52296. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52297. var num15 = gradient * num4;
  52298. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52299. var num3 = Math.floor(num65);
  52300. var num13 = num3 + 1.0;
  52301. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52302. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52303. var num7 = (num8 + num12) * 0.5;
  52304. var num6 = gradient - num7;
  52305. var num2 = num7 - num8;
  52306. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52307. };
  52308. return BounceEase;
  52309. }(EasingFunction));
  52310. BABYLON.BounceEase = BounceEase;
  52311. var CubicEase = /** @class */ (function (_super) {
  52312. __extends(CubicEase, _super);
  52313. function CubicEase() {
  52314. return _super !== null && _super.apply(this, arguments) || this;
  52315. }
  52316. CubicEase.prototype.easeInCore = function (gradient) {
  52317. return (gradient * gradient * gradient);
  52318. };
  52319. return CubicEase;
  52320. }(EasingFunction));
  52321. BABYLON.CubicEase = CubicEase;
  52322. var ElasticEase = /** @class */ (function (_super) {
  52323. __extends(ElasticEase, _super);
  52324. function ElasticEase(oscillations, springiness) {
  52325. if (oscillations === void 0) { oscillations = 3; }
  52326. if (springiness === void 0) { springiness = 3; }
  52327. var _this = _super.call(this) || this;
  52328. _this.oscillations = oscillations;
  52329. _this.springiness = springiness;
  52330. return _this;
  52331. }
  52332. ElasticEase.prototype.easeInCore = function (gradient) {
  52333. var num2;
  52334. var num3 = Math.max(0.0, this.oscillations);
  52335. var num = Math.max(0.0, this.springiness);
  52336. if (num == 0) {
  52337. num2 = gradient;
  52338. }
  52339. else {
  52340. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52341. }
  52342. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52343. };
  52344. return ElasticEase;
  52345. }(EasingFunction));
  52346. BABYLON.ElasticEase = ElasticEase;
  52347. var ExponentialEase = /** @class */ (function (_super) {
  52348. __extends(ExponentialEase, _super);
  52349. function ExponentialEase(exponent) {
  52350. if (exponent === void 0) { exponent = 2; }
  52351. var _this = _super.call(this) || this;
  52352. _this.exponent = exponent;
  52353. return _this;
  52354. }
  52355. ExponentialEase.prototype.easeInCore = function (gradient) {
  52356. if (this.exponent <= 0) {
  52357. return gradient;
  52358. }
  52359. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52360. };
  52361. return ExponentialEase;
  52362. }(EasingFunction));
  52363. BABYLON.ExponentialEase = ExponentialEase;
  52364. var PowerEase = /** @class */ (function (_super) {
  52365. __extends(PowerEase, _super);
  52366. function PowerEase(power) {
  52367. if (power === void 0) { power = 2; }
  52368. var _this = _super.call(this) || this;
  52369. _this.power = power;
  52370. return _this;
  52371. }
  52372. PowerEase.prototype.easeInCore = function (gradient) {
  52373. var y = Math.max(0.0, this.power);
  52374. return Math.pow(gradient, y);
  52375. };
  52376. return PowerEase;
  52377. }(EasingFunction));
  52378. BABYLON.PowerEase = PowerEase;
  52379. var QuadraticEase = /** @class */ (function (_super) {
  52380. __extends(QuadraticEase, _super);
  52381. function QuadraticEase() {
  52382. return _super !== null && _super.apply(this, arguments) || this;
  52383. }
  52384. QuadraticEase.prototype.easeInCore = function (gradient) {
  52385. return (gradient * gradient);
  52386. };
  52387. return QuadraticEase;
  52388. }(EasingFunction));
  52389. BABYLON.QuadraticEase = QuadraticEase;
  52390. var QuarticEase = /** @class */ (function (_super) {
  52391. __extends(QuarticEase, _super);
  52392. function QuarticEase() {
  52393. return _super !== null && _super.apply(this, arguments) || this;
  52394. }
  52395. QuarticEase.prototype.easeInCore = function (gradient) {
  52396. return (gradient * gradient * gradient * gradient);
  52397. };
  52398. return QuarticEase;
  52399. }(EasingFunction));
  52400. BABYLON.QuarticEase = QuarticEase;
  52401. var QuinticEase = /** @class */ (function (_super) {
  52402. __extends(QuinticEase, _super);
  52403. function QuinticEase() {
  52404. return _super !== null && _super.apply(this, arguments) || this;
  52405. }
  52406. QuinticEase.prototype.easeInCore = function (gradient) {
  52407. return (gradient * gradient * gradient * gradient * gradient);
  52408. };
  52409. return QuinticEase;
  52410. }(EasingFunction));
  52411. BABYLON.QuinticEase = QuinticEase;
  52412. var SineEase = /** @class */ (function (_super) {
  52413. __extends(SineEase, _super);
  52414. function SineEase() {
  52415. return _super !== null && _super.apply(this, arguments) || this;
  52416. }
  52417. SineEase.prototype.easeInCore = function (gradient) {
  52418. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52419. };
  52420. return SineEase;
  52421. }(EasingFunction));
  52422. BABYLON.SineEase = SineEase;
  52423. var BezierCurveEase = /** @class */ (function (_super) {
  52424. __extends(BezierCurveEase, _super);
  52425. function BezierCurveEase(x1, y1, x2, y2) {
  52426. if (x1 === void 0) { x1 = 0; }
  52427. if (y1 === void 0) { y1 = 0; }
  52428. if (x2 === void 0) { x2 = 1; }
  52429. if (y2 === void 0) { y2 = 1; }
  52430. var _this = _super.call(this) || this;
  52431. _this.x1 = x1;
  52432. _this.y1 = y1;
  52433. _this.x2 = x2;
  52434. _this.y2 = y2;
  52435. return _this;
  52436. }
  52437. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52438. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52439. };
  52440. return BezierCurveEase;
  52441. }(EasingFunction));
  52442. BABYLON.BezierCurveEase = BezierCurveEase;
  52443. })(BABYLON || (BABYLON = {}));
  52444. //# sourceMappingURL=babylon.easing.js.map
  52445. var BABYLON;
  52446. (function (BABYLON) {
  52447. /**
  52448. * A Condition applied to an Action
  52449. */
  52450. var Condition = /** @class */ (function () {
  52451. /**
  52452. * Creates a new Condition
  52453. * @param actionManager the manager of the action the condition is applied to
  52454. */
  52455. function Condition(actionManager) {
  52456. this._actionManager = actionManager;
  52457. }
  52458. /**
  52459. * Check if the current condition is valid
  52460. * @returns a boolean
  52461. */
  52462. Condition.prototype.isValid = function () {
  52463. return true;
  52464. };
  52465. /**
  52466. * Internal only
  52467. * @hidden
  52468. */
  52469. Condition.prototype._getProperty = function (propertyPath) {
  52470. return this._actionManager._getProperty(propertyPath);
  52471. };
  52472. /**
  52473. * Internal only
  52474. * @hidden
  52475. */
  52476. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52477. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52478. };
  52479. /**
  52480. * Serialize placeholder for child classes
  52481. * @returns the serialized object
  52482. */
  52483. Condition.prototype.serialize = function () {
  52484. };
  52485. /**
  52486. * Internal only
  52487. * @hidden
  52488. */
  52489. Condition.prototype._serialize = function (serializedCondition) {
  52490. return {
  52491. type: 2,
  52492. children: [],
  52493. name: serializedCondition.name,
  52494. properties: serializedCondition.properties
  52495. };
  52496. };
  52497. return Condition;
  52498. }());
  52499. BABYLON.Condition = Condition;
  52500. /**
  52501. * Defines specific conditional operators as extensions of Condition
  52502. */
  52503. var ValueCondition = /** @class */ (function (_super) {
  52504. __extends(ValueCondition, _super);
  52505. /**
  52506. * Creates a new ValueCondition
  52507. * @param actionManager manager for the action the condition applies to
  52508. * @param target for the action
  52509. * @param propertyPath path to specify the property of the target the conditional operator uses
  52510. * @param value the value compared by the conditional operator against the current value of the property
  52511. * @param operator the conditional operator, default ValueCondition.IsEqual
  52512. */
  52513. function ValueCondition(actionManager, target,
  52514. /** path to specify the property of the target the conditional operator uses */
  52515. propertyPath,
  52516. /** the value compared by the conditional operator against the current value of the property */
  52517. value,
  52518. /** the conditional operator, default ValueCondition.IsEqual */
  52519. operator) {
  52520. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52521. var _this = _super.call(this, actionManager) || this;
  52522. _this.propertyPath = propertyPath;
  52523. _this.value = value;
  52524. _this.operator = operator;
  52525. _this._target = target;
  52526. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52527. _this._property = _this._getProperty(_this.propertyPath);
  52528. return _this;
  52529. }
  52530. Object.defineProperty(ValueCondition, "IsEqual", {
  52531. /**
  52532. * returns the number for IsEqual
  52533. */
  52534. get: function () {
  52535. return ValueCondition._IsEqual;
  52536. },
  52537. enumerable: true,
  52538. configurable: true
  52539. });
  52540. Object.defineProperty(ValueCondition, "IsDifferent", {
  52541. /**
  52542. * Returns the number for IsDifferent
  52543. */
  52544. get: function () {
  52545. return ValueCondition._IsDifferent;
  52546. },
  52547. enumerable: true,
  52548. configurable: true
  52549. });
  52550. Object.defineProperty(ValueCondition, "IsGreater", {
  52551. /**
  52552. * Returns the number for IsGreater
  52553. */
  52554. get: function () {
  52555. return ValueCondition._IsGreater;
  52556. },
  52557. enumerable: true,
  52558. configurable: true
  52559. });
  52560. Object.defineProperty(ValueCondition, "IsLesser", {
  52561. /**
  52562. * Returns the number for IsLesser
  52563. */
  52564. get: function () {
  52565. return ValueCondition._IsLesser;
  52566. },
  52567. enumerable: true,
  52568. configurable: true
  52569. });
  52570. /**
  52571. * Compares the given value with the property value for the specified conditional operator
  52572. * @returns the result of the comparison
  52573. */
  52574. ValueCondition.prototype.isValid = function () {
  52575. switch (this.operator) {
  52576. case ValueCondition.IsGreater:
  52577. return this._effectiveTarget[this._property] > this.value;
  52578. case ValueCondition.IsLesser:
  52579. return this._effectiveTarget[this._property] < this.value;
  52580. case ValueCondition.IsEqual:
  52581. case ValueCondition.IsDifferent:
  52582. var check;
  52583. if (this.value.equals) {
  52584. check = this.value.equals(this._effectiveTarget[this._property]);
  52585. }
  52586. else {
  52587. check = this.value === this._effectiveTarget[this._property];
  52588. }
  52589. return this.operator === ValueCondition.IsEqual ? check : !check;
  52590. }
  52591. return false;
  52592. };
  52593. /**
  52594. * Serialize the ValueCondition into a JSON compatible object
  52595. * @returns serialization object
  52596. */
  52597. ValueCondition.prototype.serialize = function () {
  52598. return this._serialize({
  52599. name: "ValueCondition",
  52600. properties: [
  52601. BABYLON.Action._GetTargetProperty(this._target),
  52602. { name: "propertyPath", value: this.propertyPath },
  52603. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52604. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52605. ]
  52606. });
  52607. };
  52608. /**
  52609. * Gets the name of the conditional operator for the ValueCondition
  52610. * @param operator the conditional operator
  52611. * @returns the name
  52612. */
  52613. ValueCondition.GetOperatorName = function (operator) {
  52614. switch (operator) {
  52615. case ValueCondition._IsEqual: return "IsEqual";
  52616. case ValueCondition._IsDifferent: return "IsDifferent";
  52617. case ValueCondition._IsGreater: return "IsGreater";
  52618. case ValueCondition._IsLesser: return "IsLesser";
  52619. default: return "";
  52620. }
  52621. };
  52622. /**
  52623. * Internal only
  52624. * @hidden
  52625. */
  52626. ValueCondition._IsEqual = 0;
  52627. /**
  52628. * Internal only
  52629. * @hidden
  52630. */
  52631. ValueCondition._IsDifferent = 1;
  52632. /**
  52633. * Internal only
  52634. * @hidden
  52635. */
  52636. ValueCondition._IsGreater = 2;
  52637. /**
  52638. * Internal only
  52639. * @hidden
  52640. */
  52641. ValueCondition._IsLesser = 3;
  52642. return ValueCondition;
  52643. }(Condition));
  52644. BABYLON.ValueCondition = ValueCondition;
  52645. /**
  52646. * Defines a predicate condition as an extension of Condition
  52647. */
  52648. var PredicateCondition = /** @class */ (function (_super) {
  52649. __extends(PredicateCondition, _super);
  52650. /**
  52651. * Creates a new PredicateCondition
  52652. * @param actionManager manager for the action the condition applies to
  52653. * @param predicate defines the predicate function used to validate the condition
  52654. */
  52655. function PredicateCondition(actionManager,
  52656. /** defines the predicate function used to validate the condition */
  52657. predicate) {
  52658. var _this = _super.call(this, actionManager) || this;
  52659. _this.predicate = predicate;
  52660. return _this;
  52661. }
  52662. /**
  52663. * @returns the validity of the predicate condition
  52664. */
  52665. PredicateCondition.prototype.isValid = function () {
  52666. return this.predicate();
  52667. };
  52668. return PredicateCondition;
  52669. }(Condition));
  52670. BABYLON.PredicateCondition = PredicateCondition;
  52671. /**
  52672. * Defines a state condition as an extension of Condition
  52673. */
  52674. var StateCondition = /** @class */ (function (_super) {
  52675. __extends(StateCondition, _super);
  52676. /**
  52677. * Creates a new StateCondition
  52678. * @param actionManager manager for the action the condition applies to
  52679. * @param target of the condition
  52680. * @param value to compare with target state
  52681. */
  52682. function StateCondition(actionManager, target, value) {
  52683. var _this = _super.call(this, actionManager) || this;
  52684. _this.value = value;
  52685. _this._target = target;
  52686. return _this;
  52687. }
  52688. /**
  52689. * @returns the validity of the state
  52690. */
  52691. StateCondition.prototype.isValid = function () {
  52692. return this._target.state === this.value;
  52693. };
  52694. /**
  52695. * Serialize the StateCondition into a JSON compatible object
  52696. * @returns serialization object
  52697. */
  52698. StateCondition.prototype.serialize = function () {
  52699. return this._serialize({
  52700. name: "StateCondition",
  52701. properties: [
  52702. BABYLON.Action._GetTargetProperty(this._target),
  52703. { name: "value", value: this.value }
  52704. ]
  52705. });
  52706. };
  52707. return StateCondition;
  52708. }(Condition));
  52709. BABYLON.StateCondition = StateCondition;
  52710. })(BABYLON || (BABYLON = {}));
  52711. //# sourceMappingURL=babylon.condition.js.map
  52712. var BABYLON;
  52713. (function (BABYLON) {
  52714. /**
  52715. * The action to be carried out following a trigger
  52716. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52717. */
  52718. var Action = /** @class */ (function () {
  52719. /**
  52720. * Creates a new Action
  52721. * @param triggerOptions the trigger, with or without parameters, for the action
  52722. * @param condition an optional determinant of action
  52723. */
  52724. function Action(
  52725. /** the trigger, with or without parameters, for the action */
  52726. triggerOptions, condition) {
  52727. this.triggerOptions = triggerOptions;
  52728. /**
  52729. * An event triggered prior to action being executed.
  52730. */
  52731. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52732. if (triggerOptions.parameter) {
  52733. this.trigger = triggerOptions.trigger;
  52734. this._triggerParameter = triggerOptions.parameter;
  52735. }
  52736. else {
  52737. this.trigger = triggerOptions;
  52738. }
  52739. this._nextActiveAction = this;
  52740. this._condition = condition;
  52741. }
  52742. /**
  52743. * Internal only
  52744. * @hidden
  52745. */
  52746. Action.prototype._prepare = function () {
  52747. };
  52748. /**
  52749. * Gets the trigger parameters
  52750. * @returns the trigger parameters
  52751. */
  52752. Action.prototype.getTriggerParameter = function () {
  52753. return this._triggerParameter;
  52754. };
  52755. /**
  52756. * Internal only - executes current action event
  52757. * @hidden
  52758. */
  52759. Action.prototype._executeCurrent = function (evt) {
  52760. if (this._nextActiveAction._condition) {
  52761. var condition = this._nextActiveAction._condition;
  52762. var currentRenderId = this._actionManager.getScene().getRenderId();
  52763. // We cache the current evaluation for the current frame
  52764. if (condition._evaluationId === currentRenderId) {
  52765. if (!condition._currentResult) {
  52766. return;
  52767. }
  52768. }
  52769. else {
  52770. condition._evaluationId = currentRenderId;
  52771. if (!condition.isValid()) {
  52772. condition._currentResult = false;
  52773. return;
  52774. }
  52775. condition._currentResult = true;
  52776. }
  52777. }
  52778. this.onBeforeExecuteObservable.notifyObservers(this);
  52779. this._nextActiveAction.execute(evt);
  52780. this.skipToNextActiveAction();
  52781. };
  52782. /**
  52783. * Execute placeholder for child classes
  52784. * @param evt optional action event
  52785. */
  52786. Action.prototype.execute = function (evt) {
  52787. };
  52788. /**
  52789. * Skips to next active action
  52790. */
  52791. Action.prototype.skipToNextActiveAction = function () {
  52792. if (this._nextActiveAction._child) {
  52793. if (!this._nextActiveAction._child._actionManager) {
  52794. this._nextActiveAction._child._actionManager = this._actionManager;
  52795. }
  52796. this._nextActiveAction = this._nextActiveAction._child;
  52797. }
  52798. else {
  52799. this._nextActiveAction = this;
  52800. }
  52801. };
  52802. /**
  52803. * Adds action to chain of actions, may be a DoNothingAction
  52804. * @param action defines the next action to execute
  52805. * @returns The action passed in
  52806. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52807. */
  52808. Action.prototype.then = function (action) {
  52809. this._child = action;
  52810. action._actionManager = this._actionManager;
  52811. action._prepare();
  52812. return action;
  52813. };
  52814. /**
  52815. * Internal only
  52816. * @hidden
  52817. */
  52818. Action.prototype._getProperty = function (propertyPath) {
  52819. return this._actionManager._getProperty(propertyPath);
  52820. };
  52821. /**
  52822. * Internal only
  52823. * @hidden
  52824. */
  52825. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52826. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52827. };
  52828. /**
  52829. * Serialize placeholder for child classes
  52830. * @param parent of child
  52831. * @returns the serialized object
  52832. */
  52833. Action.prototype.serialize = function (parent) {
  52834. };
  52835. /**
  52836. * Internal only called by serialize
  52837. * @hidden
  52838. */
  52839. Action.prototype._serialize = function (serializedAction, parent) {
  52840. var serializationObject = {
  52841. type: 1,
  52842. children: [],
  52843. name: serializedAction.name,
  52844. properties: serializedAction.properties || []
  52845. };
  52846. // Serialize child
  52847. if (this._child) {
  52848. this._child.serialize(serializationObject);
  52849. }
  52850. // Check if "this" has a condition
  52851. if (this._condition) {
  52852. var serializedCondition = this._condition.serialize();
  52853. serializedCondition.children.push(serializationObject);
  52854. if (parent) {
  52855. parent.children.push(serializedCondition);
  52856. }
  52857. return serializedCondition;
  52858. }
  52859. if (parent) {
  52860. parent.children.push(serializationObject);
  52861. }
  52862. return serializationObject;
  52863. };
  52864. /**
  52865. * Internal only
  52866. * @hidden
  52867. */
  52868. Action._SerializeValueAsString = function (value) {
  52869. if (typeof value === "number") {
  52870. return value.toString();
  52871. }
  52872. if (typeof value === "boolean") {
  52873. return value ? "true" : "false";
  52874. }
  52875. if (value instanceof BABYLON.Vector2) {
  52876. return value.x + ", " + value.y;
  52877. }
  52878. if (value instanceof BABYLON.Vector3) {
  52879. return value.x + ", " + value.y + ", " + value.z;
  52880. }
  52881. if (value instanceof BABYLON.Color3) {
  52882. return value.r + ", " + value.g + ", " + value.b;
  52883. }
  52884. if (value instanceof BABYLON.Color4) {
  52885. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52886. }
  52887. return value; // string
  52888. };
  52889. /**
  52890. * Internal only
  52891. * @hidden
  52892. */
  52893. Action._GetTargetProperty = function (target) {
  52894. return {
  52895. name: "target",
  52896. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52897. : target instanceof BABYLON.Light ? "LightProperties"
  52898. : target instanceof BABYLON.Camera ? "CameraProperties"
  52899. : "SceneProperties",
  52900. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52901. };
  52902. };
  52903. return Action;
  52904. }());
  52905. BABYLON.Action = Action;
  52906. })(BABYLON || (BABYLON = {}));
  52907. //# sourceMappingURL=babylon.action.js.map
  52908. var BABYLON;
  52909. (function (BABYLON) {
  52910. /**
  52911. * ActionEvent is the event being sent when an action is triggered.
  52912. */
  52913. var ActionEvent = /** @class */ (function () {
  52914. /**
  52915. * Creates a new ActionEvent
  52916. * @param source The mesh or sprite that triggered the action
  52917. * @param pointerX The X mouse cursor position at the time of the event
  52918. * @param pointerY The Y mouse cursor position at the time of the event
  52919. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52920. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52921. * @param additionalData additional data for the event
  52922. */
  52923. function ActionEvent(
  52924. /** The mesh or sprite that triggered the action */
  52925. source,
  52926. /** The X mouse cursor position at the time of the event */
  52927. pointerX,
  52928. /** The Y mouse cursor position at the time of the event */
  52929. pointerY,
  52930. /** The mesh that is currently pointed at (can be null) */
  52931. meshUnderPointer,
  52932. /** the original (browser) event that triggered the ActionEvent */
  52933. sourceEvent,
  52934. /** additional data for the event */
  52935. additionalData) {
  52936. this.source = source;
  52937. this.pointerX = pointerX;
  52938. this.pointerY = pointerY;
  52939. this.meshUnderPointer = meshUnderPointer;
  52940. this.sourceEvent = sourceEvent;
  52941. this.additionalData = additionalData;
  52942. }
  52943. /**
  52944. * Helper function to auto-create an ActionEvent from a source mesh.
  52945. * @param source The source mesh that triggered the event
  52946. * @param evt The original (browser) event
  52947. * @param additionalData additional data for the event
  52948. * @returns the new ActionEvent
  52949. */
  52950. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52951. var scene = source.getScene();
  52952. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52953. };
  52954. /**
  52955. * Helper function to auto-create an ActionEvent from a source sprite
  52956. * @param source The source sprite that triggered the event
  52957. * @param scene Scene associated with the sprite
  52958. * @param evt The original (browser) event
  52959. * @param additionalData additional data for the event
  52960. * @returns the new ActionEvent
  52961. */
  52962. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52963. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52964. };
  52965. /**
  52966. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52967. * @param scene the scene where the event occurred
  52968. * @param evt The original (browser) event
  52969. * @returns the new ActionEvent
  52970. */
  52971. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52972. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52973. };
  52974. /**
  52975. * Helper function to auto-create an ActionEvent from a primitive
  52976. * @param prim defines the target primitive
  52977. * @param pointerPos defines the pointer position
  52978. * @param evt The original (browser) event
  52979. * @param additionalData additional data for the event
  52980. * @returns the new ActionEvent
  52981. */
  52982. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52983. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52984. };
  52985. return ActionEvent;
  52986. }());
  52987. BABYLON.ActionEvent = ActionEvent;
  52988. /**
  52989. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52990. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52991. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52992. */
  52993. var ActionManager = /** @class */ (function () {
  52994. /**
  52995. * Creates a new action manager
  52996. * @param scene defines the hosting scene
  52997. */
  52998. function ActionManager(scene) {
  52999. // Members
  53000. /** Gets the list of actions */
  53001. this.actions = new Array();
  53002. /** Gets the cursor to use when hovering items */
  53003. this.hoverCursor = '';
  53004. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53005. scene._actionManagers.push(this);
  53006. }
  53007. Object.defineProperty(ActionManager, "NothingTrigger", {
  53008. /**
  53009. * Nothing
  53010. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53011. */
  53012. get: function () {
  53013. return ActionManager._NothingTrigger;
  53014. },
  53015. enumerable: true,
  53016. configurable: true
  53017. });
  53018. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53019. /**
  53020. * On pick
  53021. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53022. */
  53023. get: function () {
  53024. return ActionManager._OnPickTrigger;
  53025. },
  53026. enumerable: true,
  53027. configurable: true
  53028. });
  53029. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53030. /**
  53031. * On left pick
  53032. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53033. */
  53034. get: function () {
  53035. return ActionManager._OnLeftPickTrigger;
  53036. },
  53037. enumerable: true,
  53038. configurable: true
  53039. });
  53040. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53041. /**
  53042. * On right pick
  53043. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53044. */
  53045. get: function () {
  53046. return ActionManager._OnRightPickTrigger;
  53047. },
  53048. enumerable: true,
  53049. configurable: true
  53050. });
  53051. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53052. /**
  53053. * On center pick
  53054. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53055. */
  53056. get: function () {
  53057. return ActionManager._OnCenterPickTrigger;
  53058. },
  53059. enumerable: true,
  53060. configurable: true
  53061. });
  53062. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53063. /**
  53064. * On pick down
  53065. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53066. */
  53067. get: function () {
  53068. return ActionManager._OnPickDownTrigger;
  53069. },
  53070. enumerable: true,
  53071. configurable: true
  53072. });
  53073. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53074. /**
  53075. * On double pick
  53076. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53077. */
  53078. get: function () {
  53079. return ActionManager._OnDoublePickTrigger;
  53080. },
  53081. enumerable: true,
  53082. configurable: true
  53083. });
  53084. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53085. /**
  53086. * On pick up
  53087. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53088. */
  53089. get: function () {
  53090. return ActionManager._OnPickUpTrigger;
  53091. },
  53092. enumerable: true,
  53093. configurable: true
  53094. });
  53095. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53096. /**
  53097. * On pick out.
  53098. * This trigger will only be raised if you also declared a OnPickDown
  53099. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53100. */
  53101. get: function () {
  53102. return ActionManager._OnPickOutTrigger;
  53103. },
  53104. enumerable: true,
  53105. configurable: true
  53106. });
  53107. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53108. /**
  53109. * On long press
  53110. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53111. */
  53112. get: function () {
  53113. return ActionManager._OnLongPressTrigger;
  53114. },
  53115. enumerable: true,
  53116. configurable: true
  53117. });
  53118. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53119. /**
  53120. * On pointer over
  53121. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53122. */
  53123. get: function () {
  53124. return ActionManager._OnPointerOverTrigger;
  53125. },
  53126. enumerable: true,
  53127. configurable: true
  53128. });
  53129. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53130. /**
  53131. * On pointer out
  53132. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53133. */
  53134. get: function () {
  53135. return ActionManager._OnPointerOutTrigger;
  53136. },
  53137. enumerable: true,
  53138. configurable: true
  53139. });
  53140. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53141. /**
  53142. * On every frame
  53143. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53144. */
  53145. get: function () {
  53146. return ActionManager._OnEveryFrameTrigger;
  53147. },
  53148. enumerable: true,
  53149. configurable: true
  53150. });
  53151. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53152. /**
  53153. * On intersection enter
  53154. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53155. */
  53156. get: function () {
  53157. return ActionManager._OnIntersectionEnterTrigger;
  53158. },
  53159. enumerable: true,
  53160. configurable: true
  53161. });
  53162. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53163. /**
  53164. * On intersection exit
  53165. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53166. */
  53167. get: function () {
  53168. return ActionManager._OnIntersectionExitTrigger;
  53169. },
  53170. enumerable: true,
  53171. configurable: true
  53172. });
  53173. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53174. /**
  53175. * On key down
  53176. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53177. */
  53178. get: function () {
  53179. return ActionManager._OnKeyDownTrigger;
  53180. },
  53181. enumerable: true,
  53182. configurable: true
  53183. });
  53184. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53185. /**
  53186. * On key up
  53187. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53188. */
  53189. get: function () {
  53190. return ActionManager._OnKeyUpTrigger;
  53191. },
  53192. enumerable: true,
  53193. configurable: true
  53194. });
  53195. // Methods
  53196. /**
  53197. * Releases all associated resources
  53198. */
  53199. ActionManager.prototype.dispose = function () {
  53200. var index = this._scene._actionManagers.indexOf(this);
  53201. for (var i = 0; i < this.actions.length; i++) {
  53202. var action = this.actions[i];
  53203. ActionManager.Triggers[action.trigger]--;
  53204. if (ActionManager.Triggers[action.trigger] === 0) {
  53205. delete ActionManager.Triggers[action.trigger];
  53206. }
  53207. }
  53208. if (index > -1) {
  53209. this._scene._actionManagers.splice(index, 1);
  53210. }
  53211. };
  53212. /**
  53213. * Gets hosting scene
  53214. * @returns the hosting scene
  53215. */
  53216. ActionManager.prototype.getScene = function () {
  53217. return this._scene;
  53218. };
  53219. /**
  53220. * Does this action manager handles actions of any of the given triggers
  53221. * @param triggers defines the triggers to be tested
  53222. * @return a boolean indicating whether one (or more) of the triggers is handled
  53223. */
  53224. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53225. for (var index = 0; index < this.actions.length; index++) {
  53226. var action = this.actions[index];
  53227. if (triggers.indexOf(action.trigger) > -1) {
  53228. return true;
  53229. }
  53230. }
  53231. return false;
  53232. };
  53233. /**
  53234. * Does this action manager handles actions of a given trigger
  53235. * @param trigger defines the trigger to be tested
  53236. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53237. * @return whether the trigger is handled
  53238. */
  53239. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53240. for (var index = 0; index < this.actions.length; index++) {
  53241. var action = this.actions[index];
  53242. if (action.trigger === trigger) {
  53243. if (parameterPredicate) {
  53244. if (parameterPredicate(action.getTriggerParameter())) {
  53245. return true;
  53246. }
  53247. }
  53248. else {
  53249. return true;
  53250. }
  53251. }
  53252. }
  53253. return false;
  53254. };
  53255. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53256. /**
  53257. * Does this action manager has pointer triggers
  53258. */
  53259. get: function () {
  53260. for (var index = 0; index < this.actions.length; index++) {
  53261. var action = this.actions[index];
  53262. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53263. return true;
  53264. }
  53265. }
  53266. return false;
  53267. },
  53268. enumerable: true,
  53269. configurable: true
  53270. });
  53271. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53272. /**
  53273. * Does this action manager has pick triggers
  53274. */
  53275. get: function () {
  53276. for (var index = 0; index < this.actions.length; index++) {
  53277. var action = this.actions[index];
  53278. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53279. return true;
  53280. }
  53281. }
  53282. return false;
  53283. },
  53284. enumerable: true,
  53285. configurable: true
  53286. });
  53287. Object.defineProperty(ActionManager, "HasTriggers", {
  53288. /**
  53289. * Does exist one action manager with at least one trigger
  53290. **/
  53291. get: function () {
  53292. for (var t in ActionManager.Triggers) {
  53293. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53294. return true;
  53295. }
  53296. }
  53297. return false;
  53298. },
  53299. enumerable: true,
  53300. configurable: true
  53301. });
  53302. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53303. /**
  53304. * Does exist one action manager with at least one pick trigger
  53305. **/
  53306. get: function () {
  53307. for (var t in ActionManager.Triggers) {
  53308. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53309. var t_int = parseInt(t);
  53310. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53311. return true;
  53312. }
  53313. }
  53314. }
  53315. return false;
  53316. },
  53317. enumerable: true,
  53318. configurable: true
  53319. });
  53320. /**
  53321. * Does exist one action manager that handles actions of a given trigger
  53322. * @param trigger defines the trigger to be tested
  53323. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53324. **/
  53325. ActionManager.HasSpecificTrigger = function (trigger) {
  53326. for (var t in ActionManager.Triggers) {
  53327. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53328. var t_int = parseInt(t);
  53329. if (t_int === trigger) {
  53330. return true;
  53331. }
  53332. }
  53333. }
  53334. return false;
  53335. };
  53336. /**
  53337. * Registers an action to this action manager
  53338. * @param action defines the action to be registered
  53339. * @return the action amended (prepared) after registration
  53340. */
  53341. ActionManager.prototype.registerAction = function (action) {
  53342. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53343. if (this.getScene().actionManager !== this) {
  53344. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53345. return null;
  53346. }
  53347. }
  53348. this.actions.push(action);
  53349. if (ActionManager.Triggers[action.trigger]) {
  53350. ActionManager.Triggers[action.trigger]++;
  53351. }
  53352. else {
  53353. ActionManager.Triggers[action.trigger] = 1;
  53354. }
  53355. action._actionManager = this;
  53356. action._prepare();
  53357. return action;
  53358. };
  53359. /**
  53360. * Unregisters an action to this action manager
  53361. * @param action defines the action to be unregistered
  53362. * @return a boolean indicating whether the action has been unregistered
  53363. */
  53364. ActionManager.prototype.unregisterAction = function (action) {
  53365. var index = this.actions.indexOf(action);
  53366. if (index !== -1) {
  53367. this.actions.splice(index, 1);
  53368. ActionManager.Triggers[action.trigger] -= 1;
  53369. if (ActionManager.Triggers[action.trigger] === 0) {
  53370. delete ActionManager.Triggers[action.trigger];
  53371. }
  53372. delete action._actionManager;
  53373. return true;
  53374. }
  53375. return false;
  53376. };
  53377. /**
  53378. * Process a specific trigger
  53379. * @param trigger defines the trigger to process
  53380. * @param evt defines the event details to be processed
  53381. */
  53382. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53383. for (var index = 0; index < this.actions.length; index++) {
  53384. var action = this.actions[index];
  53385. if (action.trigger === trigger) {
  53386. if (evt) {
  53387. if (trigger === ActionManager.OnKeyUpTrigger
  53388. || trigger === ActionManager.OnKeyDownTrigger) {
  53389. var parameter = action.getTriggerParameter();
  53390. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53391. if (!parameter.toLowerCase) {
  53392. continue;
  53393. }
  53394. var lowerCase = parameter.toLowerCase();
  53395. if (lowerCase !== evt.sourceEvent.key) {
  53396. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53397. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53398. if (actualkey !== lowerCase) {
  53399. continue;
  53400. }
  53401. }
  53402. }
  53403. }
  53404. }
  53405. action._executeCurrent(evt);
  53406. }
  53407. }
  53408. };
  53409. /** @hidden */
  53410. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53411. var properties = propertyPath.split(".");
  53412. for (var index = 0; index < properties.length - 1; index++) {
  53413. target = target[properties[index]];
  53414. }
  53415. return target;
  53416. };
  53417. /** @hidden */
  53418. ActionManager.prototype._getProperty = function (propertyPath) {
  53419. var properties = propertyPath.split(".");
  53420. return properties[properties.length - 1];
  53421. };
  53422. /**
  53423. * Serialize this manager to a JSON object
  53424. * @param name defines the property name to store this manager
  53425. * @returns a JSON representation of this manager
  53426. */
  53427. ActionManager.prototype.serialize = function (name) {
  53428. var root = {
  53429. children: new Array(),
  53430. name: name,
  53431. type: 3,
  53432. properties: new Array() // Empty for root but required
  53433. };
  53434. for (var i = 0; i < this.actions.length; i++) {
  53435. var triggerObject = {
  53436. type: 0,
  53437. children: new Array(),
  53438. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53439. properties: new Array()
  53440. };
  53441. var triggerOptions = this.actions[i].triggerOptions;
  53442. if (triggerOptions && typeof triggerOptions !== "number") {
  53443. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53444. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53445. }
  53446. else {
  53447. var parameter = {};
  53448. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53449. if (triggerOptions.parameter.mesh) {
  53450. parameter._meshId = triggerOptions.parameter.mesh.id;
  53451. }
  53452. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53453. }
  53454. }
  53455. // Serialize child action, recursively
  53456. this.actions[i].serialize(triggerObject);
  53457. // Add serialized trigger
  53458. root.children.push(triggerObject);
  53459. }
  53460. return root;
  53461. };
  53462. /**
  53463. * Creates a new ActionManager from a JSON data
  53464. * @param parsedActions defines the JSON data to read from
  53465. * @param object defines the hosting mesh
  53466. * @param scene defines the hosting scene
  53467. */
  53468. ActionManager.Parse = function (parsedActions, object, scene) {
  53469. var actionManager = new ActionManager(scene);
  53470. if (object === null)
  53471. scene.actionManager = actionManager;
  53472. else
  53473. object.actionManager = actionManager;
  53474. // instanciate a new object
  53475. var instanciate = function (name, params) {
  53476. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53477. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53478. newInstance.constructor.apply(newInstance, params);
  53479. return newInstance;
  53480. };
  53481. var parseParameter = function (name, value, target, propertyPath) {
  53482. if (propertyPath === null) {
  53483. // String, boolean or float
  53484. var floatValue = parseFloat(value);
  53485. if (value === "true" || value === "false")
  53486. return value === "true";
  53487. else
  53488. return isNaN(floatValue) ? value : floatValue;
  53489. }
  53490. var effectiveTarget = propertyPath.split(".");
  53491. var values = value.split(",");
  53492. // Get effective Target
  53493. for (var i = 0; i < effectiveTarget.length; i++) {
  53494. target = target[effectiveTarget[i]];
  53495. }
  53496. // Return appropriate value with its type
  53497. if (typeof (target) === "boolean")
  53498. return values[0] === "true";
  53499. if (typeof (target) === "string")
  53500. return values[0];
  53501. // Parameters with multiple values such as Vector3 etc.
  53502. var split = new Array();
  53503. for (var i = 0; i < values.length; i++)
  53504. split.push(parseFloat(values[i]));
  53505. if (target instanceof BABYLON.Vector3)
  53506. return BABYLON.Vector3.FromArray(split);
  53507. if (target instanceof BABYLON.Vector4)
  53508. return BABYLON.Vector4.FromArray(split);
  53509. if (target instanceof BABYLON.Color3)
  53510. return BABYLON.Color3.FromArray(split);
  53511. if (target instanceof BABYLON.Color4)
  53512. return BABYLON.Color4.FromArray(split);
  53513. return parseFloat(values[0]);
  53514. };
  53515. // traverse graph per trigger
  53516. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53517. if (combineArray === void 0) { combineArray = null; }
  53518. if (parsedAction.detached)
  53519. return;
  53520. var parameters = new Array();
  53521. var target = null;
  53522. var propertyPath = null;
  53523. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53524. // Parameters
  53525. if (parsedAction.type === 2)
  53526. parameters.push(actionManager);
  53527. else
  53528. parameters.push(trigger);
  53529. if (combine) {
  53530. var actions = new Array();
  53531. for (var j = 0; j < parsedAction.combine.length; j++) {
  53532. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53533. }
  53534. parameters.push(actions);
  53535. }
  53536. else {
  53537. for (var i = 0; i < parsedAction.properties.length; i++) {
  53538. var value = parsedAction.properties[i].value;
  53539. var name = parsedAction.properties[i].name;
  53540. var targetType = parsedAction.properties[i].targetType;
  53541. if (name === "target")
  53542. if (targetType !== null && targetType === "SceneProperties")
  53543. value = target = scene;
  53544. else
  53545. value = target = scene.getNodeByName(value);
  53546. else if (name === "parent")
  53547. value = scene.getNodeByName(value);
  53548. else if (name === "sound")
  53549. value = scene.getSoundByName(value);
  53550. else if (name !== "propertyPath") {
  53551. if (parsedAction.type === 2 && name === "operator")
  53552. value = BABYLON.ValueCondition[value];
  53553. else
  53554. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53555. }
  53556. else {
  53557. propertyPath = value;
  53558. }
  53559. parameters.push(value);
  53560. }
  53561. }
  53562. if (combineArray === null) {
  53563. parameters.push(condition);
  53564. }
  53565. else {
  53566. parameters.push(null);
  53567. }
  53568. // If interpolate value action
  53569. if (parsedAction.name === "InterpolateValueAction") {
  53570. var param = parameters[parameters.length - 2];
  53571. parameters[parameters.length - 1] = param;
  53572. parameters[parameters.length - 2] = condition;
  53573. }
  53574. // Action or condition(s) and not CombineAction
  53575. var newAction = instanciate(parsedAction.name, parameters);
  53576. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53577. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53578. if (action)
  53579. action.then(nothing);
  53580. else
  53581. actionManager.registerAction(nothing);
  53582. action = nothing;
  53583. }
  53584. if (combineArray === null) {
  53585. if (newAction instanceof BABYLON.Condition) {
  53586. condition = newAction;
  53587. newAction = action;
  53588. }
  53589. else {
  53590. condition = null;
  53591. if (action)
  53592. action.then(newAction);
  53593. else
  53594. actionManager.registerAction(newAction);
  53595. }
  53596. }
  53597. else {
  53598. combineArray.push(newAction);
  53599. }
  53600. for (var i = 0; i < parsedAction.children.length; i++)
  53601. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53602. };
  53603. // triggers
  53604. for (var i = 0; i < parsedActions.children.length; i++) {
  53605. var triggerParams;
  53606. var trigger = parsedActions.children[i];
  53607. if (trigger.properties.length > 0) {
  53608. var param = trigger.properties[0].value;
  53609. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53610. if (value._meshId) {
  53611. value.mesh = scene.getMeshByID(value._meshId);
  53612. }
  53613. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53614. }
  53615. else
  53616. triggerParams = ActionManager[trigger.name];
  53617. for (var j = 0; j < trigger.children.length; j++) {
  53618. if (!trigger.detached)
  53619. traverse(trigger.children[j], triggerParams, null, null);
  53620. }
  53621. }
  53622. };
  53623. /**
  53624. * Get a trigger name by index
  53625. * @param trigger defines the trigger index
  53626. * @returns a trigger name
  53627. */
  53628. ActionManager.GetTriggerName = function (trigger) {
  53629. switch (trigger) {
  53630. case 0: return "NothingTrigger";
  53631. case 1: return "OnPickTrigger";
  53632. case 2: return "OnLeftPickTrigger";
  53633. case 3: return "OnRightPickTrigger";
  53634. case 4: return "OnCenterPickTrigger";
  53635. case 5: return "OnPickDownTrigger";
  53636. case 6: return "OnPickUpTrigger";
  53637. case 7: return "OnLongPressTrigger";
  53638. case 8: return "OnPointerOverTrigger";
  53639. case 9: return "OnPointerOutTrigger";
  53640. case 10: return "OnEveryFrameTrigger";
  53641. case 11: return "OnIntersectionEnterTrigger";
  53642. case 12: return "OnIntersectionExitTrigger";
  53643. case 13: return "OnKeyDownTrigger";
  53644. case 14: return "OnKeyUpTrigger";
  53645. case 15: return "OnPickOutTrigger";
  53646. default: return "";
  53647. }
  53648. };
  53649. // Statics
  53650. ActionManager._NothingTrigger = 0;
  53651. ActionManager._OnPickTrigger = 1;
  53652. ActionManager._OnLeftPickTrigger = 2;
  53653. ActionManager._OnRightPickTrigger = 3;
  53654. ActionManager._OnCenterPickTrigger = 4;
  53655. ActionManager._OnPickDownTrigger = 5;
  53656. ActionManager._OnDoublePickTrigger = 6;
  53657. ActionManager._OnPickUpTrigger = 7;
  53658. ActionManager._OnLongPressTrigger = 8;
  53659. ActionManager._OnPointerOverTrigger = 9;
  53660. ActionManager._OnPointerOutTrigger = 10;
  53661. ActionManager._OnEveryFrameTrigger = 11;
  53662. ActionManager._OnIntersectionEnterTrigger = 12;
  53663. ActionManager._OnIntersectionExitTrigger = 13;
  53664. ActionManager._OnKeyDownTrigger = 14;
  53665. ActionManager._OnKeyUpTrigger = 15;
  53666. ActionManager._OnPickOutTrigger = 16;
  53667. /** Gets the list of active triggers */
  53668. ActionManager.Triggers = {};
  53669. return ActionManager;
  53670. }());
  53671. BABYLON.ActionManager = ActionManager;
  53672. })(BABYLON || (BABYLON = {}));
  53673. //# sourceMappingURL=babylon.actionManager.js.map
  53674. var BABYLON;
  53675. (function (BABYLON) {
  53676. var InterpolateValueAction = /** @class */ (function (_super) {
  53677. __extends(InterpolateValueAction, _super);
  53678. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53679. if (duration === void 0) { duration = 1000; }
  53680. var _this = _super.call(this, triggerOptions, condition) || this;
  53681. _this.propertyPath = propertyPath;
  53682. _this.value = value;
  53683. _this.duration = duration;
  53684. _this.stopOtherAnimations = stopOtherAnimations;
  53685. _this.onInterpolationDone = onInterpolationDone;
  53686. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53687. _this._target = _this._effectiveTarget = target;
  53688. return _this;
  53689. }
  53690. InterpolateValueAction.prototype._prepare = function () {
  53691. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53692. this._property = this._getProperty(this.propertyPath);
  53693. };
  53694. InterpolateValueAction.prototype.execute = function () {
  53695. var _this = this;
  53696. var scene = this._actionManager.getScene();
  53697. var keys = [
  53698. {
  53699. frame: 0,
  53700. value: this._effectiveTarget[this._property]
  53701. }, {
  53702. frame: 100,
  53703. value: this.value
  53704. }
  53705. ];
  53706. var dataType;
  53707. if (typeof this.value === "number") {
  53708. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53709. }
  53710. else if (this.value instanceof BABYLON.Color3) {
  53711. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53712. }
  53713. else if (this.value instanceof BABYLON.Vector3) {
  53714. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53715. }
  53716. else if (this.value instanceof BABYLON.Matrix) {
  53717. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53718. }
  53719. else if (this.value instanceof BABYLON.Quaternion) {
  53720. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53721. }
  53722. else {
  53723. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53724. return;
  53725. }
  53726. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53727. animation.setKeys(keys);
  53728. if (this.stopOtherAnimations) {
  53729. scene.stopAnimation(this._effectiveTarget);
  53730. }
  53731. var wrapper = function () {
  53732. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53733. if (_this.onInterpolationDone) {
  53734. _this.onInterpolationDone();
  53735. }
  53736. };
  53737. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53738. };
  53739. InterpolateValueAction.prototype.serialize = function (parent) {
  53740. return _super.prototype._serialize.call(this, {
  53741. name: "InterpolateValueAction",
  53742. properties: [
  53743. BABYLON.Action._GetTargetProperty(this._target),
  53744. { name: "propertyPath", value: this.propertyPath },
  53745. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53746. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53747. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53748. ]
  53749. }, parent);
  53750. };
  53751. return InterpolateValueAction;
  53752. }(BABYLON.Action));
  53753. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53754. })(BABYLON || (BABYLON = {}));
  53755. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53756. var BABYLON;
  53757. (function (BABYLON) {
  53758. var SwitchBooleanAction = /** @class */ (function (_super) {
  53759. __extends(SwitchBooleanAction, _super);
  53760. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53761. var _this = _super.call(this, triggerOptions, condition) || this;
  53762. _this.propertyPath = propertyPath;
  53763. _this._target = _this._effectiveTarget = target;
  53764. return _this;
  53765. }
  53766. SwitchBooleanAction.prototype._prepare = function () {
  53767. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53768. this._property = this._getProperty(this.propertyPath);
  53769. };
  53770. SwitchBooleanAction.prototype.execute = function () {
  53771. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53772. };
  53773. SwitchBooleanAction.prototype.serialize = function (parent) {
  53774. return _super.prototype._serialize.call(this, {
  53775. name: "SwitchBooleanAction",
  53776. properties: [
  53777. BABYLON.Action._GetTargetProperty(this._target),
  53778. { name: "propertyPath", value: this.propertyPath }
  53779. ]
  53780. }, parent);
  53781. };
  53782. return SwitchBooleanAction;
  53783. }(BABYLON.Action));
  53784. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53785. var SetStateAction = /** @class */ (function (_super) {
  53786. __extends(SetStateAction, _super);
  53787. function SetStateAction(triggerOptions, target, value, condition) {
  53788. var _this = _super.call(this, triggerOptions, condition) || this;
  53789. _this.value = value;
  53790. _this._target = target;
  53791. return _this;
  53792. }
  53793. SetStateAction.prototype.execute = function () {
  53794. this._target.state = this.value;
  53795. };
  53796. SetStateAction.prototype.serialize = function (parent) {
  53797. return _super.prototype._serialize.call(this, {
  53798. name: "SetStateAction",
  53799. properties: [
  53800. BABYLON.Action._GetTargetProperty(this._target),
  53801. { name: "value", value: this.value }
  53802. ]
  53803. }, parent);
  53804. };
  53805. return SetStateAction;
  53806. }(BABYLON.Action));
  53807. BABYLON.SetStateAction = SetStateAction;
  53808. var SetValueAction = /** @class */ (function (_super) {
  53809. __extends(SetValueAction, _super);
  53810. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53811. var _this = _super.call(this, triggerOptions, condition) || this;
  53812. _this.propertyPath = propertyPath;
  53813. _this.value = value;
  53814. _this._target = _this._effectiveTarget = target;
  53815. return _this;
  53816. }
  53817. SetValueAction.prototype._prepare = function () {
  53818. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53819. this._property = this._getProperty(this.propertyPath);
  53820. };
  53821. SetValueAction.prototype.execute = function () {
  53822. this._effectiveTarget[this._property] = this.value;
  53823. if (this._target.markAsDirty) {
  53824. this._target.markAsDirty(this._property);
  53825. }
  53826. };
  53827. SetValueAction.prototype.serialize = function (parent) {
  53828. return _super.prototype._serialize.call(this, {
  53829. name: "SetValueAction",
  53830. properties: [
  53831. BABYLON.Action._GetTargetProperty(this._target),
  53832. { name: "propertyPath", value: this.propertyPath },
  53833. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53834. ]
  53835. }, parent);
  53836. };
  53837. return SetValueAction;
  53838. }(BABYLON.Action));
  53839. BABYLON.SetValueAction = SetValueAction;
  53840. var IncrementValueAction = /** @class */ (function (_super) {
  53841. __extends(IncrementValueAction, _super);
  53842. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53843. var _this = _super.call(this, triggerOptions, condition) || this;
  53844. _this.propertyPath = propertyPath;
  53845. _this.value = value;
  53846. _this._target = _this._effectiveTarget = target;
  53847. return _this;
  53848. }
  53849. IncrementValueAction.prototype._prepare = function () {
  53850. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53851. this._property = this._getProperty(this.propertyPath);
  53852. if (typeof this._effectiveTarget[this._property] !== "number") {
  53853. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53854. }
  53855. };
  53856. IncrementValueAction.prototype.execute = function () {
  53857. this._effectiveTarget[this._property] += this.value;
  53858. if (this._target.markAsDirty) {
  53859. this._target.markAsDirty(this._property);
  53860. }
  53861. };
  53862. IncrementValueAction.prototype.serialize = function (parent) {
  53863. return _super.prototype._serialize.call(this, {
  53864. name: "IncrementValueAction",
  53865. properties: [
  53866. BABYLON.Action._GetTargetProperty(this._target),
  53867. { name: "propertyPath", value: this.propertyPath },
  53868. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53869. ]
  53870. }, parent);
  53871. };
  53872. return IncrementValueAction;
  53873. }(BABYLON.Action));
  53874. BABYLON.IncrementValueAction = IncrementValueAction;
  53875. var PlayAnimationAction = /** @class */ (function (_super) {
  53876. __extends(PlayAnimationAction, _super);
  53877. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53878. var _this = _super.call(this, triggerOptions, condition) || this;
  53879. _this.from = from;
  53880. _this.to = to;
  53881. _this.loop = loop;
  53882. _this._target = target;
  53883. return _this;
  53884. }
  53885. PlayAnimationAction.prototype._prepare = function () {
  53886. };
  53887. PlayAnimationAction.prototype.execute = function () {
  53888. var scene = this._actionManager.getScene();
  53889. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53890. };
  53891. PlayAnimationAction.prototype.serialize = function (parent) {
  53892. return _super.prototype._serialize.call(this, {
  53893. name: "PlayAnimationAction",
  53894. properties: [
  53895. BABYLON.Action._GetTargetProperty(this._target),
  53896. { name: "from", value: String(this.from) },
  53897. { name: "to", value: String(this.to) },
  53898. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53899. ]
  53900. }, parent);
  53901. };
  53902. return PlayAnimationAction;
  53903. }(BABYLON.Action));
  53904. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53905. var StopAnimationAction = /** @class */ (function (_super) {
  53906. __extends(StopAnimationAction, _super);
  53907. function StopAnimationAction(triggerOptions, target, condition) {
  53908. var _this = _super.call(this, triggerOptions, condition) || this;
  53909. _this._target = target;
  53910. return _this;
  53911. }
  53912. StopAnimationAction.prototype._prepare = function () {
  53913. };
  53914. StopAnimationAction.prototype.execute = function () {
  53915. var scene = this._actionManager.getScene();
  53916. scene.stopAnimation(this._target);
  53917. };
  53918. StopAnimationAction.prototype.serialize = function (parent) {
  53919. return _super.prototype._serialize.call(this, {
  53920. name: "StopAnimationAction",
  53921. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53922. }, parent);
  53923. };
  53924. return StopAnimationAction;
  53925. }(BABYLON.Action));
  53926. BABYLON.StopAnimationAction = StopAnimationAction;
  53927. var DoNothingAction = /** @class */ (function (_super) {
  53928. __extends(DoNothingAction, _super);
  53929. function DoNothingAction(triggerOptions, condition) {
  53930. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53931. return _super.call(this, triggerOptions, condition) || this;
  53932. }
  53933. DoNothingAction.prototype.execute = function () {
  53934. };
  53935. DoNothingAction.prototype.serialize = function (parent) {
  53936. return _super.prototype._serialize.call(this, {
  53937. name: "DoNothingAction",
  53938. properties: []
  53939. }, parent);
  53940. };
  53941. return DoNothingAction;
  53942. }(BABYLON.Action));
  53943. BABYLON.DoNothingAction = DoNothingAction;
  53944. var CombineAction = /** @class */ (function (_super) {
  53945. __extends(CombineAction, _super);
  53946. function CombineAction(triggerOptions, children, condition) {
  53947. var _this = _super.call(this, triggerOptions, condition) || this;
  53948. _this.children = children;
  53949. return _this;
  53950. }
  53951. CombineAction.prototype._prepare = function () {
  53952. for (var index = 0; index < this.children.length; index++) {
  53953. this.children[index]._actionManager = this._actionManager;
  53954. this.children[index]._prepare();
  53955. }
  53956. };
  53957. CombineAction.prototype.execute = function (evt) {
  53958. for (var index = 0; index < this.children.length; index++) {
  53959. this.children[index].execute(evt);
  53960. }
  53961. };
  53962. CombineAction.prototype.serialize = function (parent) {
  53963. var serializationObject = _super.prototype._serialize.call(this, {
  53964. name: "CombineAction",
  53965. properties: [],
  53966. combine: []
  53967. }, parent);
  53968. for (var i = 0; i < this.children.length; i++) {
  53969. serializationObject.combine.push(this.children[i].serialize(null));
  53970. }
  53971. return serializationObject;
  53972. };
  53973. return CombineAction;
  53974. }(BABYLON.Action));
  53975. BABYLON.CombineAction = CombineAction;
  53976. var ExecuteCodeAction = /** @class */ (function (_super) {
  53977. __extends(ExecuteCodeAction, _super);
  53978. function ExecuteCodeAction(triggerOptions, func, condition) {
  53979. var _this = _super.call(this, triggerOptions, condition) || this;
  53980. _this.func = func;
  53981. return _this;
  53982. }
  53983. ExecuteCodeAction.prototype.execute = function (evt) {
  53984. this.func(evt);
  53985. };
  53986. return ExecuteCodeAction;
  53987. }(BABYLON.Action));
  53988. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53989. var SetParentAction = /** @class */ (function (_super) {
  53990. __extends(SetParentAction, _super);
  53991. function SetParentAction(triggerOptions, target, parent, condition) {
  53992. var _this = _super.call(this, triggerOptions, condition) || this;
  53993. _this._target = target;
  53994. _this._parent = parent;
  53995. return _this;
  53996. }
  53997. SetParentAction.prototype._prepare = function () {
  53998. };
  53999. SetParentAction.prototype.execute = function () {
  54000. if (this._target.parent === this._parent) {
  54001. return;
  54002. }
  54003. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54004. invertParentWorldMatrix.invert();
  54005. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54006. this._target.parent = this._parent;
  54007. };
  54008. SetParentAction.prototype.serialize = function (parent) {
  54009. return _super.prototype._serialize.call(this, {
  54010. name: "SetParentAction",
  54011. properties: [
  54012. BABYLON.Action._GetTargetProperty(this._target),
  54013. BABYLON.Action._GetTargetProperty(this._parent),
  54014. ]
  54015. }, parent);
  54016. };
  54017. return SetParentAction;
  54018. }(BABYLON.Action));
  54019. BABYLON.SetParentAction = SetParentAction;
  54020. var PlaySoundAction = /** @class */ (function (_super) {
  54021. __extends(PlaySoundAction, _super);
  54022. function PlaySoundAction(triggerOptions, sound, condition) {
  54023. var _this = _super.call(this, triggerOptions, condition) || this;
  54024. _this._sound = sound;
  54025. return _this;
  54026. }
  54027. PlaySoundAction.prototype._prepare = function () {
  54028. };
  54029. PlaySoundAction.prototype.execute = function () {
  54030. if (this._sound !== undefined)
  54031. this._sound.play();
  54032. };
  54033. PlaySoundAction.prototype.serialize = function (parent) {
  54034. return _super.prototype._serialize.call(this, {
  54035. name: "PlaySoundAction",
  54036. properties: [{ name: "sound", value: this._sound.name }]
  54037. }, parent);
  54038. };
  54039. return PlaySoundAction;
  54040. }(BABYLON.Action));
  54041. BABYLON.PlaySoundAction = PlaySoundAction;
  54042. var StopSoundAction = /** @class */ (function (_super) {
  54043. __extends(StopSoundAction, _super);
  54044. function StopSoundAction(triggerOptions, sound, condition) {
  54045. var _this = _super.call(this, triggerOptions, condition) || this;
  54046. _this._sound = sound;
  54047. return _this;
  54048. }
  54049. StopSoundAction.prototype._prepare = function () {
  54050. };
  54051. StopSoundAction.prototype.execute = function () {
  54052. if (this._sound !== undefined)
  54053. this._sound.stop();
  54054. };
  54055. StopSoundAction.prototype.serialize = function (parent) {
  54056. return _super.prototype._serialize.call(this, {
  54057. name: "StopSoundAction",
  54058. properties: [{ name: "sound", value: this._sound.name }]
  54059. }, parent);
  54060. };
  54061. return StopSoundAction;
  54062. }(BABYLON.Action));
  54063. BABYLON.StopSoundAction = StopSoundAction;
  54064. })(BABYLON || (BABYLON = {}));
  54065. //# sourceMappingURL=babylon.directActions.js.map
  54066. var BABYLON;
  54067. (function (BABYLON) {
  54068. var SpriteManager = /** @class */ (function () {
  54069. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54070. if (epsilon === void 0) { epsilon = 0.01; }
  54071. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54072. this.name = name;
  54073. this.sprites = new Array();
  54074. this.renderingGroupId = 0;
  54075. this.layerMask = 0x0FFFFFFF;
  54076. this.fogEnabled = true;
  54077. this.isPickable = false;
  54078. /**
  54079. * An event triggered when the manager is disposed.
  54080. */
  54081. this.onDisposeObservable = new BABYLON.Observable();
  54082. this._vertexBuffers = {};
  54083. this._capacity = capacity;
  54084. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54085. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54086. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54087. if (cellSize.width && cellSize.height) {
  54088. this.cellWidth = cellSize.width;
  54089. this.cellHeight = cellSize.height;
  54090. }
  54091. else if (cellSize !== undefined) {
  54092. this.cellWidth = cellSize;
  54093. this.cellHeight = cellSize;
  54094. }
  54095. else {
  54096. return;
  54097. }
  54098. this._epsilon = epsilon;
  54099. this._scene = scene;
  54100. this._scene.spriteManagers.push(this);
  54101. var indices = [];
  54102. var index = 0;
  54103. for (var count = 0; count < capacity; count++) {
  54104. indices.push(index);
  54105. indices.push(index + 1);
  54106. indices.push(index + 2);
  54107. indices.push(index);
  54108. indices.push(index + 2);
  54109. indices.push(index + 3);
  54110. index += 4;
  54111. }
  54112. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54113. // VBO
  54114. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54115. this._vertexData = new Float32Array(capacity * 16 * 4);
  54116. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54117. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54118. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54119. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54120. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54121. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54122. this._vertexBuffers["options"] = options;
  54123. this._vertexBuffers["cellInfo"] = cellInfo;
  54124. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54125. // Effects
  54126. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54127. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54128. }
  54129. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54130. set: function (callback) {
  54131. if (this._onDisposeObserver) {
  54132. this.onDisposeObservable.remove(this._onDisposeObserver);
  54133. }
  54134. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54135. },
  54136. enumerable: true,
  54137. configurable: true
  54138. });
  54139. Object.defineProperty(SpriteManager.prototype, "texture", {
  54140. get: function () {
  54141. return this._spriteTexture;
  54142. },
  54143. set: function (value) {
  54144. this._spriteTexture = value;
  54145. },
  54146. enumerable: true,
  54147. configurable: true
  54148. });
  54149. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54150. var arrayOffset = index * 16;
  54151. if (offsetX === 0)
  54152. offsetX = this._epsilon;
  54153. else if (offsetX === 1)
  54154. offsetX = 1 - this._epsilon;
  54155. if (offsetY === 0)
  54156. offsetY = this._epsilon;
  54157. else if (offsetY === 1)
  54158. offsetY = 1 - this._epsilon;
  54159. this._vertexData[arrayOffset] = sprite.position.x;
  54160. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54161. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54162. this._vertexData[arrayOffset + 3] = sprite.angle;
  54163. this._vertexData[arrayOffset + 4] = sprite.width;
  54164. this._vertexData[arrayOffset + 5] = sprite.height;
  54165. this._vertexData[arrayOffset + 6] = offsetX;
  54166. this._vertexData[arrayOffset + 7] = offsetY;
  54167. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54168. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54169. var offset = (sprite.cellIndex / rowSize) >> 0;
  54170. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54171. this._vertexData[arrayOffset + 11] = offset;
  54172. // Color
  54173. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54174. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54175. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54176. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54177. };
  54178. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54179. var count = Math.min(this._capacity, this.sprites.length);
  54180. var min = BABYLON.Vector3.Zero();
  54181. var max = BABYLON.Vector3.Zero();
  54182. var distance = Number.MAX_VALUE;
  54183. var currentSprite = null;
  54184. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54185. var cameraView = camera.getViewMatrix();
  54186. for (var index = 0; index < count; index++) {
  54187. var sprite = this.sprites[index];
  54188. if (!sprite) {
  54189. continue;
  54190. }
  54191. if (predicate) {
  54192. if (!predicate(sprite)) {
  54193. continue;
  54194. }
  54195. }
  54196. else if (!sprite.isPickable) {
  54197. continue;
  54198. }
  54199. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54200. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54201. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54202. if (ray.intersectsBoxMinMax(min, max)) {
  54203. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54204. if (distance > currentDistance) {
  54205. distance = currentDistance;
  54206. currentSprite = sprite;
  54207. if (fastCheck) {
  54208. break;
  54209. }
  54210. }
  54211. }
  54212. }
  54213. if (currentSprite) {
  54214. var result = new BABYLON.PickingInfo();
  54215. result.hit = true;
  54216. result.pickedSprite = currentSprite;
  54217. result.distance = distance;
  54218. return result;
  54219. }
  54220. return null;
  54221. };
  54222. SpriteManager.prototype.render = function () {
  54223. // Check
  54224. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54225. return;
  54226. var engine = this._scene.getEngine();
  54227. var baseSize = this._spriteTexture.getBaseSize();
  54228. // Sprites
  54229. var deltaTime = engine.getDeltaTime();
  54230. var max = Math.min(this._capacity, this.sprites.length);
  54231. var rowSize = baseSize.width / this.cellWidth;
  54232. var offset = 0;
  54233. for (var index = 0; index < max; index++) {
  54234. var sprite = this.sprites[index];
  54235. if (!sprite) {
  54236. continue;
  54237. }
  54238. sprite._animate(deltaTime);
  54239. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54240. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54241. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54242. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54243. }
  54244. this._buffer.update(this._vertexData);
  54245. // Render
  54246. var effect = this._effectBase;
  54247. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54248. effect = this._effectFog;
  54249. }
  54250. engine.enableEffect(effect);
  54251. var viewMatrix = this._scene.getViewMatrix();
  54252. effect.setTexture("diffuseSampler", this._spriteTexture);
  54253. effect.setMatrix("view", viewMatrix);
  54254. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54255. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54256. // Fog
  54257. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54258. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54259. effect.setColor3("vFogColor", this._scene.fogColor);
  54260. }
  54261. // VBOs
  54262. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54263. // Draw order
  54264. engine.setDepthFunctionToLessOrEqual();
  54265. effect.setBool("alphaTest", true);
  54266. engine.setColorWrite(false);
  54267. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54268. engine.setColorWrite(true);
  54269. effect.setBool("alphaTest", false);
  54270. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54271. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54272. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54273. };
  54274. SpriteManager.prototype.dispose = function () {
  54275. if (this._buffer) {
  54276. this._buffer.dispose();
  54277. this._buffer = null;
  54278. }
  54279. if (this._indexBuffer) {
  54280. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54281. this._indexBuffer = null;
  54282. }
  54283. if (this._spriteTexture) {
  54284. this._spriteTexture.dispose();
  54285. this._spriteTexture = null;
  54286. }
  54287. // Remove from scene
  54288. var index = this._scene.spriteManagers.indexOf(this);
  54289. this._scene.spriteManagers.splice(index, 1);
  54290. // Callback
  54291. this.onDisposeObservable.notifyObservers(this);
  54292. this.onDisposeObservable.clear();
  54293. };
  54294. return SpriteManager;
  54295. }());
  54296. BABYLON.SpriteManager = SpriteManager;
  54297. })(BABYLON || (BABYLON = {}));
  54298. //# sourceMappingURL=babylon.spriteManager.js.map
  54299. var BABYLON;
  54300. (function (BABYLON) {
  54301. var Sprite = /** @class */ (function () {
  54302. function Sprite(name, manager) {
  54303. this.name = name;
  54304. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54305. this.width = 1.0;
  54306. this.height = 1.0;
  54307. this.angle = 0;
  54308. this.cellIndex = 0;
  54309. this.invertU = 0;
  54310. this.invertV = 0;
  54311. this.animations = new Array();
  54312. this.isPickable = false;
  54313. this._animationStarted = false;
  54314. this._loopAnimation = false;
  54315. this._fromIndex = 0;
  54316. this._toIndex = 0;
  54317. this._delay = 0;
  54318. this._direction = 1;
  54319. this._time = 0;
  54320. this._manager = manager;
  54321. this._manager.sprites.push(this);
  54322. this.position = BABYLON.Vector3.Zero();
  54323. }
  54324. Object.defineProperty(Sprite.prototype, "size", {
  54325. get: function () {
  54326. return this.width;
  54327. },
  54328. set: function (value) {
  54329. this.width = value;
  54330. this.height = value;
  54331. },
  54332. enumerable: true,
  54333. configurable: true
  54334. });
  54335. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54336. this._fromIndex = from;
  54337. this._toIndex = to;
  54338. this._loopAnimation = loop;
  54339. this._delay = delay;
  54340. this._animationStarted = true;
  54341. this._direction = from < to ? 1 : -1;
  54342. this.cellIndex = from;
  54343. this._time = 0;
  54344. this._onAnimationEnd = onAnimationEnd;
  54345. };
  54346. Sprite.prototype.stopAnimation = function () {
  54347. this._animationStarted = false;
  54348. };
  54349. Sprite.prototype._animate = function (deltaTime) {
  54350. if (!this._animationStarted)
  54351. return;
  54352. this._time += deltaTime;
  54353. if (this._time > this._delay) {
  54354. this._time = this._time % this._delay;
  54355. this.cellIndex += this._direction;
  54356. if (this.cellIndex > this._toIndex) {
  54357. if (this._loopAnimation) {
  54358. this.cellIndex = this._fromIndex;
  54359. }
  54360. else {
  54361. this.cellIndex = this._toIndex;
  54362. this._animationStarted = false;
  54363. if (this._onAnimationEnd) {
  54364. this._onAnimationEnd();
  54365. }
  54366. if (this.disposeWhenFinishedAnimating) {
  54367. this.dispose();
  54368. }
  54369. }
  54370. }
  54371. }
  54372. };
  54373. Sprite.prototype.dispose = function () {
  54374. for (var i = 0; i < this._manager.sprites.length; i++) {
  54375. if (this._manager.sprites[i] == this) {
  54376. this._manager.sprites.splice(i, 1);
  54377. }
  54378. }
  54379. };
  54380. return Sprite;
  54381. }());
  54382. BABYLON.Sprite = Sprite;
  54383. })(BABYLON || (BABYLON = {}));
  54384. //# sourceMappingURL=babylon.sprite.js.map
  54385. var BABYLON;
  54386. (function (BABYLON) {
  54387. var IntersectionInfo = /** @class */ (function () {
  54388. function IntersectionInfo(bu, bv, distance) {
  54389. this.bu = bu;
  54390. this.bv = bv;
  54391. this.distance = distance;
  54392. this.faceId = 0;
  54393. this.subMeshId = 0;
  54394. }
  54395. return IntersectionInfo;
  54396. }());
  54397. BABYLON.IntersectionInfo = IntersectionInfo;
  54398. var PickingInfo = /** @class */ (function () {
  54399. function PickingInfo() {
  54400. this.hit = false;
  54401. this.distance = 0;
  54402. this.pickedPoint = null;
  54403. this.pickedMesh = null;
  54404. this.bu = 0;
  54405. this.bv = 0;
  54406. this.faceId = -1;
  54407. this.subMeshId = 0;
  54408. this.pickedSprite = null;
  54409. }
  54410. // Methods
  54411. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54412. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54413. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54414. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54415. return null;
  54416. }
  54417. var indices = this.pickedMesh.getIndices();
  54418. if (!indices) {
  54419. return null;
  54420. }
  54421. var result;
  54422. if (useVerticesNormals) {
  54423. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54424. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54425. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54426. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54427. normal0 = normal0.scale(this.bu);
  54428. normal1 = normal1.scale(this.bv);
  54429. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54430. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54431. }
  54432. else {
  54433. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54434. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54435. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54436. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54437. var p1p2 = vertex1.subtract(vertex2);
  54438. var p3p2 = vertex3.subtract(vertex2);
  54439. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54440. }
  54441. if (useWorldCoordinates) {
  54442. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54443. }
  54444. return BABYLON.Vector3.Normalize(result);
  54445. };
  54446. PickingInfo.prototype.getTextureCoordinates = function () {
  54447. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54448. return null;
  54449. }
  54450. var indices = this.pickedMesh.getIndices();
  54451. if (!indices) {
  54452. return null;
  54453. }
  54454. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54455. if (!uvs) {
  54456. return null;
  54457. }
  54458. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54459. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54460. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54461. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54462. uv1 = uv1.scale(this.bu);
  54463. uv2 = uv2.scale(this.bv);
  54464. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54465. };
  54466. return PickingInfo;
  54467. }());
  54468. BABYLON.PickingInfo = PickingInfo;
  54469. })(BABYLON || (BABYLON = {}));
  54470. //# sourceMappingURL=babylon.pickingInfo.js.map
  54471. var BABYLON;
  54472. (function (BABYLON) {
  54473. var Ray = /** @class */ (function () {
  54474. function Ray(origin, direction, length) {
  54475. if (length === void 0) { length = Number.MAX_VALUE; }
  54476. this.origin = origin;
  54477. this.direction = direction;
  54478. this.length = length;
  54479. }
  54480. // Methods
  54481. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54482. var d = 0.0;
  54483. var maxValue = Number.MAX_VALUE;
  54484. var inv;
  54485. var min;
  54486. var max;
  54487. var temp;
  54488. if (Math.abs(this.direction.x) < 0.0000001) {
  54489. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54490. return false;
  54491. }
  54492. }
  54493. else {
  54494. inv = 1.0 / this.direction.x;
  54495. min = (minimum.x - this.origin.x) * inv;
  54496. max = (maximum.x - this.origin.x) * inv;
  54497. if (max === -Infinity) {
  54498. max = Infinity;
  54499. }
  54500. if (min > max) {
  54501. temp = min;
  54502. min = max;
  54503. max = temp;
  54504. }
  54505. d = Math.max(min, d);
  54506. maxValue = Math.min(max, maxValue);
  54507. if (d > maxValue) {
  54508. return false;
  54509. }
  54510. }
  54511. if (Math.abs(this.direction.y) < 0.0000001) {
  54512. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54513. return false;
  54514. }
  54515. }
  54516. else {
  54517. inv = 1.0 / this.direction.y;
  54518. min = (minimum.y - this.origin.y) * inv;
  54519. max = (maximum.y - this.origin.y) * inv;
  54520. if (max === -Infinity) {
  54521. max = Infinity;
  54522. }
  54523. if (min > max) {
  54524. temp = min;
  54525. min = max;
  54526. max = temp;
  54527. }
  54528. d = Math.max(min, d);
  54529. maxValue = Math.min(max, maxValue);
  54530. if (d > maxValue) {
  54531. return false;
  54532. }
  54533. }
  54534. if (Math.abs(this.direction.z) < 0.0000001) {
  54535. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54536. return false;
  54537. }
  54538. }
  54539. else {
  54540. inv = 1.0 / this.direction.z;
  54541. min = (minimum.z - this.origin.z) * inv;
  54542. max = (maximum.z - this.origin.z) * inv;
  54543. if (max === -Infinity) {
  54544. max = Infinity;
  54545. }
  54546. if (min > max) {
  54547. temp = min;
  54548. min = max;
  54549. max = temp;
  54550. }
  54551. d = Math.max(min, d);
  54552. maxValue = Math.min(max, maxValue);
  54553. if (d > maxValue) {
  54554. return false;
  54555. }
  54556. }
  54557. return true;
  54558. };
  54559. Ray.prototype.intersectsBox = function (box) {
  54560. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54561. };
  54562. Ray.prototype.intersectsSphere = function (sphere) {
  54563. var x = sphere.center.x - this.origin.x;
  54564. var y = sphere.center.y - this.origin.y;
  54565. var z = sphere.center.z - this.origin.z;
  54566. var pyth = (x * x) + (y * y) + (z * z);
  54567. var rr = sphere.radius * sphere.radius;
  54568. if (pyth <= rr) {
  54569. return true;
  54570. }
  54571. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54572. if (dot < 0.0) {
  54573. return false;
  54574. }
  54575. var temp = pyth - (dot * dot);
  54576. return temp <= rr;
  54577. };
  54578. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54579. if (!this._edge1) {
  54580. this._edge1 = BABYLON.Vector3.Zero();
  54581. this._edge2 = BABYLON.Vector3.Zero();
  54582. this._pvec = BABYLON.Vector3.Zero();
  54583. this._tvec = BABYLON.Vector3.Zero();
  54584. this._qvec = BABYLON.Vector3.Zero();
  54585. }
  54586. vertex1.subtractToRef(vertex0, this._edge1);
  54587. vertex2.subtractToRef(vertex0, this._edge2);
  54588. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54589. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54590. if (det === 0) {
  54591. return null;
  54592. }
  54593. var invdet = 1 / det;
  54594. this.origin.subtractToRef(vertex0, this._tvec);
  54595. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54596. if (bu < 0 || bu > 1.0) {
  54597. return null;
  54598. }
  54599. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54600. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54601. if (bv < 0 || bu + bv > 1.0) {
  54602. return null;
  54603. }
  54604. //check if the distance is longer than the predefined length.
  54605. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54606. if (distance > this.length) {
  54607. return null;
  54608. }
  54609. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54610. };
  54611. Ray.prototype.intersectsPlane = function (plane) {
  54612. var distance;
  54613. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54614. if (Math.abs(result1) < 9.99999997475243E-07) {
  54615. return null;
  54616. }
  54617. else {
  54618. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54619. distance = (-plane.d - result2) / result1;
  54620. if (distance < 0.0) {
  54621. if (distance < -9.99999997475243E-07) {
  54622. return null;
  54623. }
  54624. else {
  54625. return 0;
  54626. }
  54627. }
  54628. return distance;
  54629. }
  54630. };
  54631. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54632. var tm = BABYLON.Tmp.Matrix[0];
  54633. mesh.getWorldMatrix().invertToRef(tm);
  54634. if (this._tmpRay) {
  54635. Ray.TransformToRef(this, tm, this._tmpRay);
  54636. }
  54637. else {
  54638. this._tmpRay = Ray.Transform(this, tm);
  54639. }
  54640. return mesh.intersects(this._tmpRay, fastCheck);
  54641. };
  54642. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54643. if (results) {
  54644. results.length = 0;
  54645. }
  54646. else {
  54647. results = [];
  54648. }
  54649. for (var i = 0; i < meshes.length; i++) {
  54650. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54651. if (pickInfo.hit) {
  54652. results.push(pickInfo);
  54653. }
  54654. }
  54655. results.sort(this._comparePickingInfo);
  54656. return results;
  54657. };
  54658. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54659. if (pickingInfoA.distance < pickingInfoB.distance) {
  54660. return -1;
  54661. }
  54662. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54663. return 1;
  54664. }
  54665. else {
  54666. return 0;
  54667. }
  54668. };
  54669. /**
  54670. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54671. * @param sega the first point of the segment to test the intersection against
  54672. * @param segb the second point of the segment to test the intersection against
  54673. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54674. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54675. */
  54676. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54677. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54678. var u = segb.subtract(sega);
  54679. var v = rsegb.subtract(this.origin);
  54680. var w = sega.subtract(this.origin);
  54681. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54682. var b = BABYLON.Vector3.Dot(u, v);
  54683. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54684. var d = BABYLON.Vector3.Dot(u, w);
  54685. var e = BABYLON.Vector3.Dot(v, w);
  54686. var D = a * c - b * b; // always >= 0
  54687. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54688. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54689. // compute the line parameters of the two closest points
  54690. if (D < Ray.smallnum) { // the lines are almost parallel
  54691. sN = 0.0; // force using point P0 on segment S1
  54692. sD = 1.0; // to prevent possible division by 0.0 later
  54693. tN = e;
  54694. tD = c;
  54695. }
  54696. else { // get the closest points on the infinite lines
  54697. sN = (b * e - c * d);
  54698. tN = (a * e - b * d);
  54699. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54700. sN = 0.0;
  54701. tN = e;
  54702. tD = c;
  54703. }
  54704. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54705. sN = sD;
  54706. tN = e + b;
  54707. tD = c;
  54708. }
  54709. }
  54710. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54711. tN = 0.0;
  54712. // recompute sc for this edge
  54713. if (-d < 0.0) {
  54714. sN = 0.0;
  54715. }
  54716. else if (-d > a)
  54717. sN = sD;
  54718. else {
  54719. sN = -d;
  54720. sD = a;
  54721. }
  54722. }
  54723. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54724. tN = tD;
  54725. // recompute sc for this edge
  54726. if ((-d + b) < 0.0) {
  54727. sN = 0;
  54728. }
  54729. else if ((-d + b) > a) {
  54730. sN = sD;
  54731. }
  54732. else {
  54733. sN = (-d + b);
  54734. sD = a;
  54735. }
  54736. }
  54737. // finally do the division to get sc and tc
  54738. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54739. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54740. // get the difference of the two closest points
  54741. var qtc = v.multiplyByFloats(tc, tc, tc);
  54742. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54743. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54744. if (isIntersected) {
  54745. return qtc.length();
  54746. }
  54747. return -1;
  54748. };
  54749. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54750. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54751. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54752. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54753. this.direction.normalize();
  54754. return this;
  54755. };
  54756. // Statics
  54757. Ray.Zero = function () {
  54758. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54759. };
  54760. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54761. var result = Ray.Zero();
  54762. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54763. };
  54764. /**
  54765. * 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
  54766. * transformed to the given world matrix.
  54767. * @param origin The origin point
  54768. * @param end The end point
  54769. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54770. */
  54771. Ray.CreateNewFromTo = function (origin, end, world) {
  54772. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54773. var direction = end.subtract(origin);
  54774. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54775. direction.normalize();
  54776. return Ray.Transform(new Ray(origin, direction, length), world);
  54777. };
  54778. Ray.Transform = function (ray, matrix) {
  54779. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54780. Ray.TransformToRef(ray, matrix, result);
  54781. return result;
  54782. };
  54783. Ray.TransformToRef = function (ray, matrix, result) {
  54784. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54785. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54786. result.length = ray.length;
  54787. var dir = result.direction;
  54788. var len = dir.length();
  54789. if (!(len === 0 || len === 1)) {
  54790. var num = 1.0 / len;
  54791. dir.x *= num;
  54792. dir.y *= num;
  54793. dir.z *= num;
  54794. result.length *= len;
  54795. }
  54796. };
  54797. Ray.smallnum = 0.00000001;
  54798. Ray.rayl = 10e8;
  54799. return Ray;
  54800. }());
  54801. BABYLON.Ray = Ray;
  54802. })(BABYLON || (BABYLON = {}));
  54803. //# sourceMappingURL=babylon.ray.js.map
  54804. var BABYLON;
  54805. (function (BABYLON) {
  54806. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54807. if (boxMin.x > sphereCenter.x + sphereRadius)
  54808. return false;
  54809. if (sphereCenter.x - sphereRadius > boxMax.x)
  54810. return false;
  54811. if (boxMin.y > sphereCenter.y + sphereRadius)
  54812. return false;
  54813. if (sphereCenter.y - sphereRadius > boxMax.y)
  54814. return false;
  54815. if (boxMin.z > sphereCenter.z + sphereRadius)
  54816. return false;
  54817. if (sphereCenter.z - sphereRadius > boxMax.z)
  54818. return false;
  54819. return true;
  54820. };
  54821. var getLowestRoot = (function () {
  54822. var result = { root: 0, found: false };
  54823. return function (a, b, c, maxR) {
  54824. result.root = 0;
  54825. result.found = false;
  54826. var determinant = b * b - 4.0 * a * c;
  54827. if (determinant < 0)
  54828. return result;
  54829. var sqrtD = Math.sqrt(determinant);
  54830. var r1 = (-b - sqrtD) / (2.0 * a);
  54831. var r2 = (-b + sqrtD) / (2.0 * a);
  54832. if (r1 > r2) {
  54833. var temp = r2;
  54834. r2 = r1;
  54835. r1 = temp;
  54836. }
  54837. if (r1 > 0 && r1 < maxR) {
  54838. result.root = r1;
  54839. result.found = true;
  54840. return result;
  54841. }
  54842. if (r2 > 0 && r2 < maxR) {
  54843. result.root = r2;
  54844. result.found = true;
  54845. return result;
  54846. }
  54847. return result;
  54848. };
  54849. })();
  54850. var Collider = /** @class */ (function () {
  54851. function Collider() {
  54852. this._collisionPoint = BABYLON.Vector3.Zero();
  54853. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54854. this._tempVector = BABYLON.Vector3.Zero();
  54855. this._tempVector2 = BABYLON.Vector3.Zero();
  54856. this._tempVector3 = BABYLON.Vector3.Zero();
  54857. this._tempVector4 = BABYLON.Vector3.Zero();
  54858. this._edge = BABYLON.Vector3.Zero();
  54859. this._baseToVertex = BABYLON.Vector3.Zero();
  54860. this._destinationPoint = BABYLON.Vector3.Zero();
  54861. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54862. this._displacementVector = BABYLON.Vector3.Zero();
  54863. this._radius = BABYLON.Vector3.One();
  54864. this._retry = 0;
  54865. this._basePointWorld = BABYLON.Vector3.Zero();
  54866. this._velocityWorld = BABYLON.Vector3.Zero();
  54867. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54868. this._collisionMask = -1;
  54869. }
  54870. Object.defineProperty(Collider.prototype, "collisionMask", {
  54871. get: function () {
  54872. return this._collisionMask;
  54873. },
  54874. set: function (mask) {
  54875. this._collisionMask = !isNaN(mask) ? mask : -1;
  54876. },
  54877. enumerable: true,
  54878. configurable: true
  54879. });
  54880. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54881. /**
  54882. * Gets the plane normal used to compute the sliding response (in local space)
  54883. */
  54884. get: function () {
  54885. return this._slidePlaneNormal;
  54886. },
  54887. enumerable: true,
  54888. configurable: true
  54889. });
  54890. // Methods
  54891. Collider.prototype._initialize = function (source, dir, e) {
  54892. this._velocity = dir;
  54893. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54894. this._basePoint = source;
  54895. source.multiplyToRef(this._radius, this._basePointWorld);
  54896. dir.multiplyToRef(this._radius, this._velocityWorld);
  54897. this._velocityWorldLength = this._velocityWorld.length();
  54898. this._epsilon = e;
  54899. this.collisionFound = false;
  54900. };
  54901. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54902. pa.subtractToRef(point, this._tempVector);
  54903. pb.subtractToRef(point, this._tempVector2);
  54904. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54905. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54906. if (d < 0)
  54907. return false;
  54908. pc.subtractToRef(point, this._tempVector3);
  54909. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54910. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54911. if (d < 0)
  54912. return false;
  54913. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54914. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54915. return d >= 0;
  54916. };
  54917. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54918. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54919. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54920. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54921. return false;
  54922. }
  54923. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54924. return false;
  54925. return true;
  54926. };
  54927. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54928. var t0;
  54929. var embeddedInPlane = false;
  54930. //defensive programming, actually not needed.
  54931. if (!trianglePlaneArray) {
  54932. trianglePlaneArray = [];
  54933. }
  54934. if (!trianglePlaneArray[faceIndex]) {
  54935. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54936. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54937. }
  54938. var trianglePlane = trianglePlaneArray[faceIndex];
  54939. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54940. return;
  54941. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54942. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54943. if (normalDotVelocity == 0) {
  54944. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54945. return;
  54946. embeddedInPlane = true;
  54947. t0 = 0;
  54948. }
  54949. else {
  54950. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54951. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54952. if (t0 > t1) {
  54953. var temp = t1;
  54954. t1 = t0;
  54955. t0 = temp;
  54956. }
  54957. if (t0 > 1.0 || t1 < 0.0)
  54958. return;
  54959. if (t0 < 0)
  54960. t0 = 0;
  54961. if (t0 > 1.0)
  54962. t0 = 1.0;
  54963. }
  54964. this._collisionPoint.copyFromFloats(0, 0, 0);
  54965. var found = false;
  54966. var t = 1.0;
  54967. if (!embeddedInPlane) {
  54968. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54969. this._velocity.scaleToRef(t0, this._tempVector);
  54970. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54971. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54972. found = true;
  54973. t = t0;
  54974. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54975. }
  54976. }
  54977. if (!found) {
  54978. var velocitySquaredLength = this._velocity.lengthSquared();
  54979. var a = velocitySquaredLength;
  54980. this._basePoint.subtractToRef(p1, this._tempVector);
  54981. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54982. var c = this._tempVector.lengthSquared() - 1.0;
  54983. var lowestRoot = getLowestRoot(a, b, c, t);
  54984. if (lowestRoot.found) {
  54985. t = lowestRoot.root;
  54986. found = true;
  54987. this._collisionPoint.copyFrom(p1);
  54988. }
  54989. this._basePoint.subtractToRef(p2, this._tempVector);
  54990. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54991. c = this._tempVector.lengthSquared() - 1.0;
  54992. lowestRoot = getLowestRoot(a, b, c, t);
  54993. if (lowestRoot.found) {
  54994. t = lowestRoot.root;
  54995. found = true;
  54996. this._collisionPoint.copyFrom(p2);
  54997. }
  54998. this._basePoint.subtractToRef(p3, this._tempVector);
  54999. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55000. c = this._tempVector.lengthSquared() - 1.0;
  55001. lowestRoot = getLowestRoot(a, b, c, t);
  55002. if (lowestRoot.found) {
  55003. t = lowestRoot.root;
  55004. found = true;
  55005. this._collisionPoint.copyFrom(p3);
  55006. }
  55007. p2.subtractToRef(p1, this._edge);
  55008. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55009. var edgeSquaredLength = this._edge.lengthSquared();
  55010. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55011. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55012. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55013. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55014. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55015. lowestRoot = getLowestRoot(a, b, c, t);
  55016. if (lowestRoot.found) {
  55017. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55018. if (f >= 0.0 && f <= 1.0) {
  55019. t = lowestRoot.root;
  55020. found = true;
  55021. this._edge.scaleInPlace(f);
  55022. p1.addToRef(this._edge, this._collisionPoint);
  55023. }
  55024. }
  55025. p3.subtractToRef(p2, this._edge);
  55026. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55027. edgeSquaredLength = this._edge.lengthSquared();
  55028. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55029. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55030. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55031. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55032. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55033. lowestRoot = getLowestRoot(a, b, c, t);
  55034. if (lowestRoot.found) {
  55035. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55036. if (f >= 0.0 && f <= 1.0) {
  55037. t = lowestRoot.root;
  55038. found = true;
  55039. this._edge.scaleInPlace(f);
  55040. p2.addToRef(this._edge, this._collisionPoint);
  55041. }
  55042. }
  55043. p1.subtractToRef(p3, this._edge);
  55044. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55045. edgeSquaredLength = this._edge.lengthSquared();
  55046. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55047. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55048. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55049. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55050. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55051. lowestRoot = getLowestRoot(a, b, c, t);
  55052. if (lowestRoot.found) {
  55053. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55054. if (f >= 0.0 && f <= 1.0) {
  55055. t = lowestRoot.root;
  55056. found = true;
  55057. this._edge.scaleInPlace(f);
  55058. p3.addToRef(this._edge, this._collisionPoint);
  55059. }
  55060. }
  55061. }
  55062. if (found) {
  55063. var distToCollision = t * this._velocity.length();
  55064. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55065. if (!this.intersectionPoint) {
  55066. this.intersectionPoint = this._collisionPoint.clone();
  55067. }
  55068. else {
  55069. this.intersectionPoint.copyFrom(this._collisionPoint);
  55070. }
  55071. this._nearestDistance = distToCollision;
  55072. this.collisionFound = true;
  55073. }
  55074. }
  55075. };
  55076. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55077. for (var i = indexStart; i < indexEnd; i += 3) {
  55078. var p1 = pts[indices[i] - decal];
  55079. var p2 = pts[indices[i + 1] - decal];
  55080. var p3 = pts[indices[i + 2] - decal];
  55081. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55082. }
  55083. };
  55084. Collider.prototype._getResponse = function (pos, vel) {
  55085. pos.addToRef(vel, this._destinationPoint);
  55086. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55087. this._basePoint.addToRef(vel, pos);
  55088. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55089. this._slidePlaneNormal.normalize();
  55090. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55091. pos.addInPlace(this._displacementVector);
  55092. this.intersectionPoint.addInPlace(this._displacementVector);
  55093. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55094. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55095. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55096. };
  55097. return Collider;
  55098. }());
  55099. BABYLON.Collider = Collider;
  55100. })(BABYLON || (BABYLON = {}));
  55101. //# sourceMappingURL=babylon.collider.js.map
  55102. var BABYLON;
  55103. (function (BABYLON) {
  55104. //WebWorker code will be inserted to this variable.
  55105. BABYLON.CollisionWorker = "";
  55106. /** Defines supported task for worker process */
  55107. var WorkerTaskType;
  55108. (function (WorkerTaskType) {
  55109. /** Initialization */
  55110. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55111. /** Update of geometry */
  55112. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55113. /** Evaluate collision */
  55114. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55115. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55116. /** Defines kind of replies returned by worker */
  55117. var WorkerReplyType;
  55118. (function (WorkerReplyType) {
  55119. /** Success */
  55120. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55121. /** Unkown error */
  55122. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55123. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55124. var CollisionCoordinatorWorker = /** @class */ (function () {
  55125. function CollisionCoordinatorWorker() {
  55126. var _this = this;
  55127. this._scaledPosition = BABYLON.Vector3.Zero();
  55128. this._scaledVelocity = BABYLON.Vector3.Zero();
  55129. this.onMeshUpdated = function (transformNode) {
  55130. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55131. };
  55132. this.onGeometryUpdated = function (geometry) {
  55133. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55134. };
  55135. this._afterRender = function () {
  55136. if (!_this._init)
  55137. return;
  55138. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55139. return;
  55140. }
  55141. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55142. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55143. if (_this._runningUpdated > 4) {
  55144. return;
  55145. }
  55146. ++_this._runningUpdated;
  55147. var payload = {
  55148. updatedMeshes: _this._addUpdateMeshesList,
  55149. updatedGeometries: _this._addUpdateGeometriesList,
  55150. removedGeometries: _this._toRemoveGeometryArray,
  55151. removedMeshes: _this._toRemoveMeshesArray
  55152. };
  55153. var message = {
  55154. payload: payload,
  55155. taskType: WorkerTaskType.UPDATE
  55156. };
  55157. var serializable = [];
  55158. for (var id in payload.updatedGeometries) {
  55159. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55160. //prepare transferables
  55161. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55162. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55163. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55164. }
  55165. }
  55166. _this._worker.postMessage(message, serializable);
  55167. _this._addUpdateMeshesList = {};
  55168. _this._addUpdateGeometriesList = {};
  55169. _this._toRemoveGeometryArray = [];
  55170. _this._toRemoveMeshesArray = [];
  55171. };
  55172. this._onMessageFromWorker = function (e) {
  55173. var returnData = e.data;
  55174. if (returnData.error != WorkerReplyType.SUCCESS) {
  55175. //TODO what errors can be returned from the worker?
  55176. BABYLON.Tools.Warn("error returned from worker!");
  55177. return;
  55178. }
  55179. switch (returnData.taskType) {
  55180. case WorkerTaskType.INIT:
  55181. _this._init = true;
  55182. //Update the worked with ALL of the scene's current state
  55183. _this._scene.meshes.forEach(function (mesh) {
  55184. _this.onMeshAdded(mesh);
  55185. });
  55186. _this._scene.getGeometries().forEach(function (geometry) {
  55187. _this.onGeometryAdded(geometry);
  55188. });
  55189. break;
  55190. case WorkerTaskType.UPDATE:
  55191. _this._runningUpdated--;
  55192. break;
  55193. case WorkerTaskType.COLLIDE:
  55194. var returnPayload = returnData.payload;
  55195. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55196. return;
  55197. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55198. if (callback) {
  55199. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55200. if (mesh) {
  55201. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55202. }
  55203. }
  55204. //cleanup
  55205. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55206. break;
  55207. }
  55208. };
  55209. this._collisionsCallbackArray = [];
  55210. this._init = false;
  55211. this._runningUpdated = 0;
  55212. this._addUpdateMeshesList = {};
  55213. this._addUpdateGeometriesList = {};
  55214. this._toRemoveGeometryArray = [];
  55215. this._toRemoveMeshesArray = [];
  55216. }
  55217. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55218. if (!this._init)
  55219. return;
  55220. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55221. return;
  55222. position.divideToRef(collider._radius, this._scaledPosition);
  55223. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55224. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55225. var payload = {
  55226. collider: {
  55227. position: this._scaledPosition.asArray(),
  55228. velocity: this._scaledVelocity.asArray(),
  55229. radius: collider._radius.asArray()
  55230. },
  55231. collisionId: collisionIndex,
  55232. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55233. maximumRetry: maximumRetry
  55234. };
  55235. var message = {
  55236. payload: payload,
  55237. taskType: WorkerTaskType.COLLIDE
  55238. };
  55239. this._worker.postMessage(message);
  55240. };
  55241. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55242. this._scene = scene;
  55243. this._scene.registerAfterRender(this._afterRender);
  55244. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55245. this._worker = new Worker(workerUrl);
  55246. this._worker.onmessage = this._onMessageFromWorker;
  55247. var message = {
  55248. payload: {},
  55249. taskType: WorkerTaskType.INIT
  55250. };
  55251. this._worker.postMessage(message);
  55252. };
  55253. CollisionCoordinatorWorker.prototype.destroy = function () {
  55254. this._scene.unregisterAfterRender(this._afterRender);
  55255. this._worker.terminate();
  55256. };
  55257. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55258. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55259. this.onMeshUpdated(mesh);
  55260. };
  55261. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55262. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55263. };
  55264. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55265. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55266. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55267. this.onGeometryUpdated(geometry);
  55268. };
  55269. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55270. this._toRemoveGeometryArray.push(geometry.id);
  55271. };
  55272. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55273. var submeshes = [];
  55274. if (mesh.subMeshes) {
  55275. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55276. var boundingInfo = sm.getBoundingInfo();
  55277. return {
  55278. position: idx,
  55279. verticesStart: sm.verticesStart,
  55280. verticesCount: sm.verticesCount,
  55281. indexStart: sm.indexStart,
  55282. indexCount: sm.indexCount,
  55283. hasMaterial: !!sm.getMaterial(),
  55284. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55285. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55286. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55287. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55288. };
  55289. });
  55290. }
  55291. var geometryId = null;
  55292. if (mesh instanceof BABYLON.Mesh) {
  55293. var geometry = mesh.geometry;
  55294. geometryId = geometry ? geometry.id : null;
  55295. }
  55296. else if (mesh instanceof BABYLON.InstancedMesh) {
  55297. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55298. geometryId = geometry ? geometry.id : null;
  55299. }
  55300. var boundingInfo = mesh.getBoundingInfo();
  55301. return {
  55302. uniqueId: mesh.uniqueId,
  55303. id: mesh.id,
  55304. name: mesh.name,
  55305. geometryId: geometryId,
  55306. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55307. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55308. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55309. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55310. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55311. subMeshes: submeshes,
  55312. checkCollisions: mesh.checkCollisions
  55313. };
  55314. };
  55315. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55316. return {
  55317. id: geometry.id,
  55318. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55319. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55320. indices: new Uint32Array(geometry.getIndices() || []),
  55321. };
  55322. };
  55323. return CollisionCoordinatorWorker;
  55324. }());
  55325. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55326. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55327. function CollisionCoordinatorLegacy() {
  55328. this._scaledPosition = BABYLON.Vector3.Zero();
  55329. this._scaledVelocity = BABYLON.Vector3.Zero();
  55330. this._finalPosition = BABYLON.Vector3.Zero();
  55331. }
  55332. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55333. position.divideToRef(collider._radius, this._scaledPosition);
  55334. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55335. collider.collidedMesh = null;
  55336. collider._retry = 0;
  55337. collider._initialVelocity = this._scaledVelocity;
  55338. collider._initialPosition = this._scaledPosition;
  55339. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55340. this._finalPosition.multiplyInPlace(collider._radius);
  55341. //run the callback
  55342. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55343. };
  55344. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55345. this._scene = scene;
  55346. };
  55347. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55348. //Legacy need no destruction method.
  55349. };
  55350. //No update in legacy mode
  55351. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55352. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55353. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55354. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55355. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55356. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55357. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55358. if (excludedMesh === void 0) { excludedMesh = null; }
  55359. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55360. if (collider._retry >= maximumRetry) {
  55361. finalPosition.copyFrom(position);
  55362. return;
  55363. }
  55364. // Check if this is a mesh else camera or -1
  55365. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55366. collider._initialize(position, velocity, closeDistance);
  55367. // Check all meshes
  55368. for (var index = 0; index < this._scene.meshes.length; index++) {
  55369. var mesh = this._scene.meshes[index];
  55370. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55371. mesh._checkCollision(collider);
  55372. }
  55373. }
  55374. if (!collider.collisionFound) {
  55375. position.addToRef(velocity, finalPosition);
  55376. return;
  55377. }
  55378. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55379. collider._getResponse(position, velocity);
  55380. }
  55381. if (velocity.length() <= closeDistance) {
  55382. finalPosition.copyFrom(position);
  55383. return;
  55384. }
  55385. collider._retry++;
  55386. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55387. };
  55388. return CollisionCoordinatorLegacy;
  55389. }());
  55390. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55391. })(BABYLON || (BABYLON = {}));
  55392. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55393. var BABYLON;
  55394. (function (BABYLON) {
  55395. /**
  55396. * A particle represents one of the element emitted by a particle system.
  55397. * This is mainly define by its coordinates, direction, velocity and age.
  55398. */
  55399. var Particle = /** @class */ (function () {
  55400. /**
  55401. * Creates a new instance Particle
  55402. * @param particleSystem the particle system the particle belongs to
  55403. */
  55404. function Particle(
  55405. /**
  55406. * particleSystem the particle system the particle belongs to.
  55407. */
  55408. particleSystem) {
  55409. this.particleSystem = particleSystem;
  55410. /**
  55411. * The world position of the particle in the scene.
  55412. */
  55413. this.position = BABYLON.Vector3.Zero();
  55414. /**
  55415. * The world direction of the particle in the scene.
  55416. */
  55417. this.direction = BABYLON.Vector3.Zero();
  55418. /**
  55419. * The color of the particle.
  55420. */
  55421. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55422. /**
  55423. * The color change of the particle per step.
  55424. */
  55425. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55426. /**
  55427. * Defines how long will the life of the particle be.
  55428. */
  55429. this.lifeTime = 1.0;
  55430. /**
  55431. * The current age of the particle.
  55432. */
  55433. this.age = 0;
  55434. /**
  55435. * The current size of the particle.
  55436. */
  55437. this.size = 0;
  55438. /**
  55439. * The current angle of the particle.
  55440. */
  55441. this.angle = 0;
  55442. /**
  55443. * Defines how fast is the angle changing.
  55444. */
  55445. this.angularSpeed = 0;
  55446. /**
  55447. * Defines the cell index used by the particle to be rendered from a sprite.
  55448. */
  55449. this.cellIndex = 0;
  55450. this._currentFrameCounter = 0;
  55451. if (!this.particleSystem.isAnimationSheetEnabled) {
  55452. return;
  55453. }
  55454. this.updateCellInfoFromSystem();
  55455. }
  55456. Particle.prototype.updateCellInfoFromSystem = function () {
  55457. this.cellIndex = this.particleSystem.startSpriteCellID;
  55458. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55459. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55460. }
  55461. else {
  55462. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55463. }
  55464. };
  55465. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55466. // (ageOffset / scaledUpdateSpeed) / available cells
  55467. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55468. this._currentFrameCounter += scaledUpdateSpeed;
  55469. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55470. this._currentFrameCounter = 0;
  55471. this.cellIndex++;
  55472. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55473. this.cellIndex = this.particleSystem.endSpriteCellID;
  55474. }
  55475. }
  55476. };
  55477. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55478. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55479. this.cellIndex++;
  55480. this._currentFrameCounter = 0;
  55481. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55482. if (this.particleSystem.spriteCellLoop) {
  55483. this.cellIndex = this.particleSystem.startSpriteCellID;
  55484. }
  55485. else {
  55486. this.cellIndex = this.particleSystem.endSpriteCellID;
  55487. }
  55488. }
  55489. }
  55490. else {
  55491. this._currentFrameCounter++;
  55492. }
  55493. };
  55494. /**
  55495. * Copy the properties of particle to another one.
  55496. * @param other the particle to copy the information to.
  55497. */
  55498. Particle.prototype.copyTo = function (other) {
  55499. other.position.copyFrom(this.position);
  55500. other.direction.copyFrom(this.direction);
  55501. other.color.copyFrom(this.color);
  55502. other.colorStep.copyFrom(this.colorStep);
  55503. other.lifeTime = this.lifeTime;
  55504. other.age = this.age;
  55505. other.size = this.size;
  55506. other.angle = this.angle;
  55507. other.angularSpeed = this.angularSpeed;
  55508. other.particleSystem = this.particleSystem;
  55509. other.cellIndex = this.cellIndex;
  55510. };
  55511. return Particle;
  55512. }());
  55513. BABYLON.Particle = Particle;
  55514. })(BABYLON || (BABYLON = {}));
  55515. //# sourceMappingURL=babylon.particle.js.map
  55516. var BABYLON;
  55517. (function (BABYLON) {
  55518. /**
  55519. * This represents a particle system in Babylon.
  55520. * 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.
  55521. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55522. * @example https://doc.babylonjs.com/babylon101/particles
  55523. */
  55524. var ParticleSystem = /** @class */ (function () {
  55525. /**
  55526. * Instantiates a particle system.
  55527. * 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.
  55528. * @param name The name of the particle system
  55529. * @param capacity The max number of particles alive at the same time
  55530. * @param scene The scene the particle system belongs to
  55531. * @param customEffect a custom effect used to change the way particles are rendered by default
  55532. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55533. * @param epsilon Offset used to render the particles
  55534. */
  55535. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55536. if (customEffect === void 0) { customEffect = null; }
  55537. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55538. if (epsilon === void 0) { epsilon = 0.01; }
  55539. var _this = this;
  55540. /**
  55541. * List of animations used by the particle system.
  55542. */
  55543. this.animations = [];
  55544. /**
  55545. * The rendering group used by the Particle system to chose when to render.
  55546. */
  55547. this.renderingGroupId = 0;
  55548. /**
  55549. * The emitter represents the Mesh or position we are attaching the particle system to.
  55550. */
  55551. this.emitter = null;
  55552. /**
  55553. * The maximum number of particles to emit per frame
  55554. */
  55555. this.emitRate = 10;
  55556. /**
  55557. * If you want to launch only a few particles at once, that can be done, as well.
  55558. */
  55559. this.manualEmitCount = -1;
  55560. /**
  55561. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55562. */
  55563. this.updateSpeed = 0.01;
  55564. /**
  55565. * The amount of time the particle system is running (depends of the overall update speed).
  55566. */
  55567. this.targetStopDuration = 0;
  55568. /**
  55569. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55570. */
  55571. this.disposeOnStop = false;
  55572. /**
  55573. * Minimum power of emitting particles.
  55574. */
  55575. this.minEmitPower = 1;
  55576. /**
  55577. * Maximum power of emitting particles.
  55578. */
  55579. this.maxEmitPower = 1;
  55580. /**
  55581. * Minimum life time of emitting particles.
  55582. */
  55583. this.minLifeTime = 1;
  55584. /**
  55585. * Maximum life time of emitting particles.
  55586. */
  55587. this.maxLifeTime = 1;
  55588. /**
  55589. * Minimum Size of emitting particles.
  55590. */
  55591. this.minSize = 1;
  55592. /**
  55593. * Maximum Size of emitting particles.
  55594. */
  55595. this.maxSize = 1;
  55596. /**
  55597. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55598. */
  55599. this.minAngularSpeed = 0;
  55600. /**
  55601. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55602. */
  55603. this.maxAngularSpeed = 0;
  55604. /**
  55605. * The layer mask we are rendering the particles through.
  55606. */
  55607. this.layerMask = 0x0FFFFFFF;
  55608. /**
  55609. * This can help using your own shader to render the particle system.
  55610. * The according effect will be created
  55611. */
  55612. this.customShader = null;
  55613. /**
  55614. * By default particle system starts as soon as they are created. This prevents the
  55615. * automatic start to happen and let you decide when to start emitting particles.
  55616. */
  55617. this.preventAutoStart = false;
  55618. /**
  55619. * Callback triggered when the particle animation is ending.
  55620. */
  55621. this.onAnimationEnd = null;
  55622. /**
  55623. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55624. */
  55625. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55626. /**
  55627. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55628. * to override the particles.
  55629. */
  55630. this.forceDepthWrite = false;
  55631. /**
  55632. * You can use gravity if you want to give an orientation to your particles.
  55633. */
  55634. this.gravity = BABYLON.Vector3.Zero();
  55635. /**
  55636. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55637. */
  55638. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55639. /**
  55640. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55641. */
  55642. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55643. /**
  55644. * Color the particle will have at the end of its lifetime.
  55645. */
  55646. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55647. /**
  55648. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55649. */
  55650. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55651. /**
  55652. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55653. */
  55654. this.spriteCellLoop = true;
  55655. /**
  55656. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55657. */
  55658. this.spriteCellChangeSpeed = 0;
  55659. /**
  55660. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55661. */
  55662. this.startSpriteCellID = 0;
  55663. /**
  55664. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55665. */
  55666. this.endSpriteCellID = 0;
  55667. /**
  55668. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55669. */
  55670. this.spriteCellWidth = 0;
  55671. /**
  55672. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55673. */
  55674. this.spriteCellHeight = 0;
  55675. /**
  55676. * An event triggered when the system is disposed.
  55677. */
  55678. this.onDisposeObservable = new BABYLON.Observable();
  55679. this._particles = new Array();
  55680. this._stockParticles = new Array();
  55681. this._newPartsExcess = 0;
  55682. this._vertexBuffers = {};
  55683. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55684. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55685. this._scaledDirection = BABYLON.Vector3.Zero();
  55686. this._scaledGravity = BABYLON.Vector3.Zero();
  55687. this._currentRenderId = -1;
  55688. this._started = false;
  55689. this._stopped = false;
  55690. this._actualFrame = 0;
  55691. this._vertexBufferSize = 11;
  55692. // start of sub system methods
  55693. /**
  55694. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55695. * Its lifetime will start back at 0.
  55696. */
  55697. this.recycleParticle = function (particle) {
  55698. var lastParticle = _this._particles.pop();
  55699. if (lastParticle !== particle) {
  55700. lastParticle.copyTo(particle);
  55701. }
  55702. _this._stockParticles.push(lastParticle);
  55703. };
  55704. this._createParticle = function () {
  55705. var particle;
  55706. if (_this._stockParticles.length !== 0) {
  55707. particle = _this._stockParticles.pop();
  55708. particle.age = 0;
  55709. particle.cellIndex = _this.startSpriteCellID;
  55710. }
  55711. else {
  55712. particle = new BABYLON.Particle(_this);
  55713. }
  55714. return particle;
  55715. };
  55716. this._emitFromParticle = function (particle) {
  55717. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55718. return;
  55719. }
  55720. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55721. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55722. subSystem._rootParticleSystem = _this;
  55723. _this.activeSubSystems.push(subSystem);
  55724. subSystem.start();
  55725. };
  55726. this._appendParticleVertexes = null;
  55727. this.id = name;
  55728. this.name = name;
  55729. this._capacity = capacity;
  55730. this._epsilon = epsilon;
  55731. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55732. if (isAnimationSheetEnabled) {
  55733. this._vertexBufferSize = 12;
  55734. }
  55735. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55736. this._customEffect = customEffect;
  55737. scene.particleSystems.push(this);
  55738. this._createIndexBuffer();
  55739. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  55740. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55741. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55742. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55743. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55744. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  55745. if (this._isAnimationSheetEnabled) {
  55746. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  55747. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55748. }
  55749. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55750. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55751. this._vertexBuffers["options"] = options;
  55752. // Default emitter type
  55753. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55754. this.updateFunction = function (particles) {
  55755. for (var index = 0; index < particles.length; index++) {
  55756. var particle = particles[index];
  55757. particle.age += _this._scaledUpdateSpeed;
  55758. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55759. _this._emitFromParticle(particle);
  55760. _this.recycleParticle(particle);
  55761. index--;
  55762. continue;
  55763. }
  55764. else {
  55765. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55766. particle.color.addInPlace(_this._scaledColorStep);
  55767. if (particle.color.a < 0)
  55768. particle.color.a = 0;
  55769. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55770. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55771. particle.position.addInPlace(_this._scaledDirection);
  55772. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55773. particle.direction.addInPlace(_this._scaledGravity);
  55774. if (_this._isAnimationSheetEnabled) {
  55775. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55776. }
  55777. }
  55778. }
  55779. };
  55780. }
  55781. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55782. /**
  55783. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55784. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55785. */
  55786. get: function () {
  55787. if (this.particleEmitterType.direction1) {
  55788. return this.particleEmitterType.direction1;
  55789. }
  55790. return BABYLON.Vector3.Zero();
  55791. },
  55792. set: function (value) {
  55793. if (this.particleEmitterType.direction1) {
  55794. this.particleEmitterType.direction1 = value;
  55795. }
  55796. },
  55797. enumerable: true,
  55798. configurable: true
  55799. });
  55800. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55801. /**
  55802. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55803. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55804. */
  55805. get: function () {
  55806. if (this.particleEmitterType.direction2) {
  55807. return this.particleEmitterType.direction2;
  55808. }
  55809. return BABYLON.Vector3.Zero();
  55810. },
  55811. set: function (value) {
  55812. if (this.particleEmitterType.direction2) {
  55813. this.particleEmitterType.direction2 = value;
  55814. }
  55815. },
  55816. enumerable: true,
  55817. configurable: true
  55818. });
  55819. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55820. /**
  55821. * 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.
  55822. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55823. */
  55824. get: function () {
  55825. if (this.particleEmitterType.minEmitBox) {
  55826. return this.particleEmitterType.minEmitBox;
  55827. }
  55828. return BABYLON.Vector3.Zero();
  55829. },
  55830. set: function (value) {
  55831. if (this.particleEmitterType.minEmitBox) {
  55832. this.particleEmitterType.minEmitBox = value;
  55833. }
  55834. },
  55835. enumerable: true,
  55836. configurable: true
  55837. });
  55838. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55839. /**
  55840. * 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.
  55841. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55842. */
  55843. get: function () {
  55844. if (this.particleEmitterType.maxEmitBox) {
  55845. return this.particleEmitterType.maxEmitBox;
  55846. }
  55847. return BABYLON.Vector3.Zero();
  55848. },
  55849. set: function (value) {
  55850. if (this.particleEmitterType.maxEmitBox) {
  55851. this.particleEmitterType.maxEmitBox = value;
  55852. }
  55853. },
  55854. enumerable: true,
  55855. configurable: true
  55856. });
  55857. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55858. /**
  55859. * Sets a callback that will be triggered when the system is disposed.
  55860. */
  55861. set: function (callback) {
  55862. if (this._onDisposeObserver) {
  55863. this.onDisposeObservable.remove(this._onDisposeObserver);
  55864. }
  55865. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55866. },
  55867. enumerable: true,
  55868. configurable: true
  55869. });
  55870. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55871. /**
  55872. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  55873. */
  55874. get: function () {
  55875. return this._isAnimationSheetEnabled;
  55876. },
  55877. enumerable: true,
  55878. configurable: true
  55879. });
  55880. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55881. //end of Sub-emitter
  55882. /**
  55883. * Gets the current list of active particles
  55884. */
  55885. get: function () {
  55886. return this._particles;
  55887. },
  55888. enumerable: true,
  55889. configurable: true
  55890. });
  55891. /**
  55892. * Returns the string "ParticleSystem"
  55893. * @returns a string containing the class name
  55894. */
  55895. ParticleSystem.prototype.getClassName = function () {
  55896. return "ParticleSystem";
  55897. };
  55898. ParticleSystem.prototype._createIndexBuffer = function () {
  55899. var indices = [];
  55900. var index = 0;
  55901. for (var count = 0; count < this._capacity; count++) {
  55902. indices.push(index);
  55903. indices.push(index + 1);
  55904. indices.push(index + 2);
  55905. indices.push(index);
  55906. indices.push(index + 2);
  55907. indices.push(index + 3);
  55908. index += 4;
  55909. }
  55910. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55911. };
  55912. /**
  55913. * Gets the maximum number of particles active at the same time.
  55914. * @returns The max number of active particles.
  55915. */
  55916. ParticleSystem.prototype.getCapacity = function () {
  55917. return this._capacity;
  55918. };
  55919. /**
  55920. * Gets Wether there are still active particles in the system.
  55921. * @returns True if it is alive, otherwise false.
  55922. */
  55923. ParticleSystem.prototype.isAlive = function () {
  55924. return this._alive;
  55925. };
  55926. /**
  55927. * Gets Wether the system has been started.
  55928. * @returns True if it has been started, otherwise false.
  55929. */
  55930. ParticleSystem.prototype.isStarted = function () {
  55931. return this._started;
  55932. };
  55933. /**
  55934. * Starts the particle system and begins to emit.
  55935. */
  55936. ParticleSystem.prototype.start = function () {
  55937. this._started = true;
  55938. this._stopped = false;
  55939. this._actualFrame = 0;
  55940. if (this.subEmitters && this.subEmitters.length != 0) {
  55941. this.activeSubSystems = new Array();
  55942. }
  55943. };
  55944. /**
  55945. * Stops the particle system.
  55946. * @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.
  55947. */
  55948. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55949. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55950. this._stopped = true;
  55951. if (stopSubEmitters) {
  55952. this._stopSubEmitters();
  55953. }
  55954. };
  55955. // animation sheet
  55956. /**
  55957. * Remove all active particles
  55958. */
  55959. ParticleSystem.prototype.reset = function () {
  55960. this._stockParticles = [];
  55961. this._particles = [];
  55962. };
  55963. /**
  55964. * @hidden (for internal use only)
  55965. */
  55966. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55967. var offset = index * this._vertexBufferSize;
  55968. this._vertexData[offset] = particle.position.x;
  55969. this._vertexData[offset + 1] = particle.position.y;
  55970. this._vertexData[offset + 2] = particle.position.z;
  55971. this._vertexData[offset + 3] = particle.color.r;
  55972. this._vertexData[offset + 4] = particle.color.g;
  55973. this._vertexData[offset + 5] = particle.color.b;
  55974. this._vertexData[offset + 6] = particle.color.a;
  55975. this._vertexData[offset + 7] = particle.angle;
  55976. this._vertexData[offset + 8] = particle.size;
  55977. this._vertexData[offset + 9] = offsetX;
  55978. this._vertexData[offset + 10] = offsetY;
  55979. };
  55980. /**
  55981. * @hidden (for internal use only)
  55982. */
  55983. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  55984. if (offsetX === 0)
  55985. offsetX = this._epsilon;
  55986. else if (offsetX === 1)
  55987. offsetX = 1 - this._epsilon;
  55988. if (offsetY === 0)
  55989. offsetY = this._epsilon;
  55990. else if (offsetY === 1)
  55991. offsetY = 1 - this._epsilon;
  55992. var offset = index * this._vertexBufferSize;
  55993. this._vertexData[offset] = particle.position.x;
  55994. this._vertexData[offset + 1] = particle.position.y;
  55995. this._vertexData[offset + 2] = particle.position.z;
  55996. this._vertexData[offset + 3] = particle.color.r;
  55997. this._vertexData[offset + 4] = particle.color.g;
  55998. this._vertexData[offset + 5] = particle.color.b;
  55999. this._vertexData[offset + 6] = particle.color.a;
  56000. this._vertexData[offset + 7] = particle.angle;
  56001. this._vertexData[offset + 8] = particle.size;
  56002. this._vertexData[offset + 9] = offsetX;
  56003. this._vertexData[offset + 10] = offsetY;
  56004. this._vertexData[offset + 11] = particle.cellIndex;
  56005. };
  56006. ParticleSystem.prototype._stopSubEmitters = function () {
  56007. if (!this.activeSubSystems) {
  56008. return;
  56009. }
  56010. this.activeSubSystems.forEach(function (subSystem) {
  56011. subSystem.stop(true);
  56012. });
  56013. this.activeSubSystems = new Array();
  56014. };
  56015. ParticleSystem.prototype._removeFromRoot = function () {
  56016. if (!this._rootParticleSystem) {
  56017. return;
  56018. }
  56019. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56020. if (index !== -1) {
  56021. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56022. }
  56023. };
  56024. // end of sub system methods
  56025. ParticleSystem.prototype._update = function (newParticles) {
  56026. // Update current
  56027. this._alive = this._particles.length > 0;
  56028. this.updateFunction(this._particles);
  56029. // Add new ones
  56030. var worldMatrix;
  56031. if (this.emitter.position) {
  56032. var emitterMesh = this.emitter;
  56033. worldMatrix = emitterMesh.getWorldMatrix();
  56034. }
  56035. else {
  56036. var emitterPosition = this.emitter;
  56037. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56038. }
  56039. var particle;
  56040. for (var index = 0; index < newParticles; index++) {
  56041. if (this._particles.length === this._capacity) {
  56042. break;
  56043. }
  56044. particle = this._createParticle();
  56045. this._particles.push(particle);
  56046. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56047. if (this.startPositionFunction) {
  56048. this.startPositionFunction(worldMatrix, particle.position, particle);
  56049. }
  56050. else {
  56051. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56052. }
  56053. if (this.startDirectionFunction) {
  56054. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56055. }
  56056. else {
  56057. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56058. }
  56059. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56060. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56061. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56062. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56063. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56064. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56065. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56066. }
  56067. };
  56068. ParticleSystem.prototype._getEffect = function () {
  56069. if (this._customEffect) {
  56070. return this._customEffect;
  56071. }
  56072. ;
  56073. var defines = [];
  56074. if (this._scene.clipPlane) {
  56075. defines.push("#define CLIPPLANE");
  56076. }
  56077. if (this._isAnimationSheetEnabled) {
  56078. defines.push("#define ANIMATESHEET");
  56079. }
  56080. // Effect
  56081. var join = defines.join("\n");
  56082. if (this._cachedDefines !== join) {
  56083. this._cachedDefines = join;
  56084. var attributesNamesOrOptions;
  56085. var effectCreationOption;
  56086. if (this._isAnimationSheetEnabled) {
  56087. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56088. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56089. }
  56090. else {
  56091. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56092. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56093. }
  56094. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56095. }
  56096. return this._effect;
  56097. };
  56098. /**
  56099. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56100. */
  56101. ParticleSystem.prototype.animate = function () {
  56102. if (!this._started)
  56103. return;
  56104. var effect = this._getEffect();
  56105. // Check
  56106. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56107. return;
  56108. if (this._currentRenderId === this._scene.getRenderId()) {
  56109. return;
  56110. }
  56111. this._currentRenderId = this._scene.getRenderId();
  56112. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56113. // determine the number of particles we need to create
  56114. var newParticles;
  56115. if (this.manualEmitCount > -1) {
  56116. newParticles = this.manualEmitCount;
  56117. this._newPartsExcess = 0;
  56118. this.manualEmitCount = 0;
  56119. }
  56120. else {
  56121. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56122. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56123. }
  56124. if (this._newPartsExcess > 1.0) {
  56125. newParticles += this._newPartsExcess >> 0;
  56126. this._newPartsExcess -= this._newPartsExcess >> 0;
  56127. }
  56128. this._alive = false;
  56129. if (!this._stopped) {
  56130. this._actualFrame += this._scaledUpdateSpeed;
  56131. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56132. this.stop();
  56133. }
  56134. else {
  56135. newParticles = 0;
  56136. }
  56137. this._update(newParticles);
  56138. // Stopped?
  56139. if (this._stopped) {
  56140. if (!this._alive) {
  56141. this._started = false;
  56142. if (this.onAnimationEnd) {
  56143. this.onAnimationEnd();
  56144. }
  56145. if (this.disposeOnStop) {
  56146. this._scene._toBeDisposed.push(this);
  56147. }
  56148. }
  56149. }
  56150. // Animation sheet
  56151. if (this._isAnimationSheetEnabled) {
  56152. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56153. }
  56154. else {
  56155. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56156. }
  56157. // Update VBO
  56158. var offset = 0;
  56159. for (var index = 0; index < this._particles.length; index++) {
  56160. var particle = this._particles[index];
  56161. this._appendParticleVertexes(offset, particle);
  56162. offset += 4;
  56163. }
  56164. if (this._vertexBuffer) {
  56165. this._vertexBuffer.update(this._vertexData);
  56166. }
  56167. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56168. this.stop();
  56169. }
  56170. };
  56171. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56172. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56173. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56174. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56175. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56176. };
  56177. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56178. this._appendParticleVertex(offset++, particle, 0, 0);
  56179. this._appendParticleVertex(offset++, particle, 1, 0);
  56180. this._appendParticleVertex(offset++, particle, 1, 1);
  56181. this._appendParticleVertex(offset++, particle, 0, 1);
  56182. };
  56183. /**
  56184. * Rebuilds the particle system.
  56185. */
  56186. ParticleSystem.prototype.rebuild = function () {
  56187. this._createIndexBuffer();
  56188. if (this._vertexBuffer) {
  56189. this._vertexBuffer._rebuild();
  56190. }
  56191. };
  56192. /**
  56193. * Is this system ready to be used/rendered
  56194. * @return true if the system is ready
  56195. */
  56196. ParticleSystem.prototype.isReady = function () {
  56197. var effect = this._getEffect();
  56198. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56199. return false;
  56200. }
  56201. return true;
  56202. };
  56203. /**
  56204. * Renders the particle system in its current state.
  56205. * @returns the current number of particles
  56206. */
  56207. ParticleSystem.prototype.render = function () {
  56208. var effect = this._getEffect();
  56209. // Check
  56210. if (!this.isReady() || !this._particles.length) {
  56211. return 0;
  56212. }
  56213. var engine = this._scene.getEngine();
  56214. // Render
  56215. engine.enableEffect(effect);
  56216. engine.setState(false);
  56217. var viewMatrix = this._scene.getViewMatrix();
  56218. effect.setTexture("diffuseSampler", this.particleTexture);
  56219. effect.setMatrix("view", viewMatrix);
  56220. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56221. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56222. var baseSize = this.particleTexture.getBaseSize();
  56223. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56224. }
  56225. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56226. if (this._scene.clipPlane) {
  56227. var clipPlane = this._scene.clipPlane;
  56228. var invView = viewMatrix.clone();
  56229. invView.invert();
  56230. effect.setMatrix("invView", invView);
  56231. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56232. }
  56233. // VBOs
  56234. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56235. // Draw order
  56236. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56237. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56238. }
  56239. else {
  56240. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56241. }
  56242. if (this.forceDepthWrite) {
  56243. engine.setDepthWrite(true);
  56244. }
  56245. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56246. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56247. return this._particles.length;
  56248. };
  56249. /**
  56250. * Disposes the particle system and free the associated resources
  56251. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56252. */
  56253. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56254. if (disposeTexture === void 0) { disposeTexture = true; }
  56255. if (this._vertexBuffer) {
  56256. this._vertexBuffer.dispose();
  56257. this._vertexBuffer = null;
  56258. }
  56259. if (this._indexBuffer) {
  56260. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56261. this._indexBuffer = null;
  56262. }
  56263. if (disposeTexture && this.particleTexture) {
  56264. this.particleTexture.dispose();
  56265. this.particleTexture = null;
  56266. }
  56267. this._removeFromRoot();
  56268. // Remove from scene
  56269. var index = this._scene.particleSystems.indexOf(this);
  56270. if (index > -1) {
  56271. this._scene.particleSystems.splice(index, 1);
  56272. }
  56273. // Callback
  56274. this.onDisposeObservable.notifyObservers(this);
  56275. this.onDisposeObservable.clear();
  56276. };
  56277. /**
  56278. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56279. * @param radius The radius of the sphere to emit from
  56280. * @returns the emitter
  56281. */
  56282. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56283. if (radius === void 0) { radius = 1; }
  56284. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56285. this.particleEmitterType = particleEmitter;
  56286. return particleEmitter;
  56287. };
  56288. /**
  56289. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56290. * @param radius The radius of the sphere to emit from
  56291. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56292. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56293. * @returns the emitter
  56294. */
  56295. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56296. if (radius === void 0) { radius = 1; }
  56297. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56298. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56299. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56300. this.particleEmitterType = particleEmitter;
  56301. return particleEmitter;
  56302. };
  56303. /**
  56304. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56305. * @param radius The radius of the cone to emit from
  56306. * @param angle The base angle of the cone
  56307. * @returns the emitter
  56308. */
  56309. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56310. if (radius === void 0) { radius = 1; }
  56311. if (angle === void 0) { angle = Math.PI / 4; }
  56312. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56313. this.particleEmitterType = particleEmitter;
  56314. return particleEmitter;
  56315. };
  56316. // 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.
  56317. /**
  56318. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56319. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56320. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56321. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56322. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56323. * @returns the emitter
  56324. */
  56325. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56326. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56327. this.particleEmitterType = particleEmitter;
  56328. this.direction1 = direction1;
  56329. this.direction2 = direction2;
  56330. this.minEmitBox = minEmitBox;
  56331. this.maxEmitBox = maxEmitBox;
  56332. return particleEmitter;
  56333. };
  56334. // Clone
  56335. /**
  56336. * Clones the particle system.
  56337. * @param name The name of the cloned object
  56338. * @param newEmitter The new emitter to use
  56339. * @returns the cloned particle system
  56340. */
  56341. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56342. var custom = null;
  56343. var program = null;
  56344. if (this.customShader != null) {
  56345. program = this.customShader;
  56346. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56347. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56348. }
  56349. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56350. result.customShader = program;
  56351. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56352. if (newEmitter === undefined) {
  56353. newEmitter = this.emitter;
  56354. }
  56355. result.emitter = newEmitter;
  56356. if (this.particleTexture) {
  56357. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56358. }
  56359. if (!this.preventAutoStart) {
  56360. result.start();
  56361. }
  56362. return result;
  56363. };
  56364. /**
  56365. * Serializes the particle system to a JSON object.
  56366. * @returns the JSON object
  56367. */
  56368. ParticleSystem.prototype.serialize = function () {
  56369. var serializationObject = {};
  56370. serializationObject.name = this.name;
  56371. serializationObject.id = this.id;
  56372. // Emitter
  56373. if (this.emitter.position) {
  56374. var emitterMesh = this.emitter;
  56375. serializationObject.emitterId = emitterMesh.id;
  56376. }
  56377. else {
  56378. var emitterPosition = this.emitter;
  56379. serializationObject.emitter = emitterPosition.asArray();
  56380. }
  56381. serializationObject.capacity = this.getCapacity();
  56382. if (this.particleTexture) {
  56383. serializationObject.textureName = this.particleTexture.name;
  56384. }
  56385. // Animations
  56386. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56387. // Particle system
  56388. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56389. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56390. serializationObject.minSize = this.minSize;
  56391. serializationObject.maxSize = this.maxSize;
  56392. serializationObject.minEmitPower = this.minEmitPower;
  56393. serializationObject.maxEmitPower = this.maxEmitPower;
  56394. serializationObject.minLifeTime = this.minLifeTime;
  56395. serializationObject.maxLifeTime = this.maxLifeTime;
  56396. serializationObject.emitRate = this.emitRate;
  56397. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56398. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56399. serializationObject.gravity = this.gravity.asArray();
  56400. serializationObject.direction1 = this.direction1.asArray();
  56401. serializationObject.direction2 = this.direction2.asArray();
  56402. serializationObject.color1 = this.color1.asArray();
  56403. serializationObject.color2 = this.color2.asArray();
  56404. serializationObject.colorDead = this.colorDead.asArray();
  56405. serializationObject.updateSpeed = this.updateSpeed;
  56406. serializationObject.targetStopDuration = this.targetStopDuration;
  56407. serializationObject.textureMask = this.textureMask.asArray();
  56408. serializationObject.blendMode = this.blendMode;
  56409. serializationObject.customShader = this.customShader;
  56410. serializationObject.preventAutoStart = this.preventAutoStart;
  56411. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56412. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56413. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56414. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56415. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56416. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56417. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56418. // Emitter
  56419. if (this.particleEmitterType) {
  56420. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56421. }
  56422. return serializationObject;
  56423. };
  56424. /**
  56425. * Parses a JSON object to create a particle system.
  56426. * @param parsedParticleSystem The JSON object to parse
  56427. * @param scene The scene to create the particle system in
  56428. * @param rootUrl The root url to use to load external dependencies like texture
  56429. * @returns the Parsed particle system
  56430. */
  56431. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56432. var name = parsedParticleSystem.name;
  56433. var custom = null;
  56434. var program = null;
  56435. if (parsedParticleSystem.customShader) {
  56436. program = parsedParticleSystem.customShader;
  56437. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56438. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56439. }
  56440. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56441. particleSystem.customShader = program;
  56442. if (parsedParticleSystem.id) {
  56443. particleSystem.id = parsedParticleSystem.id;
  56444. }
  56445. // Auto start
  56446. if (parsedParticleSystem.preventAutoStart) {
  56447. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56448. }
  56449. // Texture
  56450. if (parsedParticleSystem.textureName) {
  56451. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56452. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56453. }
  56454. // Emitter
  56455. if (parsedParticleSystem.emitterId) {
  56456. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56457. }
  56458. else {
  56459. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56460. }
  56461. // Animations
  56462. if (parsedParticleSystem.animations) {
  56463. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56464. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56465. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56466. }
  56467. }
  56468. if (parsedParticleSystem.autoAnimate) {
  56469. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56470. }
  56471. // Particle system
  56472. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56473. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56474. particleSystem.minSize = parsedParticleSystem.minSize;
  56475. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56476. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56477. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56478. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56479. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56480. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56481. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56482. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56483. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56484. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56485. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56486. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56487. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56488. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56489. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56490. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56491. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56492. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56493. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56494. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56495. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56496. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56497. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56498. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56499. if (!particleSystem.preventAutoStart) {
  56500. particleSystem.start();
  56501. }
  56502. return particleSystem;
  56503. };
  56504. /**
  56505. * Source color is added to the destination color without alpha affecting the result.
  56506. */
  56507. ParticleSystem.BLENDMODE_ONEONE = 0;
  56508. /**
  56509. * Blend current color and particle color using particle’s alpha.
  56510. */
  56511. ParticleSystem.BLENDMODE_STANDARD = 1;
  56512. return ParticleSystem;
  56513. }());
  56514. BABYLON.ParticleSystem = ParticleSystem;
  56515. })(BABYLON || (BABYLON = {}));
  56516. //# sourceMappingURL=babylon.particleSystem.js.map
  56517. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56518. var BABYLON;
  56519. (function (BABYLON) {
  56520. /**
  56521. * Particle emitter emitting particles from the inside of a box.
  56522. * It emits the particles randomly between 2 given directions.
  56523. */
  56524. var BoxParticleEmitter = /** @class */ (function () {
  56525. /**
  56526. * Creates a new instance BoxParticleEmitter
  56527. */
  56528. function BoxParticleEmitter() {
  56529. /**
  56530. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56531. */
  56532. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56533. /**
  56534. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56535. */
  56536. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56537. /**
  56538. * 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.
  56539. */
  56540. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56541. /**
  56542. * 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.
  56543. */
  56544. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56545. }
  56546. /**
  56547. * Called by the particle System when the direction is computed for the created particle.
  56548. * @param emitPower is the power of the particle (speed)
  56549. * @param worldMatrix is the world matrix of the particle system
  56550. * @param directionToUpdate is the direction vector to update with the result
  56551. * @param particle is the particle we are computed the direction for
  56552. */
  56553. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56554. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56555. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56556. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56557. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56558. };
  56559. /**
  56560. * Called by the particle System when the position is computed for the created particle.
  56561. * @param worldMatrix is the world matrix of the particle system
  56562. * @param positionToUpdate is the position vector to update with the result
  56563. * @param particle is the particle we are computed the position for
  56564. */
  56565. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56566. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56567. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56568. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56569. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56570. };
  56571. /**
  56572. * Clones the current emitter and returns a copy of it
  56573. * @returns the new emitter
  56574. */
  56575. BoxParticleEmitter.prototype.clone = function () {
  56576. var newOne = new BoxParticleEmitter();
  56577. BABYLON.Tools.DeepCopy(this, newOne);
  56578. return newOne;
  56579. };
  56580. /**
  56581. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56582. * @param effect defines the update shader
  56583. */
  56584. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56585. effect.setVector3("direction1", this.direction1);
  56586. effect.setVector3("direction2", this.direction2);
  56587. effect.setVector3("minEmitBox", this.minEmitBox);
  56588. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56589. };
  56590. /**
  56591. * Returns a string to use to update the GPU particles update shader
  56592. * @returns a string containng the defines string
  56593. */
  56594. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56595. return "#define BOXEMITTER";
  56596. };
  56597. /**
  56598. * Returns the string "BoxEmitter"
  56599. * @returns a string containing the class name
  56600. */
  56601. BoxParticleEmitter.prototype.getClassName = function () {
  56602. return "BoxEmitter";
  56603. };
  56604. /**
  56605. * Serializes the particle system to a JSON object.
  56606. * @returns the JSON object
  56607. */
  56608. BoxParticleEmitter.prototype.serialize = function () {
  56609. var serializationObject = {};
  56610. serializationObject.type = this.getClassName();
  56611. serializationObject.direction1 = this.direction1.asArray();
  56612. ;
  56613. serializationObject.direction2 = this.direction2.asArray();
  56614. ;
  56615. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56616. ;
  56617. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56618. ;
  56619. return serializationObject;
  56620. };
  56621. /**
  56622. * Parse properties from a JSON object
  56623. * @param serializationObject defines the JSON object
  56624. */
  56625. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56626. this.direction1.copyFrom(serializationObject.direction1);
  56627. this.direction2.copyFrom(serializationObject.direction2);
  56628. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56629. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56630. };
  56631. return BoxParticleEmitter;
  56632. }());
  56633. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56634. })(BABYLON || (BABYLON = {}));
  56635. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56636. var BABYLON;
  56637. (function (BABYLON) {
  56638. /**
  56639. * Particle emitter emitting particles from the inside of a cone.
  56640. * It emits the particles alongside the cone volume from the base to the particle.
  56641. * The emission direction might be randomized.
  56642. */
  56643. var ConeParticleEmitter = /** @class */ (function () {
  56644. /**
  56645. * Creates a new instance ConeParticleEmitter
  56646. * @param radius the radius of the emission cone (1 by default)
  56647. * @param angles the cone base angle (PI by default)
  56648. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56649. */
  56650. function ConeParticleEmitter(radius,
  56651. /**
  56652. * The radius of the emission cone.
  56653. */
  56654. angle,
  56655. /**
  56656. * The cone base angle.
  56657. */
  56658. directionRandomizer) {
  56659. if (radius === void 0) { radius = 1; }
  56660. if (angle === void 0) { angle = Math.PI; }
  56661. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56662. this.angle = angle;
  56663. this.directionRandomizer = directionRandomizer;
  56664. this.radius = radius;
  56665. }
  56666. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56667. /**
  56668. * Gets the radius of the emission cone.
  56669. */
  56670. get: function () {
  56671. return this._radius;
  56672. },
  56673. /**
  56674. * Sets the radius of the emission cone.
  56675. */
  56676. set: function (value) {
  56677. this._radius = value;
  56678. if (this.angle !== 0) {
  56679. this._height = value / Math.tan(this.angle / 2);
  56680. }
  56681. else {
  56682. this._height = 1;
  56683. }
  56684. },
  56685. enumerable: true,
  56686. configurable: true
  56687. });
  56688. /**
  56689. * Called by the particle System when the direction is computed for the created particle.
  56690. * @param emitPower is the power of the particle (speed)
  56691. * @param worldMatrix is the world matrix of the particle system
  56692. * @param directionToUpdate is the direction vector to update with the result
  56693. * @param particle is the particle we are computed the direction for
  56694. */
  56695. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56696. if (this.angle === 0) {
  56697. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56698. }
  56699. else {
  56700. // measure the direction Vector from the emitter to the particle.
  56701. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56702. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56703. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56704. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56705. direction.x += randX;
  56706. direction.y += randY;
  56707. direction.z += randZ;
  56708. direction.normalize();
  56709. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56710. }
  56711. };
  56712. /**
  56713. * Called by the particle System when the position is computed for the created particle.
  56714. * @param worldMatrix is the world matrix of the particle system
  56715. * @param positionToUpdate is the position vector to update with the result
  56716. * @param particle is the particle we are computed the position for
  56717. */
  56718. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56719. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56720. var h = BABYLON.Scalar.RandomRange(0, 1);
  56721. // Better distribution in a cone at normal angles.
  56722. h = 1 - h * h;
  56723. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56724. radius = radius * h;
  56725. var randX = radius * Math.sin(s);
  56726. var randZ = radius * Math.cos(s);
  56727. var randY = h * this._height;
  56728. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56729. };
  56730. /**
  56731. * Clones the current emitter and returns a copy of it
  56732. * @returns the new emitter
  56733. */
  56734. ConeParticleEmitter.prototype.clone = function () {
  56735. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  56736. BABYLON.Tools.DeepCopy(this, newOne);
  56737. return newOne;
  56738. };
  56739. /**
  56740. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56741. * @param effect defines the update shader
  56742. */
  56743. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56744. effect.setFloat("radius", this.radius);
  56745. effect.setFloat("angle", this.angle);
  56746. effect.setFloat("height", this._height);
  56747. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56748. };
  56749. /**
  56750. * Returns a string to use to update the GPU particles update shader
  56751. * @returns a string containng the defines string
  56752. */
  56753. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56754. return "#define CONEEMITTER";
  56755. };
  56756. /**
  56757. * Returns the string "BoxEmitter"
  56758. * @returns a string containing the class name
  56759. */
  56760. ConeParticleEmitter.prototype.getClassName = function () {
  56761. return "ConeEmitter";
  56762. };
  56763. /**
  56764. * Serializes the particle system to a JSON object.
  56765. * @returns the JSON object
  56766. */
  56767. ConeParticleEmitter.prototype.serialize = function () {
  56768. var serializationObject = {};
  56769. serializationObject.type = this.getClassName();
  56770. serializationObject.radius = this.radius;
  56771. serializationObject.angle = this.angle;
  56772. serializationObject.directionRandomizer = this.directionRandomizer;
  56773. return serializationObject;
  56774. };
  56775. /**
  56776. * Parse properties from a JSON object
  56777. * @param serializationObject defines the JSON object
  56778. */
  56779. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56780. this.radius = serializationObject.radius;
  56781. this.angle = serializationObject.angle;
  56782. this.directionRandomizer = serializationObject.directionRandomizer;
  56783. };
  56784. return ConeParticleEmitter;
  56785. }());
  56786. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56787. })(BABYLON || (BABYLON = {}));
  56788. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56789. var BABYLON;
  56790. (function (BABYLON) {
  56791. /**
  56792. * Particle emitter emitting particles from the inside of a sphere.
  56793. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56794. */
  56795. var SphereParticleEmitter = /** @class */ (function () {
  56796. /**
  56797. * Creates a new instance SphereParticleEmitter
  56798. * @param radius the radius of the emission sphere (1 by default)
  56799. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56800. */
  56801. function SphereParticleEmitter(
  56802. /**
  56803. * The radius of the emission sphere.
  56804. */
  56805. radius,
  56806. /**
  56807. * How much to randomize the particle direction [0-1].
  56808. */
  56809. directionRandomizer) {
  56810. if (radius === void 0) { radius = 1; }
  56811. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56812. this.radius = radius;
  56813. this.directionRandomizer = directionRandomizer;
  56814. }
  56815. /**
  56816. * Called by the particle System when the direction is computed for the created particle.
  56817. * @param emitPower is the power of the particle (speed)
  56818. * @param worldMatrix is the world matrix of the particle system
  56819. * @param directionToUpdate is the direction vector to update with the result
  56820. * @param particle is the particle we are computed the direction for
  56821. */
  56822. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56823. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56824. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56825. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56826. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56827. direction.x += randX;
  56828. direction.y += randY;
  56829. direction.z += randZ;
  56830. direction.normalize();
  56831. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56832. };
  56833. /**
  56834. * Called by the particle System when the position is computed for the created particle.
  56835. * @param worldMatrix is the world matrix of the particle system
  56836. * @param positionToUpdate is the position vector to update with the result
  56837. * @param particle is the particle we are computed the position for
  56838. */
  56839. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56840. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56841. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  56842. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  56843. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56844. var randY = randRadius * Math.cos(theta);
  56845. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56846. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56847. };
  56848. /**
  56849. * Clones the current emitter and returns a copy of it
  56850. * @returns the new emitter
  56851. */
  56852. SphereParticleEmitter.prototype.clone = function () {
  56853. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  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. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56862. effect.setFloat("radius", this.radius);
  56863. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56864. };
  56865. /**
  56866. * Returns a string to use to update the GPU particles update shader
  56867. * @returns a string containng the defines string
  56868. */
  56869. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56870. return "#define SPHEREEMITTER";
  56871. };
  56872. /**
  56873. * Returns the string "SphereParticleEmitter"
  56874. * @returns a string containing the class name
  56875. */
  56876. SphereParticleEmitter.prototype.getClassName = function () {
  56877. return "SphereParticleEmitter";
  56878. };
  56879. /**
  56880. * Serializes the particle system to a JSON object.
  56881. * @returns the JSON object
  56882. */
  56883. SphereParticleEmitter.prototype.serialize = function () {
  56884. var serializationObject = {};
  56885. serializationObject.type = this.getClassName();
  56886. serializationObject.radius = this.radius;
  56887. serializationObject.directionRandomizer = this.directionRandomizer;
  56888. return serializationObject;
  56889. };
  56890. /**
  56891. * Parse properties from a JSON object
  56892. * @param serializationObject defines the JSON object
  56893. */
  56894. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56895. this.radius = serializationObject.radius;
  56896. this.directionRandomizer = serializationObject.directionRandomizer;
  56897. };
  56898. return SphereParticleEmitter;
  56899. }());
  56900. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56901. /**
  56902. * Particle emitter emitting particles from the inside of a sphere.
  56903. * It emits the particles randomly between two vectors.
  56904. */
  56905. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56906. __extends(SphereDirectedParticleEmitter, _super);
  56907. /**
  56908. * Creates a new instance SphereDirectedParticleEmitter
  56909. * @param radius the radius of the emission sphere (1 by default)
  56910. * @param direction1 the min limit of the emission direction (up vector by default)
  56911. * @param direction2 the max limit of the emission direction (up vector by default)
  56912. */
  56913. function SphereDirectedParticleEmitter(radius,
  56914. /**
  56915. * The min limit of the emission direction.
  56916. */
  56917. direction1,
  56918. /**
  56919. * The max limit of the emission direction.
  56920. */
  56921. direction2) {
  56922. if (radius === void 0) { radius = 1; }
  56923. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  56924. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  56925. var _this = _super.call(this, radius) || this;
  56926. _this.direction1 = direction1;
  56927. _this.direction2 = direction2;
  56928. return _this;
  56929. }
  56930. /**
  56931. * Called by the particle System when the direction is computed for the created particle.
  56932. * @param emitPower is the power of the particle (speed)
  56933. * @param worldMatrix is the world matrix of the particle system
  56934. * @param directionToUpdate is the direction vector to update with the result
  56935. * @param particle is the particle we are computed the direction for
  56936. */
  56937. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56938. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56939. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56940. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56941. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56942. };
  56943. /**
  56944. * Clones the current emitter and returns a copy of it
  56945. * @returns the new emitter
  56946. */
  56947. SphereDirectedParticleEmitter.prototype.clone = function () {
  56948. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  56949. BABYLON.Tools.DeepCopy(this, newOne);
  56950. return newOne;
  56951. };
  56952. /**
  56953. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56954. * @param effect defines the update shader
  56955. */
  56956. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  56957. effect.setFloat("radius", this.radius);
  56958. effect.setVector3("direction1", this.direction1);
  56959. effect.setVector3("direction2", this.direction2);
  56960. };
  56961. /**
  56962. * Returns a string to use to update the GPU particles update shader
  56963. * @returns a string containng the defines string
  56964. */
  56965. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  56966. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  56967. };
  56968. /**
  56969. * Returns the string "SphereDirectedParticleEmitter"
  56970. * @returns a string containing the class name
  56971. */
  56972. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  56973. return "SphereDirectedParticleEmitter";
  56974. };
  56975. /**
  56976. * Serializes the particle system to a JSON object.
  56977. * @returns the JSON object
  56978. */
  56979. SphereDirectedParticleEmitter.prototype.serialize = function () {
  56980. var serializationObject = _super.prototype.serialize.call(this);
  56981. ;
  56982. serializationObject.direction1 = this.direction1.asArray();
  56983. ;
  56984. serializationObject.direction2 = this.direction2.asArray();
  56985. ;
  56986. return serializationObject;
  56987. };
  56988. /**
  56989. * Parse properties from a JSON object
  56990. * @param serializationObject defines the JSON object
  56991. */
  56992. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  56993. _super.prototype.parse.call(this, serializationObject);
  56994. this.direction1.copyFrom(serializationObject.direction1);
  56995. this.direction2.copyFrom(serializationObject.direction2);
  56996. };
  56997. return SphereDirectedParticleEmitter;
  56998. }(SphereParticleEmitter));
  56999. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57000. })(BABYLON || (BABYLON = {}));
  57001. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57002. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57003. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57004. s = arguments[i];
  57005. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57006. t[p] = s[p];
  57007. }
  57008. return t;
  57009. };
  57010. var BABYLON;
  57011. (function (BABYLON) {
  57012. /**
  57013. * This represents a GPU particle system in Babylon
  57014. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57015. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57016. */
  57017. var GPUParticleSystem = /** @class */ (function () {
  57018. /**
  57019. * Instantiates a GPU particle system.
  57020. * 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.
  57021. * @param name The name of the particle system
  57022. * @param capacity The max number of particles alive at the same time
  57023. * @param scene The scene the particle system belongs to
  57024. */
  57025. function GPUParticleSystem(name, options, scene) {
  57026. /**
  57027. * The emitter represents the Mesh or position we are attaching the particle system to.
  57028. */
  57029. this.emitter = null;
  57030. /**
  57031. * The rendering group used by the Particle system to chose when to render.
  57032. */
  57033. this.renderingGroupId = 0;
  57034. /**
  57035. * The layer mask we are rendering the particles through.
  57036. */
  57037. this.layerMask = 0x0FFFFFFF;
  57038. this._targetIndex = 0;
  57039. this._currentRenderId = -1;
  57040. this._started = false;
  57041. this._stopped = false;
  57042. this._timeDelta = 0;
  57043. this._attributesStrideSize = 14;
  57044. this._actualFrame = 0;
  57045. /**
  57046. * List of animations used by the particle system.
  57047. */
  57048. this.animations = [];
  57049. /**
  57050. * An event triggered when the system is disposed.
  57051. */
  57052. this.onDisposeObservable = new BABYLON.Observable();
  57053. /**
  57054. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57055. */
  57056. this.updateSpeed = 0.01;
  57057. /**
  57058. * The amount of time the particle system is running (depends of the overall update speed).
  57059. */
  57060. this.targetStopDuration = 0;
  57061. /**
  57062. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57063. */
  57064. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57065. /**
  57066. * Minimum life time of emitting particles.
  57067. */
  57068. this.minLifeTime = 1;
  57069. /**
  57070. * Maximum life time of emitting particles.
  57071. */
  57072. this.maxLifeTime = 1;
  57073. /**
  57074. * Minimum Size of emitting particles.
  57075. */
  57076. this.minSize = 1;
  57077. /**
  57078. * Maximum Size of emitting particles.
  57079. */
  57080. this.maxSize = 1;
  57081. /**
  57082. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57083. */
  57084. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57085. /**
  57086. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57087. */
  57088. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57089. /**
  57090. * Color the particle will have at the end of its lifetime.
  57091. */
  57092. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57093. /**
  57094. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57095. */
  57096. this.emitRate = 100;
  57097. /**
  57098. * You can use gravity if you want to give an orientation to your particles.
  57099. */
  57100. this.gravity = BABYLON.Vector3.Zero();
  57101. /**
  57102. * Minimum power of emitting particles.
  57103. */
  57104. this.minEmitPower = 1;
  57105. /**
  57106. * Maximum power of emitting particles.
  57107. */
  57108. this.maxEmitPower = 1;
  57109. /**
  57110. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57111. * to override the particles.
  57112. */
  57113. this.forceDepthWrite = false;
  57114. this.id = name;
  57115. this.name = name;
  57116. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57117. this._engine = this._scene.getEngine();
  57118. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57119. this._capacity = fullOptions.capacity;
  57120. this._activeCount = fullOptions.capacity;
  57121. this._currentActiveCount = 0;
  57122. this._scene.particleSystems.push(this);
  57123. this._updateEffectOptions = {
  57124. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  57125. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57126. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  57127. uniformBuffersNames: [],
  57128. samplers: ["randomSampler"],
  57129. defines: "",
  57130. fallbacks: null,
  57131. onCompiled: null,
  57132. onError: null,
  57133. indexParameters: null,
  57134. maxSimultaneousLights: 0,
  57135. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  57136. };
  57137. // Random data
  57138. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57139. var d = [];
  57140. for (var i = 0; i < maxTextureSize; ++i) {
  57141. d.push(Math.random());
  57142. d.push(Math.random());
  57143. d.push(Math.random());
  57144. d.push(Math.random());
  57145. }
  57146. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57147. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57148. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57149. this._randomTextureSize = maxTextureSize;
  57150. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57151. }
  57152. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57153. /**
  57154. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57155. */
  57156. get: function () {
  57157. if (!BABYLON.Engine.LastCreatedEngine) {
  57158. return false;
  57159. }
  57160. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57161. },
  57162. enumerable: true,
  57163. configurable: true
  57164. });
  57165. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57166. /**
  57167. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57168. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57169. */
  57170. get: function () {
  57171. if (this.particleEmitterType.direction1) {
  57172. return this.particleEmitterType.direction1;
  57173. }
  57174. return BABYLON.Vector3.Zero();
  57175. },
  57176. set: function (value) {
  57177. if (this.particleEmitterType.direction1) {
  57178. this.particleEmitterType.direction1 = value;
  57179. }
  57180. },
  57181. enumerable: true,
  57182. configurable: true
  57183. });
  57184. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57185. /**
  57186. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57187. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57188. */
  57189. get: function () {
  57190. if (this.particleEmitterType.direction2) {
  57191. return this.particleEmitterType.direction2;
  57192. }
  57193. return BABYLON.Vector3.Zero();
  57194. },
  57195. set: function (value) {
  57196. if (this.particleEmitterType.direction2) {
  57197. this.particleEmitterType.direction2 = value;
  57198. }
  57199. },
  57200. enumerable: true,
  57201. configurable: true
  57202. });
  57203. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57204. /**
  57205. * 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.
  57206. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57207. */
  57208. get: function () {
  57209. if (this.particleEmitterType.minEmitBox) {
  57210. return this.particleEmitterType.minEmitBox;
  57211. }
  57212. return BABYLON.Vector3.Zero();
  57213. },
  57214. set: function (value) {
  57215. if (this.particleEmitterType.minEmitBox) {
  57216. this.particleEmitterType.minEmitBox = value;
  57217. }
  57218. },
  57219. enumerable: true,
  57220. configurable: true
  57221. });
  57222. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57223. /**
  57224. * 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.
  57225. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57226. */
  57227. get: function () {
  57228. if (this.particleEmitterType.maxEmitBox) {
  57229. return this.particleEmitterType.maxEmitBox;
  57230. }
  57231. return BABYLON.Vector3.Zero();
  57232. },
  57233. set: function (value) {
  57234. if (this.particleEmitterType.maxEmitBox) {
  57235. this.particleEmitterType.maxEmitBox = value;
  57236. }
  57237. },
  57238. enumerable: true,
  57239. configurable: true
  57240. });
  57241. /**
  57242. * Gets the maximum number of particles active at the same time.
  57243. * @returns The max number of active particles.
  57244. */
  57245. GPUParticleSystem.prototype.getCapacity = function () {
  57246. return this._capacity;
  57247. };
  57248. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57249. /**
  57250. * Gets or set the number of active particles
  57251. */
  57252. get: function () {
  57253. return this._activeCount;
  57254. },
  57255. set: function (value) {
  57256. this._activeCount = Math.min(value, this._capacity);
  57257. },
  57258. enumerable: true,
  57259. configurable: true
  57260. });
  57261. /**
  57262. * Is this system ready to be used/rendered
  57263. * @return true if the system is ready
  57264. */
  57265. GPUParticleSystem.prototype.isReady = function () {
  57266. if (!this._updateEffect) {
  57267. this._recreateUpdateEffect();
  57268. this._recreateRenderEffect();
  57269. return false;
  57270. }
  57271. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57272. return false;
  57273. }
  57274. return true;
  57275. };
  57276. /**
  57277. * Gets Wether the system has been started.
  57278. * @returns True if it has been started, otherwise false.
  57279. */
  57280. GPUParticleSystem.prototype.isStarted = function () {
  57281. return this._started;
  57282. };
  57283. /**
  57284. * Starts the particle system and begins to emit.
  57285. */
  57286. GPUParticleSystem.prototype.start = function () {
  57287. this._started = true;
  57288. this._stopped = false;
  57289. };
  57290. /**
  57291. * Stops the particle system.
  57292. */
  57293. GPUParticleSystem.prototype.stop = function () {
  57294. this._stopped = true;
  57295. };
  57296. /**
  57297. * Remove all active particles
  57298. */
  57299. GPUParticleSystem.prototype.reset = function () {
  57300. this._releaseBuffers();
  57301. this._releaseVAOs();
  57302. this._currentActiveCount = 0;
  57303. this._targetIndex = 0;
  57304. };
  57305. /**
  57306. * Returns the string "GPUParticleSystem"
  57307. * @returns a string containing the class name
  57308. */
  57309. GPUParticleSystem.prototype.getClassName = function () {
  57310. return "GPUParticleSystem";
  57311. };
  57312. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57313. var updateVertexBuffers = {};
  57314. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57315. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57316. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57317. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57318. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57319. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57320. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57321. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57322. this._engine.bindArrayBuffer(null);
  57323. return vao;
  57324. };
  57325. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57326. var renderVertexBuffers = {};
  57327. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57328. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57329. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57330. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57331. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57332. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57333. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57334. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57335. this._engine.bindArrayBuffer(null);
  57336. return vao;
  57337. };
  57338. GPUParticleSystem.prototype._initialize = function (force) {
  57339. if (force === void 0) { force = false; }
  57340. if (this._buffer0 && !force) {
  57341. return;
  57342. }
  57343. var engine = this._scene.getEngine();
  57344. var data = new Array();
  57345. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57346. // position
  57347. data.push(0.0);
  57348. data.push(0.0);
  57349. data.push(0.0);
  57350. // Age and life
  57351. data.push(0.0); // create the particle as a dead one to create a new one at start
  57352. data.push(0.0);
  57353. // Seed
  57354. data.push(Math.random());
  57355. // Size
  57356. data.push(0.0);
  57357. // color
  57358. data.push(0.0);
  57359. data.push(0.0);
  57360. data.push(0.0);
  57361. data.push(0.0);
  57362. // direction
  57363. data.push(0.0);
  57364. data.push(0.0);
  57365. data.push(0.0);
  57366. }
  57367. // Sprite data
  57368. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57369. -0.5, 0.5, 0, 1,
  57370. -0.5, -0.5, 0, 0,
  57371. 0.5, -0.5, 1, 0]);
  57372. // Buffers
  57373. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57374. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57375. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57376. // Update VAO
  57377. this._updateVAO = [];
  57378. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57379. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57380. // Render VAO
  57381. this._renderVAO = [];
  57382. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57383. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57384. // Links
  57385. this._sourceBuffer = this._buffer0;
  57386. this._targetBuffer = this._buffer1;
  57387. };
  57388. /** @hidden */
  57389. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57390. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57391. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57392. return;
  57393. }
  57394. this._updateEffectOptions.defines = defines;
  57395. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57396. };
  57397. /** @hidden */
  57398. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57399. var defines = "";
  57400. if (this._scene.clipPlane) {
  57401. defines = "\n#define CLIPPLANE";
  57402. }
  57403. if (this._renderEffect && this._renderEffect.defines === defines) {
  57404. return;
  57405. }
  57406. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57407. };
  57408. /**
  57409. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57410. */
  57411. GPUParticleSystem.prototype.animate = function () {
  57412. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57413. this._actualFrame += this._timeDelta;
  57414. if (!this._stopped) {
  57415. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57416. this.stop();
  57417. }
  57418. }
  57419. };
  57420. /**
  57421. * Renders the particle system in its current state.
  57422. * @returns the current number of particles
  57423. */
  57424. GPUParticleSystem.prototype.render = function () {
  57425. if (!this._started) {
  57426. return 0;
  57427. }
  57428. this._recreateUpdateEffect();
  57429. this._recreateRenderEffect();
  57430. if (!this.isReady()) {
  57431. return 0;
  57432. }
  57433. if (this._currentRenderId === this._scene.getRenderId()) {
  57434. return 0;
  57435. }
  57436. this._currentRenderId = this._scene.getRenderId();
  57437. // Get everything ready to render
  57438. this._initialize();
  57439. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57440. // Enable update effect
  57441. this._engine.enableEffect(this._updateEffect);
  57442. this._engine.setState(false);
  57443. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57444. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57445. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57446. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57447. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57448. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57449. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57450. this._updateEffect.setDirectColor4("color1", this.color1);
  57451. this._updateEffect.setDirectColor4("color2", this.color2);
  57452. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57453. this._updateEffect.setVector3("gravity", this.gravity);
  57454. if (this.particleEmitterType) {
  57455. this.particleEmitterType.applyToShader(this._updateEffect);
  57456. }
  57457. var emitterWM;
  57458. if (this.emitter.position) {
  57459. var emitterMesh = this.emitter;
  57460. emitterWM = emitterMesh.getWorldMatrix();
  57461. }
  57462. else {
  57463. var emitterPosition = this.emitter;
  57464. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57465. }
  57466. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57467. // Bind source VAO
  57468. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57469. // Update
  57470. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57471. this._engine.setRasterizerState(false);
  57472. this._engine.beginTransformFeedback();
  57473. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57474. this._engine.endTransformFeedback();
  57475. this._engine.setRasterizerState(true);
  57476. this._engine.bindTransformFeedbackBuffer(null);
  57477. // Enable render effect
  57478. this._engine.enableEffect(this._renderEffect);
  57479. var viewMatrix = this._scene.getViewMatrix();
  57480. this._renderEffect.setMatrix("view", viewMatrix);
  57481. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57482. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57483. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57484. if (this._scene.clipPlane) {
  57485. var clipPlane = this._scene.clipPlane;
  57486. var invView = viewMatrix.clone();
  57487. invView.invert();
  57488. this._renderEffect.setMatrix("invView", invView);
  57489. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57490. }
  57491. // Draw order
  57492. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57493. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57494. }
  57495. else {
  57496. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57497. }
  57498. if (this.forceDepthWrite) {
  57499. this._engine.setDepthWrite(true);
  57500. }
  57501. // Bind source VAO
  57502. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57503. // Render
  57504. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57505. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57506. // Switch VAOs
  57507. this._targetIndex++;
  57508. if (this._targetIndex === 2) {
  57509. this._targetIndex = 0;
  57510. }
  57511. // Switch buffers
  57512. var tmpBuffer = this._sourceBuffer;
  57513. this._sourceBuffer = this._targetBuffer;
  57514. this._targetBuffer = tmpBuffer;
  57515. return this._currentActiveCount;
  57516. };
  57517. /**
  57518. * Rebuilds the particle system
  57519. */
  57520. GPUParticleSystem.prototype.rebuild = function () {
  57521. this._initialize(true);
  57522. };
  57523. GPUParticleSystem.prototype._releaseBuffers = function () {
  57524. if (this._buffer0) {
  57525. this._buffer0.dispose();
  57526. this._buffer0 = null;
  57527. }
  57528. if (this._buffer1) {
  57529. this._buffer1.dispose();
  57530. this._buffer1 = null;
  57531. }
  57532. if (this._spriteBuffer) {
  57533. this._spriteBuffer.dispose();
  57534. this._spriteBuffer = null;
  57535. }
  57536. };
  57537. GPUParticleSystem.prototype._releaseVAOs = function () {
  57538. if (!this._updateVAO) {
  57539. return;
  57540. }
  57541. for (var index = 0; index < this._updateVAO.length; index++) {
  57542. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57543. }
  57544. this._updateVAO = [];
  57545. for (var index = 0; index < this._renderVAO.length; index++) {
  57546. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57547. }
  57548. this._renderVAO = [];
  57549. };
  57550. /**
  57551. * Disposes the particle system and free the associated resources
  57552. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57553. */
  57554. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57555. if (disposeTexture === void 0) { disposeTexture = true; }
  57556. var index = this._scene.particleSystems.indexOf(this);
  57557. if (index > -1) {
  57558. this._scene.particleSystems.splice(index, 1);
  57559. }
  57560. this._releaseBuffers();
  57561. this._releaseVAOs();
  57562. if (this._randomTexture) {
  57563. this._randomTexture.dispose();
  57564. this._randomTexture = null;
  57565. }
  57566. if (disposeTexture && this.particleTexture) {
  57567. this.particleTexture.dispose();
  57568. this.particleTexture = null;
  57569. }
  57570. // Callback
  57571. this.onDisposeObservable.notifyObservers(this);
  57572. this.onDisposeObservable.clear();
  57573. };
  57574. /**
  57575. * Clones the particle system.
  57576. * @param name The name of the cloned object
  57577. * @param newEmitter The new emitter to use
  57578. * @returns the cloned particle system
  57579. */
  57580. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57581. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57582. BABYLON.Tools.DeepCopy(this, result);
  57583. if (newEmitter === undefined) {
  57584. newEmitter = this.emitter;
  57585. }
  57586. result.emitter = newEmitter;
  57587. if (this.particleTexture) {
  57588. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57589. }
  57590. return result;
  57591. };
  57592. /**
  57593. * Serializes the particle system to a JSON object.
  57594. * @returns the JSON object
  57595. */
  57596. GPUParticleSystem.prototype.serialize = function () {
  57597. var serializationObject = {};
  57598. serializationObject.name = this.name;
  57599. serializationObject.id = this.id;
  57600. // Emitter
  57601. if (this.emitter.position) {
  57602. var emitterMesh = this.emitter;
  57603. serializationObject.emitterId = emitterMesh.id;
  57604. }
  57605. else {
  57606. var emitterPosition = this.emitter;
  57607. serializationObject.emitter = emitterPosition.asArray();
  57608. }
  57609. serializationObject.capacity = this.getCapacity();
  57610. if (this.particleTexture) {
  57611. serializationObject.textureName = this.particleTexture.name;
  57612. }
  57613. // Animations
  57614. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57615. // Particle system
  57616. serializationObject.activeParticleCount = this.activeParticleCount;
  57617. serializationObject.randomTextureSize = this._randomTextureSize;
  57618. serializationObject.minSize = this.minSize;
  57619. serializationObject.maxSize = this.maxSize;
  57620. serializationObject.minEmitPower = this.minEmitPower;
  57621. serializationObject.maxEmitPower = this.maxEmitPower;
  57622. serializationObject.minLifeTime = this.minLifeTime;
  57623. serializationObject.maxLifeTime = this.maxLifeTime;
  57624. serializationObject.emitRate = this.emitRate;
  57625. serializationObject.gravity = this.gravity.asArray();
  57626. serializationObject.color1 = this.color1.asArray();
  57627. serializationObject.color2 = this.color2.asArray();
  57628. serializationObject.colorDead = this.colorDead.asArray();
  57629. serializationObject.updateSpeed = this.updateSpeed;
  57630. serializationObject.targetStopDuration = this.targetStopDuration;
  57631. serializationObject.blendMode = this.blendMode;
  57632. // Emitter
  57633. if (this.particleEmitterType) {
  57634. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57635. }
  57636. return serializationObject;
  57637. };
  57638. /**
  57639. * Parses a JSON object to create a GPU particle system.
  57640. * @param parsedParticleSystem The JSON object to parse
  57641. * @param scene The scene to create the particle system in
  57642. * @param rootUrl The root url to use to load external dependencies like texture
  57643. * @returns the parsed GPU particle system
  57644. */
  57645. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57646. var name = parsedParticleSystem.name;
  57647. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57648. if (parsedParticleSystem.id) {
  57649. particleSystem.id = parsedParticleSystem.id;
  57650. }
  57651. // Texture
  57652. if (parsedParticleSystem.textureName) {
  57653. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57654. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57655. }
  57656. // Emitter
  57657. if (parsedParticleSystem.emitterId) {
  57658. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57659. }
  57660. else {
  57661. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57662. }
  57663. // Animations
  57664. if (parsedParticleSystem.animations) {
  57665. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57666. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57667. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57668. }
  57669. }
  57670. // Particle system
  57671. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57672. particleSystem.minSize = parsedParticleSystem.minSize;
  57673. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57674. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57675. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57676. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57677. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57678. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57679. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57680. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57681. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57682. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57683. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57684. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57685. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57686. // Emitter
  57687. if (parsedParticleSystem.particleEmitterType) {
  57688. var emitterType = void 0;
  57689. switch (parsedParticleSystem.particleEmitterType.type) {
  57690. case "SphereEmitter":
  57691. emitterType = new BABYLON.SphereParticleEmitter();
  57692. break;
  57693. case "SphereDirectedParticleEmitter":
  57694. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57695. break;
  57696. case "ConeEmitter":
  57697. emitterType = new BABYLON.ConeParticleEmitter();
  57698. break;
  57699. case "BoxEmitter":
  57700. default:
  57701. emitterType = new BABYLON.BoxParticleEmitter();
  57702. break;
  57703. }
  57704. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57705. particleSystem.particleEmitterType = emitterType;
  57706. }
  57707. return particleSystem;
  57708. };
  57709. return GPUParticleSystem;
  57710. }());
  57711. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57712. })(BABYLON || (BABYLON = {}));
  57713. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57714. var BABYLON;
  57715. (function (BABYLON) {
  57716. /**
  57717. * Represents one particle of a solid particle system.
  57718. */
  57719. var SolidParticle = /** @class */ (function () {
  57720. /**
  57721. * Creates a Solid Particle object.
  57722. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57723. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57724. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57725. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57726. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57727. * @param shapeId (integer) is the model shape identifier in the SPS.
  57728. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57729. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57730. */
  57731. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57732. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57733. /**
  57734. * particle global index
  57735. */
  57736. this.idx = 0;
  57737. /**
  57738. * The color of the particle
  57739. */
  57740. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57741. /**
  57742. * The world space position of the particle.
  57743. */
  57744. this.position = BABYLON.Vector3.Zero();
  57745. /**
  57746. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57747. */
  57748. this.rotation = BABYLON.Vector3.Zero();
  57749. /**
  57750. * The scaling of the particle.
  57751. */
  57752. this.scaling = BABYLON.Vector3.One();
  57753. /**
  57754. * The uvs of the particle.
  57755. */
  57756. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57757. /**
  57758. * The current speed of the particle.
  57759. */
  57760. this.velocity = BABYLON.Vector3.Zero();
  57761. /**
  57762. * The pivot point in the particle local space.
  57763. */
  57764. this.pivot = BABYLON.Vector3.Zero();
  57765. /**
  57766. * Must the particle be translated from its pivot point in its local space ?
  57767. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57768. * Default : false
  57769. */
  57770. this.translateFromPivot = false;
  57771. /**
  57772. * Is the particle active or not ?
  57773. */
  57774. this.alive = true;
  57775. /**
  57776. * Is the particle visible or not ?
  57777. */
  57778. this.isVisible = true;
  57779. /**
  57780. * Index of this particle in the global "positions" array (Internal use)
  57781. */
  57782. this._pos = 0;
  57783. /**
  57784. * Index of this particle in the global "indices" array (Internal use)
  57785. */
  57786. this._ind = 0;
  57787. /**
  57788. * ModelShape id of this particle
  57789. */
  57790. this.shapeId = 0;
  57791. /**
  57792. * Index of the particle in its shape id (Internal use)
  57793. */
  57794. this.idxInShape = 0;
  57795. /**
  57796. * Still set as invisible in order to skip useless computations (Internal use)
  57797. */
  57798. this._stillInvisible = false;
  57799. /**
  57800. * Last computed particle rotation matrix
  57801. */
  57802. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57803. /**
  57804. * Parent particle Id, if any.
  57805. * Default null.
  57806. */
  57807. this.parentId = null;
  57808. /**
  57809. * Internal global position in the SPS.
  57810. */
  57811. this._globalPosition = BABYLON.Vector3.Zero();
  57812. this.idx = particleIndex;
  57813. this._pos = positionIndex;
  57814. this._ind = indiceIndex;
  57815. this._model = model;
  57816. this.shapeId = shapeId;
  57817. this.idxInShape = idxInShape;
  57818. this._sps = sps;
  57819. if (modelBoundingInfo) {
  57820. this._modelBoundingInfo = modelBoundingInfo;
  57821. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57822. }
  57823. }
  57824. Object.defineProperty(SolidParticle.prototype, "scale", {
  57825. /**
  57826. * Legacy support, changed scale to scaling
  57827. */
  57828. get: function () {
  57829. return this.scaling;
  57830. },
  57831. /**
  57832. * Legacy support, changed scale to scaling
  57833. */
  57834. set: function (scale) {
  57835. this.scaling = scale;
  57836. },
  57837. enumerable: true,
  57838. configurable: true
  57839. });
  57840. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57841. /**
  57842. * Legacy support, changed quaternion to rotationQuaternion
  57843. */
  57844. get: function () {
  57845. return this.rotationQuaternion;
  57846. },
  57847. /**
  57848. * Legacy support, changed quaternion to rotationQuaternion
  57849. */
  57850. set: function (q) {
  57851. this.rotationQuaternion = q;
  57852. },
  57853. enumerable: true,
  57854. configurable: true
  57855. });
  57856. /**
  57857. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57858. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57859. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57860. * @returns true if it intersects
  57861. */
  57862. SolidParticle.prototype.intersectsMesh = function (target) {
  57863. if (!this._boundingInfo || !target._boundingInfo) {
  57864. return false;
  57865. }
  57866. if (this._sps._bSphereOnly) {
  57867. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  57868. }
  57869. return this._boundingInfo.intersects(target._boundingInfo, false);
  57870. };
  57871. return SolidParticle;
  57872. }());
  57873. BABYLON.SolidParticle = SolidParticle;
  57874. /**
  57875. * Represents the shape of the model used by one particle of a solid particle system.
  57876. * SPS internal tool, don't use it manually.
  57877. */
  57878. var ModelShape = /** @class */ (function () {
  57879. /**
  57880. * 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.
  57881. * SPS internal tool, don't use it manually.
  57882. * @hidden
  57883. */
  57884. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  57885. /**
  57886. * length of the shape in the model indices array (internal use)
  57887. */
  57888. this._indicesLength = 0;
  57889. this.shapeID = id;
  57890. this._shape = shape;
  57891. this._indicesLength = indicesLength;
  57892. this._shapeUV = shapeUV;
  57893. this._positionFunction = posFunction;
  57894. this._vertexFunction = vtxFunction;
  57895. }
  57896. return ModelShape;
  57897. }());
  57898. BABYLON.ModelShape = ModelShape;
  57899. /**
  57900. * Represents a Depth Sorted Particle in the solid particle system.
  57901. */
  57902. var DepthSortedParticle = /** @class */ (function () {
  57903. function DepthSortedParticle() {
  57904. /**
  57905. * Index of the particle in the "indices" array
  57906. */
  57907. this.ind = 0;
  57908. /**
  57909. * Length of the particle shape in the "indices" array
  57910. */
  57911. this.indicesLength = 0;
  57912. /**
  57913. * Squared distance from the particle to the camera
  57914. */
  57915. this.sqDistance = 0.0;
  57916. }
  57917. return DepthSortedParticle;
  57918. }());
  57919. BABYLON.DepthSortedParticle = DepthSortedParticle;
  57920. })(BABYLON || (BABYLON = {}));
  57921. //# sourceMappingURL=babylon.solidParticle.js.map
  57922. var BABYLON;
  57923. (function (BABYLON) {
  57924. /**
  57925. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  57926. *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.
  57927. * The SPS is also a particle system. It provides some methods to manage the particles.
  57928. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  57929. *
  57930. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  57931. */
  57932. var SolidParticleSystem = /** @class */ (function () {
  57933. /**
  57934. * Creates a SPS (Solid Particle System) object.
  57935. * @param name (String) is the SPS name, this will be the underlying mesh name.
  57936. * @param scene (Scene) is the scene in which the SPS is added.
  57937. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  57938. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  57939. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  57940. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  57941. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  57942. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  57943. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  57944. */
  57945. function SolidParticleSystem(name, scene, options) {
  57946. /**
  57947. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  57948. * Example : var p = SPS.particles[i];
  57949. */
  57950. this.particles = new Array();
  57951. /**
  57952. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  57953. */
  57954. this.nbParticles = 0;
  57955. /**
  57956. * If the particles must ever face the camera (default false). Useful for planar particles.
  57957. */
  57958. this.billboard = false;
  57959. /**
  57960. * Recompute normals when adding a shape
  57961. */
  57962. this.recomputeNormals = true;
  57963. /**
  57964. * This a counter ofr your own usage. It's not set by any SPS functions.
  57965. */
  57966. this.counter = 0;
  57967. /**
  57968. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  57969. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  57970. */
  57971. this.vars = {};
  57972. /**
  57973. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  57974. */
  57975. this._bSphereOnly = false;
  57976. /**
  57977. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  57978. */
  57979. this._bSphereRadiusFactor = 1.0;
  57980. this._positions = new Array();
  57981. this._indices = new Array();
  57982. this._normals = new Array();
  57983. this._colors = new Array();
  57984. this._uvs = new Array();
  57985. this._index = 0; // indices index
  57986. this._updatable = true;
  57987. this._pickable = false;
  57988. this._isVisibilityBoxLocked = false;
  57989. this._alwaysVisible = false;
  57990. this._depthSort = false;
  57991. this._shapeCounter = 0;
  57992. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  57993. this._color = new BABYLON.Color4(0, 0, 0, 0);
  57994. this._computeParticleColor = true;
  57995. this._computeParticleTexture = true;
  57996. this._computeParticleRotation = true;
  57997. this._computeParticleVertex = false;
  57998. this._computeBoundingBox = false;
  57999. this._depthSortParticles = true;
  58000. this._cam_axisZ = BABYLON.Vector3.Zero();
  58001. this._cam_axisY = BABYLON.Vector3.Zero();
  58002. this._cam_axisX = BABYLON.Vector3.Zero();
  58003. this._axisZ = BABYLON.Axis.Z;
  58004. this._camDir = BABYLON.Vector3.Zero();
  58005. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58006. this._rotMatrix = new BABYLON.Matrix();
  58007. this._invertMatrix = new BABYLON.Matrix();
  58008. this._rotated = BABYLON.Vector3.Zero();
  58009. this._quaternion = new BABYLON.Quaternion();
  58010. this._vertex = BABYLON.Vector3.Zero();
  58011. this._normal = BABYLON.Vector3.Zero();
  58012. this._yaw = 0.0;
  58013. this._pitch = 0.0;
  58014. this._roll = 0.0;
  58015. this._halfroll = 0.0;
  58016. this._halfpitch = 0.0;
  58017. this._halfyaw = 0.0;
  58018. this._sinRoll = 0.0;
  58019. this._cosRoll = 0.0;
  58020. this._sinPitch = 0.0;
  58021. this._cosPitch = 0.0;
  58022. this._sinYaw = 0.0;
  58023. this._cosYaw = 0.0;
  58024. this._mustUnrotateFixedNormals = false;
  58025. this._minimum = BABYLON.Vector3.Zero();
  58026. this._maximum = BABYLON.Vector3.Zero();
  58027. this._minBbox = BABYLON.Vector3.Zero();
  58028. this._maxBbox = BABYLON.Vector3.Zero();
  58029. this._particlesIntersect = false;
  58030. this._depthSortFunction = function (p1, p2) {
  58031. return (p2.sqDistance - p1.sqDistance);
  58032. };
  58033. this._needs32Bits = false;
  58034. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58035. this._scaledPivot = BABYLON.Vector3.Zero();
  58036. this._particleHasParent = false;
  58037. this.name = name;
  58038. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58039. this._camera = scene.activeCamera;
  58040. this._pickable = options ? options.isPickable : false;
  58041. this._depthSort = options ? options.enableDepthSort : false;
  58042. this._particlesIntersect = options ? options.particleIntersection : false;
  58043. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58044. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58045. if (options && options.updatable) {
  58046. this._updatable = options.updatable;
  58047. }
  58048. else {
  58049. this._updatable = true;
  58050. }
  58051. if (this._pickable) {
  58052. this.pickedParticles = [];
  58053. }
  58054. if (this._depthSort) {
  58055. this.depthSortedParticles = [];
  58056. }
  58057. }
  58058. /**
  58059. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58060. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58061. * @returns the created mesh
  58062. */
  58063. SolidParticleSystem.prototype.buildMesh = function () {
  58064. if (this.nbParticles === 0) {
  58065. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58066. this.addShape(triangle, 1);
  58067. triangle.dispose();
  58068. }
  58069. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58070. this._positions32 = new Float32Array(this._positions);
  58071. this._uvs32 = new Float32Array(this._uvs);
  58072. this._colors32 = new Float32Array(this._colors);
  58073. if (this.recomputeNormals) {
  58074. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58075. }
  58076. this._normals32 = new Float32Array(this._normals);
  58077. this._fixedNormal32 = new Float32Array(this._normals);
  58078. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58079. this._unrotateFixedNormals();
  58080. }
  58081. var vertexData = new BABYLON.VertexData();
  58082. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58083. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58084. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58085. if (this._uvs32) {
  58086. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58087. ;
  58088. }
  58089. if (this._colors32) {
  58090. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58091. }
  58092. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58093. vertexData.applyToMesh(mesh, this._updatable);
  58094. this.mesh = mesh;
  58095. this.mesh.isPickable = this._pickable;
  58096. // free memory
  58097. if (!this._depthSort) {
  58098. this._indices = null;
  58099. }
  58100. this._positions = null;
  58101. this._normals = null;
  58102. this._uvs = null;
  58103. this._colors = null;
  58104. if (!this._updatable) {
  58105. this.particles.length = 0;
  58106. }
  58107. return mesh;
  58108. };
  58109. /**
  58110. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58111. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58112. * Thus the particles generated from `digest()` have their property `position` set yet.
  58113. * @param mesh ( Mesh ) is the mesh to be digested
  58114. * @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
  58115. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58116. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58117. * @returns the current SPS
  58118. */
  58119. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58120. var size = (options && options.facetNb) || 1;
  58121. var number = (options && options.number) || 0;
  58122. var delta = (options && options.delta) || 0;
  58123. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58124. var meshInd = mesh.getIndices();
  58125. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58126. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58127. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58128. var f = 0; // facet counter
  58129. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58130. // compute size from number
  58131. if (number) {
  58132. number = (number > totalFacets) ? totalFacets : number;
  58133. size = Math.round(totalFacets / number);
  58134. delta = 0;
  58135. }
  58136. else {
  58137. size = (size > totalFacets) ? totalFacets : size;
  58138. }
  58139. var facetPos = []; // submesh positions
  58140. var facetInd = []; // submesh indices
  58141. var facetUV = []; // submesh UV
  58142. var facetCol = []; // submesh colors
  58143. var barycenter = BABYLON.Vector3.Zero();
  58144. var sizeO = size;
  58145. while (f < totalFacets) {
  58146. size = sizeO + Math.floor((1 + delta) * Math.random());
  58147. if (f > totalFacets - size) {
  58148. size = totalFacets - f;
  58149. }
  58150. // reset temp arrays
  58151. facetPos.length = 0;
  58152. facetInd.length = 0;
  58153. facetUV.length = 0;
  58154. facetCol.length = 0;
  58155. // iterate over "size" facets
  58156. var fi = 0;
  58157. for (var j = f * 3; j < (f + size) * 3; j++) {
  58158. facetInd.push(fi);
  58159. var i = meshInd[j];
  58160. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58161. if (meshUV) {
  58162. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58163. }
  58164. if (meshCol) {
  58165. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58166. }
  58167. fi++;
  58168. }
  58169. // create a model shape for each single particle
  58170. var idx = this.nbParticles;
  58171. var shape = this._posToShape(facetPos);
  58172. var shapeUV = this._uvsToShapeUV(facetUV);
  58173. // compute the barycenter of the shape
  58174. var v;
  58175. for (v = 0; v < shape.length; v++) {
  58176. barycenter.addInPlace(shape[v]);
  58177. }
  58178. barycenter.scaleInPlace(1 / shape.length);
  58179. // shift the shape from its barycenter to the origin
  58180. for (v = 0; v < shape.length; v++) {
  58181. shape[v].subtractInPlace(barycenter);
  58182. }
  58183. var bInfo;
  58184. if (this._particlesIntersect) {
  58185. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58186. }
  58187. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58188. // add the particle in the SPS
  58189. var currentPos = this._positions.length;
  58190. var currentInd = this._indices.length;
  58191. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58192. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58193. // initialize the particle position
  58194. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58195. this._index += shape.length;
  58196. idx++;
  58197. this.nbParticles++;
  58198. this._shapeCounter++;
  58199. f += size;
  58200. }
  58201. return this;
  58202. };
  58203. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58204. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58205. var index = 0;
  58206. var idx = 0;
  58207. for (var p = 0; p < this.particles.length; p++) {
  58208. this._particle = this.particles[p];
  58209. this._shape = this._particle._model._shape;
  58210. if (this._particle.rotationQuaternion) {
  58211. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58212. }
  58213. else {
  58214. this._yaw = this._particle.rotation.y;
  58215. this._pitch = this._particle.rotation.x;
  58216. this._roll = this._particle.rotation.z;
  58217. this._quaternionRotationYPR();
  58218. }
  58219. this._quaternionToRotationMatrix();
  58220. this._rotMatrix.invertToRef(this._invertMatrix);
  58221. for (var pt = 0; pt < this._shape.length; pt++) {
  58222. idx = index + pt * 3;
  58223. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58224. this._fixedNormal32[idx] = this._normal.x;
  58225. this._fixedNormal32[idx + 1] = this._normal.y;
  58226. this._fixedNormal32[idx + 2] = this._normal.z;
  58227. }
  58228. index = idx + 3;
  58229. }
  58230. };
  58231. //reset copy
  58232. SolidParticleSystem.prototype._resetCopy = function () {
  58233. this._copy.position.x = 0;
  58234. this._copy.position.y = 0;
  58235. this._copy.position.z = 0;
  58236. this._copy.rotation.x = 0;
  58237. this._copy.rotation.y = 0;
  58238. this._copy.rotation.z = 0;
  58239. this._copy.rotationQuaternion = null;
  58240. this._copy.scaling.x = 1.0;
  58241. this._copy.scaling.y = 1.0;
  58242. this._copy.scaling.z = 1.0;
  58243. this._copy.uvs.x = 0;
  58244. this._copy.uvs.y = 0;
  58245. this._copy.uvs.z = 1.0;
  58246. this._copy.uvs.w = 1.0;
  58247. this._copy.color = null;
  58248. this._copy.translateFromPivot = false;
  58249. };
  58250. // _meshBuilder : inserts the shape model in the global SPS mesh
  58251. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58252. var i;
  58253. var u = 0;
  58254. var c = 0;
  58255. var n = 0;
  58256. this._resetCopy();
  58257. if (options && options.positionFunction) { // call to custom positionFunction
  58258. options.positionFunction(this._copy, idx, idxInShape);
  58259. this._mustUnrotateFixedNormals = true;
  58260. }
  58261. if (this._copy.rotationQuaternion) {
  58262. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58263. }
  58264. else {
  58265. this._yaw = this._copy.rotation.y;
  58266. this._pitch = this._copy.rotation.x;
  58267. this._roll = this._copy.rotation.z;
  58268. this._quaternionRotationYPR();
  58269. }
  58270. this._quaternionToRotationMatrix();
  58271. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58272. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58273. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58274. if (this._copy.translateFromPivot) {
  58275. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58276. }
  58277. else {
  58278. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58279. }
  58280. for (i = 0; i < shape.length; i++) {
  58281. this._vertex.x = shape[i].x;
  58282. this._vertex.y = shape[i].y;
  58283. this._vertex.z = shape[i].z;
  58284. if (options && options.vertexFunction) {
  58285. options.vertexFunction(this._copy, this._vertex, i);
  58286. }
  58287. this._vertex.x *= this._copy.scaling.x;
  58288. this._vertex.y *= this._copy.scaling.y;
  58289. this._vertex.z *= this._copy.scaling.z;
  58290. this._vertex.x -= this._scaledPivot.x;
  58291. this._vertex.y -= this._scaledPivot.y;
  58292. this._vertex.z -= this._scaledPivot.z;
  58293. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58294. this._rotated.addInPlace(this._pivotBackTranslation);
  58295. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58296. if (meshUV) {
  58297. 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);
  58298. u += 2;
  58299. }
  58300. if (this._copy.color) {
  58301. this._color = this._copy.color;
  58302. }
  58303. else if (meshCol && meshCol[c] !== undefined) {
  58304. this._color.r = meshCol[c];
  58305. this._color.g = meshCol[c + 1];
  58306. this._color.b = meshCol[c + 2];
  58307. this._color.a = meshCol[c + 3];
  58308. }
  58309. else {
  58310. this._color.r = 1.0;
  58311. this._color.g = 1.0;
  58312. this._color.b = 1.0;
  58313. this._color.a = 1.0;
  58314. }
  58315. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58316. c += 4;
  58317. if (!this.recomputeNormals && meshNor) {
  58318. this._normal.x = meshNor[n];
  58319. this._normal.y = meshNor[n + 1];
  58320. this._normal.z = meshNor[n + 2];
  58321. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58322. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58323. n += 3;
  58324. }
  58325. }
  58326. for (i = 0; i < meshInd.length; i++) {
  58327. var current_ind = p + meshInd[i];
  58328. indices.push(current_ind);
  58329. if (current_ind > 65535) {
  58330. this._needs32Bits = true;
  58331. }
  58332. }
  58333. if (this._pickable) {
  58334. var nbfaces = meshInd.length / 3;
  58335. for (i = 0; i < nbfaces; i++) {
  58336. this.pickedParticles.push({ idx: idx, faceId: i });
  58337. }
  58338. }
  58339. if (this._depthSort) {
  58340. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58341. }
  58342. return this._copy;
  58343. };
  58344. // returns a shape array from positions array
  58345. SolidParticleSystem.prototype._posToShape = function (positions) {
  58346. var shape = [];
  58347. for (var i = 0; i < positions.length; i += 3) {
  58348. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58349. }
  58350. return shape;
  58351. };
  58352. // returns a shapeUV array from a Vector4 uvs
  58353. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58354. var shapeUV = [];
  58355. if (uvs) {
  58356. for (var i = 0; i < uvs.length; i++)
  58357. shapeUV.push(uvs[i]);
  58358. }
  58359. return shapeUV;
  58360. };
  58361. // adds a new particle object in the particles array
  58362. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58363. if (bInfo === void 0) { bInfo = null; }
  58364. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58365. this.particles.push(sp);
  58366. return sp;
  58367. };
  58368. /**
  58369. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58370. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58371. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58372. * @param nb (positive integer) the number of particles to be created from this model
  58373. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58374. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58375. * @returns the number of shapes in the system
  58376. */
  58377. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58378. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58379. var meshInd = mesh.getIndices();
  58380. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58381. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58382. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58383. var bbInfo;
  58384. if (this._particlesIntersect) {
  58385. bbInfo = mesh.getBoundingInfo();
  58386. }
  58387. var shape = this._posToShape(meshPos);
  58388. var shapeUV = this._uvsToShapeUV(meshUV);
  58389. var posfunc = options ? options.positionFunction : null;
  58390. var vtxfunc = options ? options.vertexFunction : null;
  58391. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58392. // particles
  58393. var sp;
  58394. var currentCopy;
  58395. var idx = this.nbParticles;
  58396. for (var i = 0; i < nb; i++) {
  58397. var currentPos = this._positions.length;
  58398. var currentInd = this._indices.length;
  58399. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58400. if (this._updatable) {
  58401. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58402. sp.position.copyFrom(currentCopy.position);
  58403. sp.rotation.copyFrom(currentCopy.rotation);
  58404. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58405. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58406. }
  58407. if (currentCopy.color && sp.color) {
  58408. sp.color.copyFrom(currentCopy.color);
  58409. }
  58410. sp.scaling.copyFrom(currentCopy.scaling);
  58411. sp.uvs.copyFrom(currentCopy.uvs);
  58412. }
  58413. this._index += shape.length;
  58414. idx++;
  58415. }
  58416. this.nbParticles += nb;
  58417. this._shapeCounter++;
  58418. return this._shapeCounter - 1;
  58419. };
  58420. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58421. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58422. this._resetCopy();
  58423. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58424. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58425. }
  58426. if (this._copy.rotationQuaternion) {
  58427. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58428. }
  58429. else {
  58430. this._yaw = this._copy.rotation.y;
  58431. this._pitch = this._copy.rotation.x;
  58432. this._roll = this._copy.rotation.z;
  58433. this._quaternionRotationYPR();
  58434. }
  58435. this._quaternionToRotationMatrix();
  58436. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58437. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58438. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58439. if (this._copy.translateFromPivot) {
  58440. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58441. }
  58442. else {
  58443. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58444. }
  58445. this._shape = particle._model._shape;
  58446. for (var pt = 0; pt < this._shape.length; pt++) {
  58447. this._vertex.x = this._shape[pt].x;
  58448. this._vertex.y = this._shape[pt].y;
  58449. this._vertex.z = this._shape[pt].z;
  58450. if (particle._model._vertexFunction) {
  58451. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58452. }
  58453. this._vertex.x *= this._copy.scaling.x;
  58454. this._vertex.y *= this._copy.scaling.y;
  58455. this._vertex.z *= this._copy.scaling.z;
  58456. this._vertex.x -= this._scaledPivot.x;
  58457. this._vertex.y -= this._scaledPivot.y;
  58458. this._vertex.z -= this._scaledPivot.z;
  58459. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58460. this._rotated.addInPlace(this._pivotBackTranslation);
  58461. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58462. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58463. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58464. }
  58465. particle.position.x = 0.0;
  58466. particle.position.y = 0.0;
  58467. particle.position.z = 0.0;
  58468. particle.rotation.x = 0.0;
  58469. particle.rotation.y = 0.0;
  58470. particle.rotation.z = 0.0;
  58471. particle.rotationQuaternion = null;
  58472. particle.scaling.x = 1.0;
  58473. particle.scaling.y = 1.0;
  58474. particle.scaling.z = 1.0;
  58475. particle.uvs.x = 0.0;
  58476. particle.uvs.y = 0.0;
  58477. particle.uvs.z = 1.0;
  58478. particle.uvs.w = 1.0;
  58479. particle.pivot.x = 0.0;
  58480. particle.pivot.y = 0.0;
  58481. particle.pivot.z = 0.0;
  58482. particle.translateFromPivot = false;
  58483. particle.parentId = null;
  58484. };
  58485. /**
  58486. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58487. * @returns the SPS.
  58488. */
  58489. SolidParticleSystem.prototype.rebuildMesh = function () {
  58490. for (var p = 0; p < this.particles.length; p++) {
  58491. this._rebuildParticle(this.particles[p]);
  58492. }
  58493. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58494. return this;
  58495. };
  58496. /**
  58497. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58498. * This method calls `updateParticle()` for each particle of the SPS.
  58499. * For an animated SPS, it is usually called within the render loop.
  58500. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58501. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58502. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58503. * @returns the SPS.
  58504. */
  58505. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58506. if (start === void 0) { start = 0; }
  58507. if (end === void 0) { end = this.nbParticles - 1; }
  58508. if (update === void 0) { update = true; }
  58509. if (!this._updatable) {
  58510. return this;
  58511. }
  58512. // custom beforeUpdate
  58513. this.beforeUpdateParticles(start, end, update);
  58514. this._cam_axisX.x = 1.0;
  58515. this._cam_axisX.y = 0.0;
  58516. this._cam_axisX.z = 0.0;
  58517. this._cam_axisY.x = 0.0;
  58518. this._cam_axisY.y = 1.0;
  58519. this._cam_axisY.z = 0.0;
  58520. this._cam_axisZ.x = 0.0;
  58521. this._cam_axisZ.y = 0.0;
  58522. this._cam_axisZ.z = 1.0;
  58523. // cases when the World Matrix is to be computed first
  58524. if (this.billboard || this._depthSort) {
  58525. this.mesh.computeWorldMatrix(true);
  58526. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58527. }
  58528. // if the particles will always face the camera
  58529. if (this.billboard) {
  58530. // compute the camera position and un-rotate it by the current mesh rotation
  58531. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58532. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58533. this._cam_axisZ.normalize();
  58534. // same for camera up vector extracted from the cam view matrix
  58535. var view = this._camera.getViewMatrix(true);
  58536. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58537. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58538. this._cam_axisY.normalize();
  58539. this._cam_axisX.normalize();
  58540. }
  58541. // if depthSort, compute the camera global position in the mesh local system
  58542. if (this._depthSort) {
  58543. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58544. }
  58545. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58546. var idx = 0; // current position index in the global array positions32
  58547. var index = 0; // position start index in the global array positions32 of the current particle
  58548. var colidx = 0; // current color index in the global array colors32
  58549. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58550. var uvidx = 0; // current uv index in the global array uvs32
  58551. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58552. var pt = 0; // current index in the particle model shape
  58553. if (this.mesh.isFacetDataEnabled) {
  58554. this._computeBoundingBox = true;
  58555. }
  58556. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58557. if (this._computeBoundingBox) {
  58558. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58559. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58560. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58561. }
  58562. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58563. if (this.mesh._boundingInfo) {
  58564. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58565. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58566. }
  58567. }
  58568. }
  58569. // particle loop
  58570. index = this.particles[start]._pos;
  58571. var vpos = (index / 3) | 0;
  58572. colorIndex = vpos * 4;
  58573. uvIndex = vpos * 2;
  58574. for (var p = start; p <= end; p++) {
  58575. this._particle = this.particles[p];
  58576. this._shape = this._particle._model._shape;
  58577. this._shapeUV = this._particle._model._shapeUV;
  58578. // call to custom user function to update the particle properties
  58579. this.updateParticle(this._particle);
  58580. // camera-particle distance for depth sorting
  58581. if (this._depthSort && this._depthSortParticles) {
  58582. var dsp = this.depthSortedParticles[p];
  58583. dsp.ind = this._particle._ind;
  58584. dsp.indicesLength = this._particle._model._indicesLength;
  58585. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58586. }
  58587. // skip the computations for inactive or already invisible particles
  58588. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58589. // increment indexes for the next particle
  58590. pt = this._shape.length;
  58591. index += pt * 3;
  58592. colorIndex += pt * 4;
  58593. uvIndex += pt * 2;
  58594. continue;
  58595. }
  58596. if (this._particle.isVisible) {
  58597. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58598. this._particleHasParent = (this._particle.parentId !== null);
  58599. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58600. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58601. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58602. // particle rotation matrix
  58603. if (this.billboard) {
  58604. this._particle.rotation.x = 0.0;
  58605. this._particle.rotation.y = 0.0;
  58606. }
  58607. if (this._computeParticleRotation || this.billboard) {
  58608. if (this._particle.rotationQuaternion) {
  58609. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58610. }
  58611. else {
  58612. this._yaw = this._particle.rotation.y;
  58613. this._pitch = this._particle.rotation.x;
  58614. this._roll = this._particle.rotation.z;
  58615. this._quaternionRotationYPR();
  58616. }
  58617. this._quaternionToRotationMatrix();
  58618. }
  58619. if (this._particleHasParent) {
  58620. this._parent = this.particles[this._particle.parentId];
  58621. 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];
  58622. 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];
  58623. 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];
  58624. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58625. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58626. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58627. if (this._computeParticleRotation || this.billboard) {
  58628. 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];
  58629. 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];
  58630. 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];
  58631. 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];
  58632. 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];
  58633. 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];
  58634. 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];
  58635. 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];
  58636. 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];
  58637. }
  58638. }
  58639. else {
  58640. this._particle._globalPosition.x = this._particle.position.x;
  58641. this._particle._globalPosition.y = this._particle.position.y;
  58642. this._particle._globalPosition.z = this._particle.position.z;
  58643. if (this._computeParticleRotation || this.billboard) {
  58644. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58645. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58646. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58647. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58648. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58649. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58650. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58651. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58652. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58653. }
  58654. }
  58655. if (this._particle.translateFromPivot) {
  58656. this._pivotBackTranslation.x = 0.0;
  58657. this._pivotBackTranslation.y = 0.0;
  58658. this._pivotBackTranslation.z = 0.0;
  58659. }
  58660. else {
  58661. this._pivotBackTranslation.x = this._scaledPivot.x;
  58662. this._pivotBackTranslation.y = this._scaledPivot.y;
  58663. this._pivotBackTranslation.z = this._scaledPivot.z;
  58664. }
  58665. // particle vertex loop
  58666. for (pt = 0; pt < this._shape.length; pt++) {
  58667. idx = index + pt * 3;
  58668. colidx = colorIndex + pt * 4;
  58669. uvidx = uvIndex + pt * 2;
  58670. this._vertex.x = this._shape[pt].x;
  58671. this._vertex.y = this._shape[pt].y;
  58672. this._vertex.z = this._shape[pt].z;
  58673. if (this._computeParticleVertex) {
  58674. this.updateParticleVertex(this._particle, this._vertex, pt);
  58675. }
  58676. // positions
  58677. this._vertex.x *= this._particle.scaling.x;
  58678. this._vertex.y *= this._particle.scaling.y;
  58679. this._vertex.z *= this._particle.scaling.z;
  58680. this._vertex.x -= this._scaledPivot.x;
  58681. this._vertex.y -= this._scaledPivot.y;
  58682. this._vertex.z -= this._scaledPivot.z;
  58683. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58684. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58685. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58686. this._rotated.x += this._pivotBackTranslation.x;
  58687. this._rotated.y += this._pivotBackTranslation.y;
  58688. this._rotated.z += this._pivotBackTranslation.z;
  58689. 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;
  58690. 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;
  58691. 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;
  58692. if (this._computeBoundingBox) {
  58693. if (this._positions32[idx] < this._minimum.x) {
  58694. this._minimum.x = this._positions32[idx];
  58695. }
  58696. if (this._positions32[idx] > this._maximum.x) {
  58697. this._maximum.x = this._positions32[idx];
  58698. }
  58699. if (this._positions32[idx + 1] < this._minimum.y) {
  58700. this._minimum.y = this._positions32[idx + 1];
  58701. }
  58702. if (this._positions32[idx + 1] > this._maximum.y) {
  58703. this._maximum.y = this._positions32[idx + 1];
  58704. }
  58705. if (this._positions32[idx + 2] < this._minimum.z) {
  58706. this._minimum.z = this._positions32[idx + 2];
  58707. }
  58708. if (this._positions32[idx + 2] > this._maximum.z) {
  58709. this._maximum.z = this._positions32[idx + 2];
  58710. }
  58711. }
  58712. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58713. if (!this._computeParticleVertex) {
  58714. this._normal.x = this._fixedNormal32[idx];
  58715. this._normal.y = this._fixedNormal32[idx + 1];
  58716. this._normal.z = this._fixedNormal32[idx + 2];
  58717. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58718. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58719. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58720. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58721. 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;
  58722. 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;
  58723. }
  58724. if (this._computeParticleColor && this._particle.color) {
  58725. this._colors32[colidx] = this._particle.color.r;
  58726. this._colors32[colidx + 1] = this._particle.color.g;
  58727. this._colors32[colidx + 2] = this._particle.color.b;
  58728. this._colors32[colidx + 3] = this._particle.color.a;
  58729. }
  58730. if (this._computeParticleTexture) {
  58731. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58732. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58733. }
  58734. }
  58735. }
  58736. // particle just set invisible : scaled to zero and positioned at the origin
  58737. else {
  58738. this._particle._stillInvisible = true; // mark the particle as invisible
  58739. for (pt = 0; pt < this._shape.length; pt++) {
  58740. idx = index + pt * 3;
  58741. colidx = colorIndex + pt * 4;
  58742. uvidx = uvIndex + pt * 2;
  58743. this._positions32[idx] = 0.0;
  58744. this._positions32[idx + 1] = 0.0;
  58745. this._positions32[idx + 2] = 0.0;
  58746. this._normals32[idx] = 0.0;
  58747. this._normals32[idx + 1] = 0.0;
  58748. this._normals32[idx + 2] = 0.0;
  58749. if (this._computeParticleColor && this._particle.color) {
  58750. this._colors32[colidx] = this._particle.color.r;
  58751. this._colors32[colidx + 1] = this._particle.color.g;
  58752. this._colors32[colidx + 2] = this._particle.color.b;
  58753. this._colors32[colidx + 3] = this._particle.color.a;
  58754. }
  58755. if (this._computeParticleTexture) {
  58756. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58757. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58758. }
  58759. }
  58760. }
  58761. // if the particle intersections must be computed : update the bbInfo
  58762. if (this._particlesIntersect) {
  58763. var bInfo = this._particle._boundingInfo;
  58764. var bBox = bInfo.boundingBox;
  58765. var bSphere = bInfo.boundingSphere;
  58766. if (!this._bSphereOnly) {
  58767. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58768. for (var b = 0; b < bBox.vectors.length; b++) {
  58769. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58770. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58771. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58772. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58773. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58774. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58775. 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;
  58776. 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;
  58777. 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;
  58778. }
  58779. bBox._update(this.mesh._worldMatrix);
  58780. }
  58781. // place and scale the particle bouding sphere in the SPS local system, then update it
  58782. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58783. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58784. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58785. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58786. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58787. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58788. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58789. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58790. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58791. 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));
  58792. bSphere._update(this.mesh._worldMatrix);
  58793. }
  58794. // increment indexes for the next particle
  58795. index = idx + 3;
  58796. colorIndex = colidx + 4;
  58797. uvIndex = uvidx + 2;
  58798. }
  58799. // if the VBO must be updated
  58800. if (update) {
  58801. if (this._computeParticleColor) {
  58802. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58803. }
  58804. if (this._computeParticleTexture) {
  58805. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58806. }
  58807. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58808. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58809. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58810. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58811. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58812. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58813. for (var i = 0; i < this._normals32.length; i++) {
  58814. this._fixedNormal32[i] = this._normals32[i];
  58815. }
  58816. }
  58817. if (!this.mesh.areNormalsFrozen) {
  58818. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58819. }
  58820. }
  58821. if (this._depthSort && this._depthSortParticles) {
  58822. this.depthSortedParticles.sort(this._depthSortFunction);
  58823. var dspl = this.depthSortedParticles.length;
  58824. var sorted = 0;
  58825. var lind = 0;
  58826. var sind = 0;
  58827. var sid = 0;
  58828. for (sorted = 0; sorted < dspl; sorted++) {
  58829. lind = this.depthSortedParticles[sorted].indicesLength;
  58830. sind = this.depthSortedParticles[sorted].ind;
  58831. for (var i = 0; i < lind; i++) {
  58832. this._indices32[sid] = this._indices[sind + i];
  58833. sid++;
  58834. }
  58835. }
  58836. this.mesh.updateIndices(this._indices32);
  58837. }
  58838. }
  58839. if (this._computeBoundingBox) {
  58840. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58841. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58842. }
  58843. this.afterUpdateParticles(start, end, update);
  58844. return this;
  58845. };
  58846. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58847. this._halfroll = this._roll * 0.5;
  58848. this._halfpitch = this._pitch * 0.5;
  58849. this._halfyaw = this._yaw * 0.5;
  58850. this._sinRoll = Math.sin(this._halfroll);
  58851. this._cosRoll = Math.cos(this._halfroll);
  58852. this._sinPitch = Math.sin(this._halfpitch);
  58853. this._cosPitch = Math.cos(this._halfpitch);
  58854. this._sinYaw = Math.sin(this._halfyaw);
  58855. this._cosYaw = Math.cos(this._halfyaw);
  58856. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58857. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58858. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58859. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58860. };
  58861. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58862. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58863. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  58864. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  58865. this._rotMatrix.m[3] = 0;
  58866. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  58867. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  58868. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  58869. this._rotMatrix.m[7] = 0;
  58870. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  58871. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  58872. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  58873. this._rotMatrix.m[11] = 0;
  58874. this._rotMatrix.m[12] = 0;
  58875. this._rotMatrix.m[13] = 0;
  58876. this._rotMatrix.m[14] = 0;
  58877. this._rotMatrix.m[15] = 1.0;
  58878. };
  58879. /**
  58880. * Disposes the SPS.
  58881. */
  58882. SolidParticleSystem.prototype.dispose = function () {
  58883. this.mesh.dispose();
  58884. this.vars = null;
  58885. // drop references to internal big arrays for the GC
  58886. this._positions = null;
  58887. this._indices = null;
  58888. this._normals = null;
  58889. this._uvs = null;
  58890. this._colors = null;
  58891. this._indices32 = null;
  58892. this._positions32 = null;
  58893. this._normals32 = null;
  58894. this._fixedNormal32 = null;
  58895. this._uvs32 = null;
  58896. this._colors32 = null;
  58897. this.pickedParticles = null;
  58898. };
  58899. /**
  58900. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  58901. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58902. * @returns the SPS.
  58903. */
  58904. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  58905. if (!this._isVisibilityBoxLocked) {
  58906. this.mesh.refreshBoundingInfo();
  58907. }
  58908. return this;
  58909. };
  58910. /**
  58911. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  58912. * @param size the size (float) of the visibility box
  58913. * note : this doesn't lock the SPS mesh bounding box.
  58914. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58915. */
  58916. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  58917. var vis = size / 2;
  58918. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  58919. };
  58920. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  58921. /**
  58922. * Gets whether the SPS as always visible or not
  58923. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58924. */
  58925. get: function () {
  58926. return this._alwaysVisible;
  58927. },
  58928. /**
  58929. * Sets the SPS as always visible or not
  58930. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58931. */
  58932. set: function (val) {
  58933. this._alwaysVisible = val;
  58934. this.mesh.alwaysSelectAsActiveMesh = val;
  58935. },
  58936. enumerable: true,
  58937. configurable: true
  58938. });
  58939. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  58940. /**
  58941. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58942. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58943. */
  58944. get: function () {
  58945. return this._isVisibilityBoxLocked;
  58946. },
  58947. /**
  58948. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  58949. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  58950. */
  58951. set: function (val) {
  58952. this._isVisibilityBoxLocked = val;
  58953. var boundingInfo = this.mesh.getBoundingInfo();
  58954. boundingInfo.isLocked = val;
  58955. },
  58956. enumerable: true,
  58957. configurable: true
  58958. });
  58959. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  58960. /**
  58961. * Gets if `setParticles()` computes the particle rotations or not.
  58962. * Default value : true. The SPS is faster when it's set to false.
  58963. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58964. */
  58965. get: function () {
  58966. return this._computeParticleRotation;
  58967. },
  58968. /**
  58969. * Tells to `setParticles()` to compute the particle rotations or not.
  58970. * Default value : true. The SPS is faster when it's set to false.
  58971. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  58972. */
  58973. set: function (val) {
  58974. this._computeParticleRotation = val;
  58975. },
  58976. enumerable: true,
  58977. configurable: true
  58978. });
  58979. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  58980. /**
  58981. * Gets if `setParticles()` computes the particle colors or not.
  58982. * Default value : true. The SPS is faster when it's set to false.
  58983. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58984. */
  58985. get: function () {
  58986. return this._computeParticleColor;
  58987. },
  58988. /**
  58989. * Tells to `setParticles()` to compute the particle colors or not.
  58990. * Default value : true. The SPS is faster when it's set to false.
  58991. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  58992. */
  58993. set: function (val) {
  58994. this._computeParticleColor = val;
  58995. },
  58996. enumerable: true,
  58997. configurable: true
  58998. });
  58999. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59000. /**
  59001. * Gets if `setParticles()` computes the particle textures or not.
  59002. * Default value : true. The SPS is faster when it's set to false.
  59003. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59004. */
  59005. get: function () {
  59006. return this._computeParticleTexture;
  59007. },
  59008. set: function (val) {
  59009. this._computeParticleTexture = val;
  59010. },
  59011. enumerable: true,
  59012. configurable: true
  59013. });
  59014. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59015. /**
  59016. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59017. * Default value : false. The SPS is faster when it's set to false.
  59018. * Note : the particle custom vertex positions aren't stored values.
  59019. */
  59020. get: function () {
  59021. return this._computeParticleVertex;
  59022. },
  59023. /**
  59024. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59025. * Default value : false. The SPS is faster when it's set to false.
  59026. * Note : the particle custom vertex positions aren't stored values.
  59027. */
  59028. set: function (val) {
  59029. this._computeParticleVertex = val;
  59030. },
  59031. enumerable: true,
  59032. configurable: true
  59033. });
  59034. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59035. /**
  59036. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59037. */
  59038. get: function () {
  59039. return this._computeBoundingBox;
  59040. },
  59041. /**
  59042. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59043. */
  59044. set: function (val) {
  59045. this._computeBoundingBox = val;
  59046. },
  59047. enumerable: true,
  59048. configurable: true
  59049. });
  59050. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59051. /**
  59052. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59053. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59054. * Default : `true`
  59055. */
  59056. get: function () {
  59057. return this._depthSortParticles;
  59058. },
  59059. /**
  59060. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59061. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59062. * Default : `true`
  59063. */
  59064. set: function (val) {
  59065. this._depthSortParticles = val;
  59066. },
  59067. enumerable: true,
  59068. configurable: true
  59069. });
  59070. // =======================================================================
  59071. // Particle behavior logic
  59072. // these following methods may be overwritten by the user to fit his needs
  59073. /**
  59074. * This function does nothing. It may be overwritten to set all the particle first values.
  59075. * The SPS doesn't call this function, you may have to call it by your own.
  59076. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59077. */
  59078. SolidParticleSystem.prototype.initParticles = function () {
  59079. };
  59080. /**
  59081. * This function does nothing. It may be overwritten to recycle a particle.
  59082. * The SPS doesn't call this function, you may have to call it by your own.
  59083. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59084. * @param particle The particle to recycle
  59085. * @returns the recycled particle
  59086. */
  59087. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59088. return particle;
  59089. };
  59090. /**
  59091. * Updates a particle : this function should be overwritten by the user.
  59092. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59093. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59094. * @example : just set a particle position or velocity and recycle conditions
  59095. * @param particle The particle to update
  59096. * @returns the updated particle
  59097. */
  59098. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59099. return particle;
  59100. };
  59101. /**
  59102. * Updates a vertex of a particle : it can be overwritten by the user.
  59103. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59104. * @param particle the current particle
  59105. * @param vertex the current index of the current particle
  59106. * @param pt the index of the current vertex in the particle shape
  59107. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59108. * @example : just set a vertex particle position
  59109. * @returns the updated vertex
  59110. */
  59111. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59112. return vertex;
  59113. };
  59114. /**
  59115. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59116. * This does nothing and may be overwritten by the user.
  59117. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59118. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59119. * @param update the boolean update value actually passed to setParticles()
  59120. */
  59121. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59122. };
  59123. /**
  59124. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59125. * This will be passed three parameters.
  59126. * This does nothing and may be overwritten by the user.
  59127. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59128. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59129. * @param update the boolean update value actually passed to setParticles()
  59130. */
  59131. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59132. };
  59133. return SolidParticleSystem;
  59134. }());
  59135. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59136. })(BABYLON || (BABYLON = {}));
  59137. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59138. var BABYLON;
  59139. (function (BABYLON) {
  59140. var ShaderMaterial = /** @class */ (function (_super) {
  59141. __extends(ShaderMaterial, _super);
  59142. function ShaderMaterial(name, scene, shaderPath, options) {
  59143. var _this = _super.call(this, name, scene) || this;
  59144. _this._textures = {};
  59145. _this._textureArrays = {};
  59146. _this._floats = {};
  59147. _this._ints = {};
  59148. _this._floatsArrays = {};
  59149. _this._colors3 = {};
  59150. _this._colors3Arrays = {};
  59151. _this._colors4 = {};
  59152. _this._vectors2 = {};
  59153. _this._vectors3 = {};
  59154. _this._vectors4 = {};
  59155. _this._matrices = {};
  59156. _this._matrices3x3 = {};
  59157. _this._matrices2x2 = {};
  59158. _this._vectors2Arrays = {};
  59159. _this._vectors3Arrays = {};
  59160. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59161. _this._shaderPath = shaderPath;
  59162. options.needAlphaBlending = options.needAlphaBlending || false;
  59163. options.needAlphaTesting = options.needAlphaTesting || false;
  59164. options.attributes = options.attributes || ["position", "normal", "uv"];
  59165. options.uniforms = options.uniforms || ["worldViewProjection"];
  59166. options.uniformBuffers = options.uniformBuffers || [];
  59167. options.samplers = options.samplers || [];
  59168. options.defines = options.defines || [];
  59169. _this._options = options;
  59170. return _this;
  59171. }
  59172. ShaderMaterial.prototype.getClassName = function () {
  59173. return "ShaderMaterial";
  59174. };
  59175. ShaderMaterial.prototype.needAlphaBlending = function () {
  59176. return this._options.needAlphaBlending;
  59177. };
  59178. ShaderMaterial.prototype.needAlphaTesting = function () {
  59179. return this._options.needAlphaTesting;
  59180. };
  59181. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59182. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59183. this._options.uniforms.push(uniformName);
  59184. }
  59185. };
  59186. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59187. if (this._options.samplers.indexOf(name) === -1) {
  59188. this._options.samplers.push(name);
  59189. }
  59190. this._textures[name] = texture;
  59191. return this;
  59192. };
  59193. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59194. if (this._options.samplers.indexOf(name) === -1) {
  59195. this._options.samplers.push(name);
  59196. }
  59197. this._checkUniform(name);
  59198. this._textureArrays[name] = textures;
  59199. return this;
  59200. };
  59201. ShaderMaterial.prototype.setFloat = function (name, value) {
  59202. this._checkUniform(name);
  59203. this._floats[name] = value;
  59204. return this;
  59205. };
  59206. ShaderMaterial.prototype.setInt = function (name, value) {
  59207. this._checkUniform(name);
  59208. this._ints[name] = value;
  59209. return this;
  59210. };
  59211. ShaderMaterial.prototype.setFloats = function (name, value) {
  59212. this._checkUniform(name);
  59213. this._floatsArrays[name] = value;
  59214. return this;
  59215. };
  59216. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59217. this._checkUniform(name);
  59218. this._colors3[name] = value;
  59219. return this;
  59220. };
  59221. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59222. this._checkUniform(name);
  59223. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59224. color.toArray(arr, arr.length);
  59225. return arr;
  59226. }, []);
  59227. return this;
  59228. };
  59229. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59230. this._checkUniform(name);
  59231. this._colors4[name] = value;
  59232. return this;
  59233. };
  59234. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59235. this._checkUniform(name);
  59236. this._vectors2[name] = value;
  59237. return this;
  59238. };
  59239. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59240. this._checkUniform(name);
  59241. this._vectors3[name] = value;
  59242. return this;
  59243. };
  59244. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59245. this._checkUniform(name);
  59246. this._vectors4[name] = value;
  59247. return this;
  59248. };
  59249. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59250. this._checkUniform(name);
  59251. this._matrices[name] = value;
  59252. return this;
  59253. };
  59254. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59255. this._checkUniform(name);
  59256. this._matrices3x3[name] = value;
  59257. return this;
  59258. };
  59259. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59260. this._checkUniform(name);
  59261. this._matrices2x2[name] = value;
  59262. return this;
  59263. };
  59264. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59265. this._checkUniform(name);
  59266. this._vectors2Arrays[name] = value;
  59267. return this;
  59268. };
  59269. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59270. this._checkUniform(name);
  59271. this._vectors3Arrays[name] = value;
  59272. return this;
  59273. };
  59274. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59275. if (!mesh) {
  59276. return true;
  59277. }
  59278. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59279. return false;
  59280. }
  59281. return false;
  59282. };
  59283. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59284. var scene = this.getScene();
  59285. var engine = scene.getEngine();
  59286. if (!this.checkReadyOnEveryCall) {
  59287. if (this._renderId === scene.getRenderId()) {
  59288. if (this._checkCache(scene, mesh, useInstances)) {
  59289. return true;
  59290. }
  59291. }
  59292. }
  59293. // Instances
  59294. var defines = [];
  59295. var attribs = [];
  59296. var fallbacks = new BABYLON.EffectFallbacks();
  59297. if (useInstances) {
  59298. defines.push("#define INSTANCES");
  59299. }
  59300. for (var index = 0; index < this._options.defines.length; index++) {
  59301. defines.push(this._options.defines[index]);
  59302. }
  59303. for (var index = 0; index < this._options.attributes.length; index++) {
  59304. attribs.push(this._options.attributes[index]);
  59305. }
  59306. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59307. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59308. defines.push("#define VERTEXCOLOR");
  59309. }
  59310. // Bones
  59311. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59312. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59313. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59314. if (mesh.numBoneInfluencers > 4) {
  59315. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59316. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59317. }
  59318. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59319. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59320. fallbacks.addCPUSkinningFallback(0, mesh);
  59321. if (this._options.uniforms.indexOf("mBones") === -1) {
  59322. this._options.uniforms.push("mBones");
  59323. }
  59324. }
  59325. else {
  59326. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59327. }
  59328. // Textures
  59329. for (var name in this._textures) {
  59330. if (!this._textures[name].isReady()) {
  59331. return false;
  59332. }
  59333. }
  59334. // Alpha test
  59335. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59336. defines.push("#define ALPHATEST");
  59337. }
  59338. var previousEffect = this._effect;
  59339. var join = defines.join("\n");
  59340. this._effect = engine.createEffect(this._shaderPath, {
  59341. attributes: attribs,
  59342. uniformsNames: this._options.uniforms,
  59343. uniformBuffersNames: this._options.uniformBuffers,
  59344. samplers: this._options.samplers,
  59345. defines: join,
  59346. fallbacks: fallbacks,
  59347. onCompiled: this.onCompiled,
  59348. onError: this.onError
  59349. }, engine);
  59350. if (!this._effect.isReady()) {
  59351. return false;
  59352. }
  59353. if (previousEffect !== this._effect) {
  59354. scene.resetCachedMaterial();
  59355. }
  59356. this._renderId = scene.getRenderId();
  59357. return true;
  59358. };
  59359. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59360. var scene = this.getScene();
  59361. if (!this._effect) {
  59362. return;
  59363. }
  59364. if (this._options.uniforms.indexOf("world") !== -1) {
  59365. this._effect.setMatrix("world", world);
  59366. }
  59367. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59368. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59369. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59370. }
  59371. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59372. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59373. }
  59374. };
  59375. ShaderMaterial.prototype.bind = function (world, mesh) {
  59376. // Std values
  59377. this.bindOnlyWorldMatrix(world);
  59378. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59379. if (this._options.uniforms.indexOf("view") !== -1) {
  59380. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59381. }
  59382. if (this._options.uniforms.indexOf("projection") !== -1) {
  59383. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59384. }
  59385. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59386. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59387. }
  59388. // Bones
  59389. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59390. var name;
  59391. // Texture
  59392. for (name in this._textures) {
  59393. this._effect.setTexture(name, this._textures[name]);
  59394. }
  59395. // Texture arrays
  59396. for (name in this._textureArrays) {
  59397. this._effect.setTextureArray(name, this._textureArrays[name]);
  59398. }
  59399. // Int
  59400. for (name in this._ints) {
  59401. this._effect.setInt(name, this._ints[name]);
  59402. }
  59403. // Float
  59404. for (name in this._floats) {
  59405. this._effect.setFloat(name, this._floats[name]);
  59406. }
  59407. // Floats
  59408. for (name in this._floatsArrays) {
  59409. this._effect.setArray(name, this._floatsArrays[name]);
  59410. }
  59411. // Color3
  59412. for (name in this._colors3) {
  59413. this._effect.setColor3(name, this._colors3[name]);
  59414. }
  59415. for (name in this._colors3Arrays) {
  59416. this._effect.setArray3(name, this._colors3Arrays[name]);
  59417. }
  59418. // Color4
  59419. for (name in this._colors4) {
  59420. var color = this._colors4[name];
  59421. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59422. }
  59423. // Vector2
  59424. for (name in this._vectors2) {
  59425. this._effect.setVector2(name, this._vectors2[name]);
  59426. }
  59427. // Vector3
  59428. for (name in this._vectors3) {
  59429. this._effect.setVector3(name, this._vectors3[name]);
  59430. }
  59431. // Vector4
  59432. for (name in this._vectors4) {
  59433. this._effect.setVector4(name, this._vectors4[name]);
  59434. }
  59435. // Matrix
  59436. for (name in this._matrices) {
  59437. this._effect.setMatrix(name, this._matrices[name]);
  59438. }
  59439. // Matrix 3x3
  59440. for (name in this._matrices3x3) {
  59441. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59442. }
  59443. // Matrix 2x2
  59444. for (name in this._matrices2x2) {
  59445. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59446. }
  59447. // Vector2Array
  59448. for (name in this._vectors2Arrays) {
  59449. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59450. }
  59451. // Vector3Array
  59452. for (name in this._vectors3Arrays) {
  59453. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59454. }
  59455. }
  59456. this._afterBind(mesh);
  59457. };
  59458. ShaderMaterial.prototype.getActiveTextures = function () {
  59459. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59460. for (var name in this._textures) {
  59461. activeTextures.push(this._textures[name]);
  59462. }
  59463. for (var name in this._textureArrays) {
  59464. var array = this._textureArrays[name];
  59465. for (var index = 0; index < array.length; index++) {
  59466. activeTextures.push(array[index]);
  59467. }
  59468. }
  59469. return activeTextures;
  59470. };
  59471. ShaderMaterial.prototype.hasTexture = function (texture) {
  59472. if (_super.prototype.hasTexture.call(this, texture)) {
  59473. return true;
  59474. }
  59475. for (var name in this._textures) {
  59476. if (this._textures[name] === texture) {
  59477. return true;
  59478. }
  59479. }
  59480. for (var name in this._textureArrays) {
  59481. var array = this._textureArrays[name];
  59482. for (var index = 0; index < array.length; index++) {
  59483. if (array[index] === texture) {
  59484. return true;
  59485. }
  59486. }
  59487. }
  59488. return false;
  59489. };
  59490. ShaderMaterial.prototype.clone = function (name) {
  59491. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59492. return newShaderMaterial;
  59493. };
  59494. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59495. if (forceDisposeTextures) {
  59496. var name;
  59497. for (name in this._textures) {
  59498. this._textures[name].dispose();
  59499. }
  59500. for (name in this._textureArrays) {
  59501. var array = this._textureArrays[name];
  59502. for (var index = 0; index < array.length; index++) {
  59503. array[index].dispose();
  59504. }
  59505. }
  59506. }
  59507. this._textures = {};
  59508. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59509. };
  59510. ShaderMaterial.prototype.serialize = function () {
  59511. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59512. serializationObject.customType = "BABYLON.ShaderMaterial";
  59513. serializationObject.options = this._options;
  59514. serializationObject.shaderPath = this._shaderPath;
  59515. var name;
  59516. // Texture
  59517. serializationObject.textures = {};
  59518. for (name in this._textures) {
  59519. serializationObject.textures[name] = this._textures[name].serialize();
  59520. }
  59521. // Texture arrays
  59522. serializationObject.textureArrays = {};
  59523. for (name in this._textureArrays) {
  59524. serializationObject.textureArrays[name] = [];
  59525. var array = this._textureArrays[name];
  59526. for (var index = 0; index < array.length; index++) {
  59527. serializationObject.textureArrays[name].push(array[index].serialize());
  59528. }
  59529. }
  59530. // Float
  59531. serializationObject.floats = {};
  59532. for (name in this._floats) {
  59533. serializationObject.floats[name] = this._floats[name];
  59534. }
  59535. // Float s
  59536. serializationObject.FloatArrays = {};
  59537. for (name in this._floatsArrays) {
  59538. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59539. }
  59540. // Color3
  59541. serializationObject.colors3 = {};
  59542. for (name in this._colors3) {
  59543. serializationObject.colors3[name] = this._colors3[name].asArray();
  59544. }
  59545. // Color3 array
  59546. serializationObject.colors3Arrays = {};
  59547. for (name in this._colors3Arrays) {
  59548. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59549. }
  59550. // Color4
  59551. serializationObject.colors4 = {};
  59552. for (name in this._colors4) {
  59553. serializationObject.colors4[name] = this._colors4[name].asArray();
  59554. }
  59555. // Vector2
  59556. serializationObject.vectors2 = {};
  59557. for (name in this._vectors2) {
  59558. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59559. }
  59560. // Vector3
  59561. serializationObject.vectors3 = {};
  59562. for (name in this._vectors3) {
  59563. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59564. }
  59565. // Vector4
  59566. serializationObject.vectors4 = {};
  59567. for (name in this._vectors4) {
  59568. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59569. }
  59570. // Matrix
  59571. serializationObject.matrices = {};
  59572. for (name in this._matrices) {
  59573. serializationObject.matrices[name] = this._matrices[name].asArray();
  59574. }
  59575. // Matrix 3x3
  59576. serializationObject.matrices3x3 = {};
  59577. for (name in this._matrices3x3) {
  59578. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59579. }
  59580. // Matrix 2x2
  59581. serializationObject.matrices2x2 = {};
  59582. for (name in this._matrices2x2) {
  59583. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59584. }
  59585. // Vector2Array
  59586. serializationObject.vectors2Arrays = {};
  59587. for (name in this._vectors2Arrays) {
  59588. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59589. }
  59590. // Vector3Array
  59591. serializationObject.vectors3Arrays = {};
  59592. for (name in this._vectors3Arrays) {
  59593. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59594. }
  59595. return serializationObject;
  59596. };
  59597. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59598. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59599. var name;
  59600. // Texture
  59601. for (name in source.textures) {
  59602. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59603. }
  59604. // Texture arrays
  59605. for (name in source.textureArrays) {
  59606. var array = source.textureArrays[name];
  59607. var textureArray = new Array();
  59608. for (var index = 0; index < array.length; index++) {
  59609. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59610. }
  59611. material.setTextureArray(name, textureArray);
  59612. }
  59613. // Float
  59614. for (name in source.floats) {
  59615. material.setFloat(name, source.floats[name]);
  59616. }
  59617. // Float s
  59618. for (name in source.floatsArrays) {
  59619. material.setFloats(name, source.floatsArrays[name]);
  59620. }
  59621. // Color3
  59622. for (name in source.colors3) {
  59623. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59624. }
  59625. // Color3 arrays
  59626. for (name in source.colors3Arrays) {
  59627. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59628. if (i % 3 === 0) {
  59629. arr.push([num]);
  59630. }
  59631. else {
  59632. arr[arr.length - 1].push(num);
  59633. }
  59634. return arr;
  59635. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59636. material.setColor3Array(name, colors);
  59637. }
  59638. // Color4
  59639. for (name in source.colors4) {
  59640. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59641. }
  59642. // Vector2
  59643. for (name in source.vectors2) {
  59644. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59645. }
  59646. // Vector3
  59647. for (name in source.vectors3) {
  59648. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59649. }
  59650. // Vector4
  59651. for (name in source.vectors4) {
  59652. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59653. }
  59654. // Matrix
  59655. for (name in source.matrices) {
  59656. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59657. }
  59658. // Matrix 3x3
  59659. for (name in source.matrices3x3) {
  59660. material.setMatrix3x3(name, source.matrices3x3[name]);
  59661. }
  59662. // Matrix 2x2
  59663. for (name in source.matrices2x2) {
  59664. material.setMatrix2x2(name, source.matrices2x2[name]);
  59665. }
  59666. // Vector2Array
  59667. for (name in source.vectors2Arrays) {
  59668. material.setArray2(name, source.vectors2Arrays[name]);
  59669. }
  59670. // Vector3Array
  59671. for (name in source.vectors3Arrays) {
  59672. material.setArray3(name, source.vectors3Arrays[name]);
  59673. }
  59674. return material;
  59675. };
  59676. return ShaderMaterial;
  59677. }(BABYLON.Material));
  59678. BABYLON.ShaderMaterial = ShaderMaterial;
  59679. })(BABYLON || (BABYLON = {}));
  59680. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59681. var BABYLON;
  59682. (function (BABYLON) {
  59683. var GroundMesh = /** @class */ (function (_super) {
  59684. __extends(GroundMesh, _super);
  59685. function GroundMesh(name, scene) {
  59686. var _this = _super.call(this, name, scene) || this;
  59687. _this.generateOctree = false;
  59688. return _this;
  59689. }
  59690. GroundMesh.prototype.getClassName = function () {
  59691. return "GroundMesh";
  59692. };
  59693. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59694. get: function () {
  59695. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59696. },
  59697. enumerable: true,
  59698. configurable: true
  59699. });
  59700. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59701. get: function () {
  59702. return this._subdivisionsX;
  59703. },
  59704. enumerable: true,
  59705. configurable: true
  59706. });
  59707. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59708. get: function () {
  59709. return this._subdivisionsY;
  59710. },
  59711. enumerable: true,
  59712. configurable: true
  59713. });
  59714. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59715. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59716. this._subdivisionsX = chunksCount;
  59717. this._subdivisionsY = chunksCount;
  59718. this.subdivide(chunksCount);
  59719. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59720. };
  59721. /**
  59722. * Returns a height (y) value in the Worl system :
  59723. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59724. * Returns the ground y position if (x, z) are outside the ground surface.
  59725. */
  59726. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59727. var world = this.getWorldMatrix();
  59728. var invMat = BABYLON.Tmp.Matrix[5];
  59729. world.invertToRef(invMat);
  59730. var tmpVect = BABYLON.Tmp.Vector3[8];
  59731. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59732. x = tmpVect.x;
  59733. z = tmpVect.z;
  59734. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59735. return this.position.y;
  59736. }
  59737. if (!this._heightQuads || this._heightQuads.length == 0) {
  59738. this._initHeightQuads();
  59739. this._computeHeightQuads();
  59740. }
  59741. var facet = this._getFacetAt(x, z);
  59742. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59743. // return y in the World system
  59744. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59745. return tmpVect.y;
  59746. };
  59747. /**
  59748. * Returns a normalized vector (Vector3) orthogonal to the ground
  59749. * at the ground coordinates (x, z) expressed in the World system.
  59750. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59751. */
  59752. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59753. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59754. this.getNormalAtCoordinatesToRef(x, z, normal);
  59755. return normal;
  59756. };
  59757. /**
  59758. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59759. * at the ground coordinates (x, z) expressed in the World system.
  59760. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59761. * Returns the GroundMesh.
  59762. */
  59763. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59764. var world = this.getWorldMatrix();
  59765. var tmpMat = BABYLON.Tmp.Matrix[5];
  59766. world.invertToRef(tmpMat);
  59767. var tmpVect = BABYLON.Tmp.Vector3[8];
  59768. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59769. x = tmpVect.x;
  59770. z = tmpVect.z;
  59771. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59772. return this;
  59773. }
  59774. if (!this._heightQuads || this._heightQuads.length == 0) {
  59775. this._initHeightQuads();
  59776. this._computeHeightQuads();
  59777. }
  59778. var facet = this._getFacetAt(x, z);
  59779. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59780. return this;
  59781. };
  59782. /**
  59783. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59784. * if the ground has been updated.
  59785. * This can be used in the render loop.
  59786. * Returns the GroundMesh.
  59787. */
  59788. GroundMesh.prototype.updateCoordinateHeights = function () {
  59789. if (!this._heightQuads || this._heightQuads.length == 0) {
  59790. this._initHeightQuads();
  59791. }
  59792. this._computeHeightQuads();
  59793. return this;
  59794. };
  59795. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59796. GroundMesh.prototype._getFacetAt = function (x, z) {
  59797. // retrieve col and row from x, z coordinates in the ground local system
  59798. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59799. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59800. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59801. var facet;
  59802. if (z < quad.slope.x * x + quad.slope.y) {
  59803. facet = quad.facet1;
  59804. }
  59805. else {
  59806. facet = quad.facet2;
  59807. }
  59808. return facet;
  59809. };
  59810. // Creates and populates the heightMap array with "facet" elements :
  59811. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59812. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59813. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59814. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59815. // Returns the GroundMesh.
  59816. GroundMesh.prototype._initHeightQuads = function () {
  59817. var subdivisionsX = this._subdivisionsX;
  59818. var subdivisionsY = this._subdivisionsY;
  59819. this._heightQuads = new Array();
  59820. for (var row = 0; row < subdivisionsY; row++) {
  59821. for (var col = 0; col < subdivisionsX; col++) {
  59822. 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) };
  59823. this._heightQuads[row * subdivisionsX + col] = quad;
  59824. }
  59825. }
  59826. return this;
  59827. };
  59828. // Compute each quad element values and update the the heightMap array :
  59829. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59830. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59831. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59832. // Returns the GroundMesh.
  59833. GroundMesh.prototype._computeHeightQuads = function () {
  59834. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59835. if (!positions) {
  59836. return this;
  59837. }
  59838. var v1 = BABYLON.Tmp.Vector3[3];
  59839. var v2 = BABYLON.Tmp.Vector3[2];
  59840. var v3 = BABYLON.Tmp.Vector3[1];
  59841. var v4 = BABYLON.Tmp.Vector3[0];
  59842. var v1v2 = BABYLON.Tmp.Vector3[4];
  59843. var v1v3 = BABYLON.Tmp.Vector3[5];
  59844. var v1v4 = BABYLON.Tmp.Vector3[6];
  59845. var norm1 = BABYLON.Tmp.Vector3[7];
  59846. var norm2 = BABYLON.Tmp.Vector3[8];
  59847. var i = 0;
  59848. var j = 0;
  59849. var k = 0;
  59850. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59851. var h = 0;
  59852. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59853. var d2 = 0;
  59854. var subdivisionsX = this._subdivisionsX;
  59855. var subdivisionsY = this._subdivisionsY;
  59856. for (var row = 0; row < subdivisionsY; row++) {
  59857. for (var col = 0; col < subdivisionsX; col++) {
  59858. i = col * 3;
  59859. j = row * (subdivisionsX + 1) * 3;
  59860. k = (row + 1) * (subdivisionsX + 1) * 3;
  59861. v1.x = positions[j + i];
  59862. v1.y = positions[j + i + 1];
  59863. v1.z = positions[j + i + 2];
  59864. v2.x = positions[j + i + 3];
  59865. v2.y = positions[j + i + 4];
  59866. v2.z = positions[j + i + 5];
  59867. v3.x = positions[k + i];
  59868. v3.y = positions[k + i + 1];
  59869. v3.z = positions[k + i + 2];
  59870. v4.x = positions[k + i + 3];
  59871. v4.y = positions[k + i + 4];
  59872. v4.z = positions[k + i + 5];
  59873. // 2D slope V1V4
  59874. cd = (v4.z - v1.z) / (v4.x - v1.x);
  59875. h = v1.z - cd * v1.x; // v1 belongs to the slope
  59876. // facet equations :
  59877. // we compute each facet normal vector
  59878. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  59879. // we compute the value d by applying the equation to v1 which belongs to the plane
  59880. // then we store the facet equation in a Vector4
  59881. v2.subtractToRef(v1, v1v2);
  59882. v3.subtractToRef(v1, v1v3);
  59883. v4.subtractToRef(v1, v1v4);
  59884. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  59885. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  59886. norm1.normalize();
  59887. norm2.normalize();
  59888. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  59889. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  59890. var quad = this._heightQuads[row * subdivisionsX + col];
  59891. quad.slope.copyFromFloats(cd, h);
  59892. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  59893. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  59894. }
  59895. }
  59896. return this;
  59897. };
  59898. GroundMesh.prototype.serialize = function (serializationObject) {
  59899. _super.prototype.serialize.call(this, serializationObject);
  59900. serializationObject.subdivisionsX = this._subdivisionsX;
  59901. serializationObject.subdivisionsY = this._subdivisionsY;
  59902. serializationObject.minX = this._minX;
  59903. serializationObject.maxX = this._maxX;
  59904. serializationObject.minZ = this._minZ;
  59905. serializationObject.maxZ = this._maxZ;
  59906. serializationObject.width = this._width;
  59907. serializationObject.height = this._height;
  59908. };
  59909. GroundMesh.Parse = function (parsedMesh, scene) {
  59910. var result = new GroundMesh(parsedMesh.name, scene);
  59911. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  59912. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  59913. result._minX = parsedMesh.minX;
  59914. result._maxX = parsedMesh.maxX;
  59915. result._minZ = parsedMesh.minZ;
  59916. result._maxZ = parsedMesh.maxZ;
  59917. result._width = parsedMesh.width;
  59918. result._height = parsedMesh.height;
  59919. return result;
  59920. };
  59921. return GroundMesh;
  59922. }(BABYLON.Mesh));
  59923. BABYLON.GroundMesh = GroundMesh;
  59924. })(BABYLON || (BABYLON = {}));
  59925. //# sourceMappingURL=babylon.groundMesh.js.map
  59926. var BABYLON;
  59927. (function (BABYLON) {
  59928. /**
  59929. * Creates an instance based on a source mesh.
  59930. */
  59931. var InstancedMesh = /** @class */ (function (_super) {
  59932. __extends(InstancedMesh, _super);
  59933. function InstancedMesh(name, source) {
  59934. var _this = _super.call(this, name, source.getScene()) || this;
  59935. source.instances.push(_this);
  59936. _this._sourceMesh = source;
  59937. _this.position.copyFrom(source.position);
  59938. _this.rotation.copyFrom(source.rotation);
  59939. _this.scaling.copyFrom(source.scaling);
  59940. if (source.rotationQuaternion) {
  59941. _this.rotationQuaternion = source.rotationQuaternion.clone();
  59942. }
  59943. _this.infiniteDistance = source.infiniteDistance;
  59944. _this.setPivotMatrix(source.getPivotMatrix());
  59945. _this.refreshBoundingInfo();
  59946. _this._syncSubMeshes();
  59947. return _this;
  59948. }
  59949. /**
  59950. * Returns the string "InstancedMesh".
  59951. */
  59952. InstancedMesh.prototype.getClassName = function () {
  59953. return "InstancedMesh";
  59954. };
  59955. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  59956. // Methods
  59957. get: function () {
  59958. return this._sourceMesh.receiveShadows;
  59959. },
  59960. enumerable: true,
  59961. configurable: true
  59962. });
  59963. Object.defineProperty(InstancedMesh.prototype, "material", {
  59964. get: function () {
  59965. return this._sourceMesh.material;
  59966. },
  59967. enumerable: true,
  59968. configurable: true
  59969. });
  59970. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  59971. get: function () {
  59972. return this._sourceMesh.visibility;
  59973. },
  59974. enumerable: true,
  59975. configurable: true
  59976. });
  59977. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  59978. get: function () {
  59979. return this._sourceMesh.skeleton;
  59980. },
  59981. enumerable: true,
  59982. configurable: true
  59983. });
  59984. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  59985. get: function () {
  59986. return this._sourceMesh.renderingGroupId;
  59987. },
  59988. set: function (value) {
  59989. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  59990. return;
  59991. }
  59992. //no-op with warning
  59993. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  59994. },
  59995. enumerable: true,
  59996. configurable: true
  59997. });
  59998. /**
  59999. * Returns the total number of vertices (integer).
  60000. */
  60001. InstancedMesh.prototype.getTotalVertices = function () {
  60002. return this._sourceMesh.getTotalVertices();
  60003. };
  60004. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60005. get: function () {
  60006. return this._sourceMesh;
  60007. },
  60008. enumerable: true,
  60009. configurable: true
  60010. });
  60011. /**
  60012. * Is this node ready to be used/rendered
  60013. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60014. * @return {boolean} is it ready
  60015. */
  60016. InstancedMesh.prototype.isReady = function (completeCheck) {
  60017. if (completeCheck === void 0) { completeCheck = false; }
  60018. return this._sourceMesh.isReady(completeCheck, true);
  60019. };
  60020. /**
  60021. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60022. */
  60023. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60024. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60025. };
  60026. /**
  60027. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60028. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60029. * The `data` are either a numeric array either a Float32Array.
  60030. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60031. * 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).
  60032. * Note that a new underlying VertexBuffer object is created each call.
  60033. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60034. *
  60035. * Possible `kind` values :
  60036. * - BABYLON.VertexBuffer.PositionKind
  60037. * - BABYLON.VertexBuffer.UVKind
  60038. * - BABYLON.VertexBuffer.UV2Kind
  60039. * - BABYLON.VertexBuffer.UV3Kind
  60040. * - BABYLON.VertexBuffer.UV4Kind
  60041. * - BABYLON.VertexBuffer.UV5Kind
  60042. * - BABYLON.VertexBuffer.UV6Kind
  60043. * - BABYLON.VertexBuffer.ColorKind
  60044. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60045. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60046. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60047. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60048. *
  60049. * Returns the Mesh.
  60050. */
  60051. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60052. if (this.sourceMesh) {
  60053. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60054. }
  60055. return this.sourceMesh;
  60056. };
  60057. /**
  60058. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60059. * If the mesh has no geometry, it is simply returned as it is.
  60060. * The `data` are either a numeric array either a Float32Array.
  60061. * No new underlying VertexBuffer object is created.
  60062. * 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.
  60063. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60064. *
  60065. * Possible `kind` values :
  60066. * - BABYLON.VertexBuffer.PositionKind
  60067. * - BABYLON.VertexBuffer.UVKind
  60068. * - BABYLON.VertexBuffer.UV2Kind
  60069. * - BABYLON.VertexBuffer.UV3Kind
  60070. * - BABYLON.VertexBuffer.UV4Kind
  60071. * - BABYLON.VertexBuffer.UV5Kind
  60072. * - BABYLON.VertexBuffer.UV6Kind
  60073. * - BABYLON.VertexBuffer.ColorKind
  60074. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60075. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60076. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60077. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60078. *
  60079. * Returns the Mesh.
  60080. */
  60081. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60082. if (this.sourceMesh) {
  60083. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60084. }
  60085. return this.sourceMesh;
  60086. };
  60087. /**
  60088. * Sets the mesh indices.
  60089. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60090. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60091. * This method creates a new index buffer each call.
  60092. * Returns the Mesh.
  60093. */
  60094. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60095. if (totalVertices === void 0) { totalVertices = null; }
  60096. if (this.sourceMesh) {
  60097. this.sourceMesh.setIndices(indices, totalVertices);
  60098. }
  60099. return this.sourceMesh;
  60100. };
  60101. /**
  60102. * Boolean : True if the mesh owns the requested kind of data.
  60103. */
  60104. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60105. return this._sourceMesh.isVerticesDataPresent(kind);
  60106. };
  60107. /**
  60108. * Returns an array of indices (IndicesArray).
  60109. */
  60110. InstancedMesh.prototype.getIndices = function () {
  60111. return this._sourceMesh.getIndices();
  60112. };
  60113. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60114. get: function () {
  60115. return this._sourceMesh._positions;
  60116. },
  60117. enumerable: true,
  60118. configurable: true
  60119. });
  60120. /**
  60121. * Sets a new updated BoundingInfo to the mesh.
  60122. * Returns the mesh.
  60123. */
  60124. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60125. var meshBB = this._sourceMesh.getBoundingInfo();
  60126. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60127. this._updateBoundingInfo();
  60128. return this;
  60129. };
  60130. InstancedMesh.prototype._preActivate = function () {
  60131. if (this._currentLOD) {
  60132. this._currentLOD._preActivate();
  60133. }
  60134. return this;
  60135. };
  60136. InstancedMesh.prototype._activate = function (renderId) {
  60137. if (this._currentLOD) {
  60138. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60139. }
  60140. return this;
  60141. };
  60142. /**
  60143. * Returns the current associated LOD AbstractMesh.
  60144. */
  60145. InstancedMesh.prototype.getLOD = function (camera) {
  60146. if (!camera) {
  60147. return this;
  60148. }
  60149. var boundingInfo = this.getBoundingInfo();
  60150. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60151. if (this._currentLOD === this.sourceMesh) {
  60152. return this;
  60153. }
  60154. return this._currentLOD;
  60155. };
  60156. InstancedMesh.prototype._syncSubMeshes = function () {
  60157. this.releaseSubMeshes();
  60158. if (this._sourceMesh.subMeshes) {
  60159. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60160. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60161. }
  60162. }
  60163. return this;
  60164. };
  60165. InstancedMesh.prototype._generatePointsArray = function () {
  60166. return this._sourceMesh._generatePointsArray();
  60167. };
  60168. /**
  60169. * Creates a new InstancedMesh from the current mesh.
  60170. * - name (string) : the cloned mesh name
  60171. * - newParent (optional Node) : the optional Node to parent the clone to.
  60172. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60173. *
  60174. * Returns the clone.
  60175. */
  60176. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60177. var result = this._sourceMesh.createInstance(name);
  60178. // Deep copy
  60179. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60180. // Bounding info
  60181. this.refreshBoundingInfo();
  60182. // Parent
  60183. if (newParent) {
  60184. result.parent = newParent;
  60185. }
  60186. if (!doNotCloneChildren) {
  60187. // Children
  60188. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60189. var mesh = this.getScene().meshes[index];
  60190. if (mesh.parent === this) {
  60191. mesh.clone(mesh.name, result);
  60192. }
  60193. }
  60194. }
  60195. result.computeWorldMatrix(true);
  60196. return result;
  60197. };
  60198. /**
  60199. * Disposes the InstancedMesh.
  60200. * Returns nothing.
  60201. */
  60202. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60203. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60204. // Remove from mesh
  60205. var index = this._sourceMesh.instances.indexOf(this);
  60206. this._sourceMesh.instances.splice(index, 1);
  60207. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60208. };
  60209. return InstancedMesh;
  60210. }(BABYLON.AbstractMesh));
  60211. BABYLON.InstancedMesh = InstancedMesh;
  60212. })(BABYLON || (BABYLON = {}));
  60213. //# sourceMappingURL=babylon.instancedMesh.js.map
  60214. var BABYLON;
  60215. (function (BABYLON) {
  60216. var LinesMesh = /** @class */ (function (_super) {
  60217. __extends(LinesMesh, _super);
  60218. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60219. if (scene === void 0) { scene = null; }
  60220. if (parent === void 0) { parent = null; }
  60221. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60222. _this.useVertexColor = useVertexColor;
  60223. _this.useVertexAlpha = useVertexAlpha;
  60224. _this.color = new BABYLON.Color3(1, 1, 1);
  60225. _this.alpha = 1;
  60226. if (source) {
  60227. _this.color = source.color.clone();
  60228. _this.alpha = source.alpha;
  60229. _this.useVertexColor = source.useVertexColor;
  60230. _this.useVertexAlpha = source.useVertexAlpha;
  60231. }
  60232. _this._intersectionThreshold = 0.1;
  60233. var defines = [];
  60234. var options = {
  60235. attributes: [BABYLON.VertexBuffer.PositionKind],
  60236. uniforms: ["world", "viewProjection"],
  60237. needAlphaBlending: true,
  60238. defines: defines
  60239. };
  60240. if (useVertexAlpha === false) {
  60241. options.needAlphaBlending = false;
  60242. }
  60243. if (!useVertexColor) {
  60244. options.uniforms.push("color");
  60245. }
  60246. else {
  60247. options.defines.push("#define VERTEXCOLOR");
  60248. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60249. }
  60250. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60251. return _this;
  60252. }
  60253. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60254. /**
  60255. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60256. * This margin is expressed in world space coordinates, so its value may vary.
  60257. * Default value is 0.1
  60258. * @returns the intersection Threshold value.
  60259. */
  60260. get: function () {
  60261. return this._intersectionThreshold;
  60262. },
  60263. /**
  60264. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60265. * This margin is expressed in world space coordinates, so its value may vary.
  60266. * @param value the new threshold to apply
  60267. */
  60268. set: function (value) {
  60269. if (this._intersectionThreshold === value) {
  60270. return;
  60271. }
  60272. this._intersectionThreshold = value;
  60273. if (this.geometry) {
  60274. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60275. }
  60276. },
  60277. enumerable: true,
  60278. configurable: true
  60279. });
  60280. /**
  60281. * Returns the string "LineMesh"
  60282. */
  60283. LinesMesh.prototype.getClassName = function () {
  60284. return "LinesMesh";
  60285. };
  60286. Object.defineProperty(LinesMesh.prototype, "material", {
  60287. get: function () {
  60288. return this._colorShader;
  60289. },
  60290. set: function (value) {
  60291. // Do nothing
  60292. },
  60293. enumerable: true,
  60294. configurable: true
  60295. });
  60296. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60297. get: function () {
  60298. return false;
  60299. },
  60300. enumerable: true,
  60301. configurable: true
  60302. });
  60303. LinesMesh.prototype.createInstance = function (name) {
  60304. throw new Error("LinesMeshes do not support createInstance.");
  60305. };
  60306. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60307. if (!this._geometry) {
  60308. return this;
  60309. }
  60310. // VBOs
  60311. this._geometry._bind(this._colorShader.getEffect());
  60312. // Color
  60313. if (!this.useVertexColor) {
  60314. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60315. }
  60316. return this;
  60317. };
  60318. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60319. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60320. return this;
  60321. }
  60322. var engine = this.getScene().getEngine();
  60323. // Draw order
  60324. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60325. return this;
  60326. };
  60327. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60328. this._colorShader.dispose();
  60329. _super.prototype.dispose.call(this, doNotRecurse);
  60330. };
  60331. /**
  60332. * Returns a new LineMesh object cloned from the current one.
  60333. */
  60334. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60335. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60336. };
  60337. return LinesMesh;
  60338. }(BABYLON.Mesh));
  60339. BABYLON.LinesMesh = LinesMesh;
  60340. })(BABYLON || (BABYLON = {}));
  60341. //# sourceMappingURL=babylon.linesMesh.js.map
  60342. var BABYLON;
  60343. (function (BABYLON) {
  60344. /**
  60345. * Class containing static functions to help procedurally build meshes
  60346. */
  60347. var MeshBuilder = /** @class */ (function () {
  60348. function MeshBuilder() {
  60349. }
  60350. MeshBuilder.updateSideOrientation = function (orientation) {
  60351. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60352. return BABYLON.Mesh.DOUBLESIDE;
  60353. }
  60354. if (orientation === undefined || orientation === null) {
  60355. return BABYLON.Mesh.FRONTSIDE;
  60356. }
  60357. return orientation;
  60358. };
  60359. /**
  60360. * Creates a box mesh
  60361. * * The parameter `size` sets the size (float) of each box side (default 1)
  60362. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60363. * * 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)
  60364. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60365. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60366. * * 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
  60367. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60368. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60369. * @param name defines the name of the mesh
  60370. * @param options defines the options used to create the mesh
  60371. * @param scene defines the hosting scene
  60372. * @returns the box mesh
  60373. */
  60374. MeshBuilder.CreateBox = function (name, options, scene) {
  60375. if (scene === void 0) { scene = null; }
  60376. var box = new BABYLON.Mesh(name, scene);
  60377. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60378. box._originalBuilderSideOrientation = options.sideOrientation;
  60379. var vertexData = BABYLON.VertexData.CreateBox(options);
  60380. vertexData.applyToMesh(box, options.updatable);
  60381. return box;
  60382. };
  60383. /**
  60384. * Creates a sphere mesh
  60385. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60386. * * 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`)
  60387. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60388. * * 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
  60389. * * 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)
  60390. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60391. * * 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
  60392. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60393. * @param name defines the name of the mesh
  60394. * @param options defines the options used to create the mesh
  60395. * @param scene defines the hosting scene
  60396. * @returns the sphere mesh
  60397. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60398. */
  60399. MeshBuilder.CreateSphere = function (name, options, scene) {
  60400. var sphere = new BABYLON.Mesh(name, scene);
  60401. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60402. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60403. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60404. vertexData.applyToMesh(sphere, options.updatable);
  60405. return sphere;
  60406. };
  60407. /**
  60408. * Creates a plane polygonal mesh. By default, this is a disc
  60409. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60410. * * 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
  60411. * * 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
  60412. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60413. * * 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
  60414. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60415. * @param name defines the name of the mesh
  60416. * @param options defines the options used to create the mesh
  60417. * @param scene defines the hosting scene
  60418. * @returns the plane polygonal mesh
  60419. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60420. */
  60421. MeshBuilder.CreateDisc = function (name, options, scene) {
  60422. if (scene === void 0) { scene = null; }
  60423. var disc = new BABYLON.Mesh(name, scene);
  60424. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60425. disc._originalBuilderSideOrientation = options.sideOrientation;
  60426. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60427. vertexData.applyToMesh(disc, options.updatable);
  60428. return disc;
  60429. };
  60430. /**
  60431. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60432. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60433. * * 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`)
  60434. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60435. * * 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
  60436. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60437. * * 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
  60438. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60439. * @param name defines the name of the mesh
  60440. * @param options defines the options used to create the mesh
  60441. * @param scene defines the hosting scene
  60442. * @returns the icosahedron mesh
  60443. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60444. */
  60445. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60446. var sphere = new BABYLON.Mesh(name, scene);
  60447. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60448. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60449. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60450. vertexData.applyToMesh(sphere, options.updatable);
  60451. return sphere;
  60452. };
  60453. ;
  60454. /**
  60455. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60456. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60457. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60458. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60459. * * 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
  60460. * * 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
  60461. * * 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
  60462. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60463. * * 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
  60464. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60465. * * 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
  60466. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60467. * * 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
  60468. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60469. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60470. * @param name defines the name of the mesh
  60471. * @param options defines the options used to create the mesh
  60472. * @param scene defines the hosting scene
  60473. * @returns the ribbon mesh
  60474. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60475. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60476. */
  60477. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60478. if (scene === void 0) { scene = null; }
  60479. var pathArray = options.pathArray;
  60480. var closeArray = options.closeArray;
  60481. var closePath = options.closePath;
  60482. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60483. var instance = options.instance;
  60484. var updatable = options.updatable;
  60485. if (instance) { // existing ribbon instance update
  60486. // positionFunction : ribbon case
  60487. // only pathArray and sideOrientation parameters are taken into account for positions update
  60488. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60489. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60490. var positionFunction = function (positions) {
  60491. var minlg = pathArray[0].length;
  60492. var i = 0;
  60493. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60494. for (var si = 1; si <= ns; si++) {
  60495. for (var p = 0; p < pathArray.length; p++) {
  60496. var path = pathArray[p];
  60497. var l = path.length;
  60498. minlg = (minlg < l) ? minlg : l;
  60499. var j = 0;
  60500. while (j < minlg) {
  60501. positions[i] = path[j].x;
  60502. positions[i + 1] = path[j].y;
  60503. positions[i + 2] = path[j].z;
  60504. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60505. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60506. }
  60507. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60508. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60509. }
  60510. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60511. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60512. }
  60513. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60514. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60515. }
  60516. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60517. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60518. }
  60519. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60520. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60521. }
  60522. j++;
  60523. i += 3;
  60524. }
  60525. if (instance._closePath) {
  60526. positions[i] = path[0].x;
  60527. positions[i + 1] = path[0].y;
  60528. positions[i + 2] = path[0].z;
  60529. i += 3;
  60530. }
  60531. }
  60532. }
  60533. };
  60534. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60535. positionFunction(positions);
  60536. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60537. instance._boundingInfo.update(instance._worldMatrix);
  60538. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60539. if (options.colors) {
  60540. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60541. for (var c = 0; c < options.colors.length; c++) {
  60542. colors[c * 4] = options.colors[c].r;
  60543. colors[c * 4 + 1] = options.colors[c].g;
  60544. colors[c * 4 + 2] = options.colors[c].b;
  60545. colors[c * 4 + 3] = options.colors[c].a;
  60546. }
  60547. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60548. }
  60549. if (options.uvs) {
  60550. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60551. for (var i = 0; i < options.uvs.length; i++) {
  60552. uvs[i * 2] = options.uvs[i].x;
  60553. uvs[i * 2 + 1] = options.uvs[i].y;
  60554. }
  60555. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60556. }
  60557. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60558. var indices = instance.getIndices();
  60559. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60560. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60561. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60562. if (instance._closePath) {
  60563. var indexFirst = 0;
  60564. var indexLast = 0;
  60565. for (var p = 0; p < pathArray.length; p++) {
  60566. indexFirst = instance._idx[p] * 3;
  60567. if (p + 1 < pathArray.length) {
  60568. indexLast = (instance._idx[p + 1] - 1) * 3;
  60569. }
  60570. else {
  60571. indexLast = normals.length - 3;
  60572. }
  60573. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60574. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60575. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60576. normals[indexLast] = normals[indexFirst];
  60577. normals[indexLast + 1] = normals[indexFirst + 1];
  60578. normals[indexLast + 2] = normals[indexFirst + 2];
  60579. }
  60580. }
  60581. if (!(instance.areNormalsFrozen)) {
  60582. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60583. }
  60584. }
  60585. return instance;
  60586. }
  60587. else { // new ribbon creation
  60588. var ribbon = new BABYLON.Mesh(name, scene);
  60589. ribbon._originalBuilderSideOrientation = sideOrientation;
  60590. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60591. if (closePath) {
  60592. ribbon._idx = vertexData._idx;
  60593. }
  60594. ribbon._closePath = closePath;
  60595. ribbon._closeArray = closeArray;
  60596. vertexData.applyToMesh(ribbon, updatable);
  60597. return ribbon;
  60598. }
  60599. };
  60600. /**
  60601. * Creates a cylinder or a cone mesh
  60602. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60603. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60604. * * 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.
  60605. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60606. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60607. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60608. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60609. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60610. * * 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).
  60611. * * 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
  60612. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60613. * * 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
  60614. * * 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.
  60615. * * If `enclose` is false, a ring surface is one element.
  60616. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60617. * * 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
  60618. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60619. * * 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
  60620. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60621. * @param name defines the name of the mesh
  60622. * @param options defines the options used to create the mesh
  60623. * @param scene defines the hosting scene
  60624. * @returns the cylinder mesh
  60625. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60626. */
  60627. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60628. var cylinder = new BABYLON.Mesh(name, scene);
  60629. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60630. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60631. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60632. vertexData.applyToMesh(cylinder, options.updatable);
  60633. return cylinder;
  60634. };
  60635. /**
  60636. * Creates a torus mesh
  60637. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60638. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60639. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60640. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60641. * * 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
  60642. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60643. * @param name defines the name of the mesh
  60644. * @param options defines the options used to create the mesh
  60645. * @param scene defines the hosting scene
  60646. * @returns the torus mesh
  60647. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60648. */
  60649. MeshBuilder.CreateTorus = function (name, options, scene) {
  60650. var torus = new BABYLON.Mesh(name, scene);
  60651. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60652. torus._originalBuilderSideOrientation = options.sideOrientation;
  60653. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60654. vertexData.applyToMesh(torus, options.updatable);
  60655. return torus;
  60656. };
  60657. /**
  60658. * Creates a torus knot mesh
  60659. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60660. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60661. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60662. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60663. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60664. * * 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
  60665. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60666. * @param name defines the name of the mesh
  60667. * @param options defines the options used to create the mesh
  60668. * @param scene defines the hosting scene
  60669. * @returns the torus knot mesh
  60670. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60671. */
  60672. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60673. var torusKnot = new BABYLON.Mesh(name, scene);
  60674. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60675. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60676. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60677. vertexData.applyToMesh(torusKnot, options.updatable);
  60678. return torusKnot;
  60679. };
  60680. /**
  60681. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60682. * * 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
  60683. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60684. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60685. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60686. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60687. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60688. * * 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
  60689. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60690. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60691. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60692. * @param name defines the name of the new line system
  60693. * @param options defines the options used to create the line system
  60694. * @param scene defines the hosting scene
  60695. * @returns a new line system mesh
  60696. */
  60697. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60698. var instance = options.instance;
  60699. var lines = options.lines;
  60700. var colors = options.colors;
  60701. if (instance) { // lines update
  60702. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60703. var vertexColor;
  60704. var lineColors;
  60705. if (colors) {
  60706. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60707. }
  60708. var i = 0;
  60709. var c = 0;
  60710. for (var l = 0; l < lines.length; l++) {
  60711. var points = lines[l];
  60712. for (var p = 0; p < points.length; p++) {
  60713. positions[i] = points[p].x;
  60714. positions[i + 1] = points[p].y;
  60715. positions[i + 2] = points[p].z;
  60716. if (colors && vertexColor) {
  60717. lineColors = colors[l];
  60718. vertexColor[c] = lineColors[p].r;
  60719. vertexColor[c + 1] = lineColors[p].g;
  60720. vertexColor[c + 2] = lineColors[p].b;
  60721. vertexColor[c + 3] = lineColors[p].a;
  60722. c += 4;
  60723. }
  60724. i += 3;
  60725. }
  60726. }
  60727. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60728. if (colors && vertexColor) {
  60729. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60730. }
  60731. return instance;
  60732. }
  60733. // line system creation
  60734. var useVertexColor = (colors) ? true : false;
  60735. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60736. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60737. vertexData.applyToMesh(lineSystem, options.updatable);
  60738. return lineSystem;
  60739. };
  60740. /**
  60741. * Creates a line mesh
  60742. * 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
  60743. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60744. * * The parameter `points` is an array successive Vector3
  60745. * * 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
  60746. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60747. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60748. * * When updating an instance, remember that only point positions can change, not the number of points
  60749. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60750. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60751. * @param name defines the name of the new line system
  60752. * @param options defines the options used to create the line system
  60753. * @param scene defines the hosting scene
  60754. * @returns a new line mesh
  60755. */
  60756. MeshBuilder.CreateLines = function (name, options, scene) {
  60757. if (scene === void 0) { scene = null; }
  60758. var colors = (options.colors) ? [options.colors] : null;
  60759. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60760. return lines;
  60761. };
  60762. /**
  60763. * Creates a dashed line mesh
  60764. * * 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
  60765. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60766. * * The parameter `points` is an array successive Vector3
  60767. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60768. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60769. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60770. * * 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
  60771. * * When updating an instance, remember that only point positions can change, not the number of points
  60772. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60773. * @param name defines the name of the mesh
  60774. * @param options defines the options used to create the mesh
  60775. * @param scene defines the hosting scene
  60776. * @returns the dashed line mesh
  60777. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60778. */
  60779. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60780. if (scene === void 0) { scene = null; }
  60781. var points = options.points;
  60782. var instance = options.instance;
  60783. var gapSize = options.gapSize || 1;
  60784. var dashSize = options.dashSize || 3;
  60785. if (instance) { // dashed lines update
  60786. var positionFunction = function (positions) {
  60787. var curvect = BABYLON.Vector3.Zero();
  60788. var nbSeg = positions.length / 6;
  60789. var lg = 0;
  60790. var nb = 0;
  60791. var shft = 0;
  60792. var dashshft = 0;
  60793. var curshft = 0;
  60794. var p = 0;
  60795. var i = 0;
  60796. var j = 0;
  60797. for (i = 0; i < points.length - 1; i++) {
  60798. points[i + 1].subtractToRef(points[i], curvect);
  60799. lg += curvect.length();
  60800. }
  60801. shft = lg / nbSeg;
  60802. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60803. for (i = 0; i < points.length - 1; i++) {
  60804. points[i + 1].subtractToRef(points[i], curvect);
  60805. nb = Math.floor(curvect.length() / shft);
  60806. curvect.normalize();
  60807. j = 0;
  60808. while (j < nb && p < positions.length) {
  60809. curshft = shft * j;
  60810. positions[p] = points[i].x + curshft * curvect.x;
  60811. positions[p + 1] = points[i].y + curshft * curvect.y;
  60812. positions[p + 2] = points[i].z + curshft * curvect.z;
  60813. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60814. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60815. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60816. p += 6;
  60817. j++;
  60818. }
  60819. }
  60820. while (p < positions.length) {
  60821. positions[p] = points[i].x;
  60822. positions[p + 1] = points[i].y;
  60823. positions[p + 2] = points[i].z;
  60824. p += 3;
  60825. }
  60826. };
  60827. instance.updateMeshPositions(positionFunction, false);
  60828. return instance;
  60829. }
  60830. // dashed lines creation
  60831. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60832. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60833. vertexData.applyToMesh(dashedLines, options.updatable);
  60834. dashedLines.dashSize = dashSize;
  60835. dashedLines.gapSize = gapSize;
  60836. return dashedLines;
  60837. };
  60838. /**
  60839. * 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.
  60840. * * 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.
  60841. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60842. * * 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.
  60843. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60844. * * 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
  60845. * * 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
  60846. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60847. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60848. * * 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
  60849. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  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 extruded shape mesh
  60855. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60856. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60857. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60858. */
  60859. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60860. if (scene === void 0) { scene = null; }
  60861. var path = options.path;
  60862. var shape = options.shape;
  60863. var scale = options.scale || 1;
  60864. var rotation = options.rotation || 0;
  60865. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60866. var updatable = options.updatable;
  60867. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60868. var instance = options.instance || null;
  60869. var invertUV = options.invertUV || false;
  60870. 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);
  60871. };
  60872. /**
  60873. * Creates an custom extruded shape mesh.
  60874. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  60875. * * 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.
  60876. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60877. * * 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
  60878. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  60879. * * 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
  60880. * * It must returns a float value that will be the scale value applied to the shape on each path point
  60881. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  60882. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  60883. * * 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
  60884. * * 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
  60885. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  60886. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60887. * * 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
  60888. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60889. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60890. * @param name defines the name of the mesh
  60891. * @param options defines the options used to create the mesh
  60892. * @param scene defines the hosting scene
  60893. * @returns the custom extruded shape mesh
  60894. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  60895. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60896. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60897. */
  60898. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  60899. var path = options.path;
  60900. var shape = options.shape;
  60901. var scaleFunction = options.scaleFunction || (function () { return 1; });
  60902. var rotationFunction = options.rotationFunction || (function () { return 0; });
  60903. var ribbonCloseArray = options.ribbonCloseArray || false;
  60904. var ribbonClosePath = options.ribbonClosePath || false;
  60905. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  60906. var updatable = options.updatable;
  60907. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60908. var instance = options.instance;
  60909. var invertUV = options.invertUV || false;
  60910. 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);
  60911. };
  60912. /**
  60913. * Creates lathe mesh.
  60914. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  60915. * * 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
  60916. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  60917. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  60918. * * 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
  60919. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  60920. * * 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
  60921. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60922. * * 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
  60923. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60924. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60925. * @param name defines the name of the mesh
  60926. * @param options defines the options used to create the mesh
  60927. * @param scene defines the hosting scene
  60928. * @returns the lathe mesh
  60929. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  60930. */
  60931. MeshBuilder.CreateLathe = function (name, options, scene) {
  60932. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  60933. var closed = (options.closed === undefined) ? true : options.closed;
  60934. var shape = options.shape;
  60935. var radius = options.radius || 1;
  60936. var tessellation = options.tessellation || 64;
  60937. var updatable = options.updatable;
  60938. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60939. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  60940. var pi2 = Math.PI * 2;
  60941. var paths = new Array();
  60942. var invertUV = options.invertUV || false;
  60943. var i = 0;
  60944. var p = 0;
  60945. var step = pi2 / tessellation * arc;
  60946. var rotated;
  60947. var path = new Array();
  60948. ;
  60949. for (i = 0; i <= tessellation; i++) {
  60950. var path = [];
  60951. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  60952. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  60953. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  60954. }
  60955. for (p = 0; p < shape.length; p++) {
  60956. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  60957. path.push(rotated);
  60958. }
  60959. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  60960. 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));
  60961. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  60962. }
  60963. paths.push(path);
  60964. }
  60965. // lathe ribbon
  60966. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  60967. return lathe;
  60968. };
  60969. /**
  60970. * Creates a plane mesh
  60971. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  60972. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  60973. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  60974. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60975. * * 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
  60976. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60977. * @param name defines the name of the mesh
  60978. * @param options defines the options used to create the mesh
  60979. * @param scene defines the hosting scene
  60980. * @returns the plane mesh
  60981. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  60982. */
  60983. MeshBuilder.CreatePlane = function (name, options, scene) {
  60984. var plane = new BABYLON.Mesh(name, scene);
  60985. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60986. plane._originalBuilderSideOrientation = options.sideOrientation;
  60987. var vertexData = BABYLON.VertexData.CreatePlane(options);
  60988. vertexData.applyToMesh(plane, options.updatable);
  60989. if (options.sourcePlane) {
  60990. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  60991. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  60992. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  60993. plane.rotate(vectorProduct, product);
  60994. }
  60995. return plane;
  60996. };
  60997. /**
  60998. * Creates a ground mesh
  60999. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61000. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61001. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61002. * @param name defines the name of the mesh
  61003. * @param options defines the options used to create the mesh
  61004. * @param scene defines the hosting scene
  61005. * @returns the ground mesh
  61006. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61007. */
  61008. MeshBuilder.CreateGround = function (name, options, scene) {
  61009. var ground = new BABYLON.GroundMesh(name, scene);
  61010. ground._setReady(false);
  61011. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61012. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61013. ground._width = options.width || 1;
  61014. ground._height = options.height || 1;
  61015. ground._maxX = ground._width / 2;
  61016. ground._maxZ = ground._height / 2;
  61017. ground._minX = -ground._maxX;
  61018. ground._minZ = -ground._maxZ;
  61019. var vertexData = BABYLON.VertexData.CreateGround(options);
  61020. vertexData.applyToMesh(ground, options.updatable);
  61021. ground._setReady(true);
  61022. return ground;
  61023. };
  61024. /**
  61025. * Creates a tiled ground mesh
  61026. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61027. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61028. * * 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
  61029. * * 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
  61030. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61031. * @param name defines the name of the mesh
  61032. * @param options defines the options used to create the mesh
  61033. * @param scene defines the hosting scene
  61034. * @returns the tiled ground mesh
  61035. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61036. */
  61037. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61038. var tiledGround = new BABYLON.Mesh(name, scene);
  61039. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61040. vertexData.applyToMesh(tiledGround, options.updatable);
  61041. return tiledGround;
  61042. };
  61043. /**
  61044. * Creates a ground mesh from a height map
  61045. * * The parameter `url` sets the URL of the height map image resource.
  61046. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61047. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61048. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61049. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61050. * * 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.
  61051. * * 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).
  61052. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61053. * @param name defines the name of the mesh
  61054. * @param url defines the url to the height map
  61055. * @param options defines the options used to create the mesh
  61056. * @param scene defines the hosting scene
  61057. * @returns the ground mesh
  61058. * @see http://doc.babylonjs.com/babylon101/height_map
  61059. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61060. */
  61061. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61062. var width = options.width || 10.0;
  61063. var height = options.height || 10.0;
  61064. var subdivisions = options.subdivisions || 1 | 0;
  61065. var minHeight = options.minHeight || 0.0;
  61066. var maxHeight = options.maxHeight || 1.0;
  61067. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61068. var updatable = options.updatable;
  61069. var onReady = options.onReady;
  61070. var ground = new BABYLON.GroundMesh(name, scene);
  61071. ground._subdivisionsX = subdivisions;
  61072. ground._subdivisionsY = subdivisions;
  61073. ground._width = width;
  61074. ground._height = height;
  61075. ground._maxX = ground._width / 2.0;
  61076. ground._maxZ = ground._height / 2.0;
  61077. ground._minX = -ground._maxX;
  61078. ground._minZ = -ground._maxZ;
  61079. ground._setReady(false);
  61080. var onload = function (img) {
  61081. // Getting height map data
  61082. var canvas = document.createElement("canvas");
  61083. var context = canvas.getContext("2d");
  61084. if (!context) {
  61085. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61086. }
  61087. if (scene.isDisposed) {
  61088. return;
  61089. }
  61090. var bufferWidth = img.width;
  61091. var bufferHeight = img.height;
  61092. canvas.width = bufferWidth;
  61093. canvas.height = bufferHeight;
  61094. context.drawImage(img, 0, 0);
  61095. // Create VertexData from map data
  61096. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61097. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61098. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61099. width: width, height: height,
  61100. subdivisions: subdivisions,
  61101. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61102. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61103. });
  61104. vertexData.applyToMesh(ground, updatable);
  61105. //execute ready callback, if set
  61106. if (onReady) {
  61107. onReady(ground);
  61108. }
  61109. ground._setReady(true);
  61110. };
  61111. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61112. return ground;
  61113. };
  61114. /**
  61115. * Creates a polygon mesh
  61116. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61117. * * 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
  61118. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61119. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61120. * * 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)
  61121. * * Remember you can only change the shape positions, not their number when updating a polygon
  61122. * @param name defines the name of the mesh
  61123. * @param options defines the options used to create the mesh
  61124. * @param scene defines the hosting scene
  61125. * @returns the polygon mesh
  61126. */
  61127. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61128. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61129. var shape = options.shape;
  61130. var holes = options.holes || [];
  61131. var depth = options.depth || 0;
  61132. var contours = [];
  61133. var hole = [];
  61134. for (var i = 0; i < shape.length; i++) {
  61135. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61136. }
  61137. var epsilon = 0.00000001;
  61138. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61139. contours.pop();
  61140. }
  61141. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61142. for (var hNb = 0; hNb < holes.length; hNb++) {
  61143. hole = [];
  61144. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61145. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61146. }
  61147. polygonTriangulation.addHole(hole);
  61148. }
  61149. var polygon = polygonTriangulation.build(options.updatable, depth);
  61150. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61151. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61152. vertexData.applyToMesh(polygon, options.updatable);
  61153. return polygon;
  61154. };
  61155. ;
  61156. /**
  61157. * Creates an extruded polygon mesh, with depth in the Y direction.
  61158. * * 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)
  61159. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61160. * @param name defines the name of the mesh
  61161. * @param options defines the options used to create the mesh
  61162. * @param scene defines the hosting scene
  61163. * @returns the polygon mesh
  61164. */
  61165. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61166. return MeshBuilder.CreatePolygon(name, options, scene);
  61167. };
  61168. ;
  61169. /**
  61170. * Creates a tube mesh.
  61171. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61172. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61173. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61174. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61175. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61176. * * 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)
  61177. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61178. * * 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
  61179. * * 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
  61180. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61181. * * 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
  61182. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61183. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61184. * @param name defines the name of the mesh
  61185. * @param options defines the options used to create the mesh
  61186. * @param scene defines the hosting scene
  61187. * @returns the tube mesh
  61188. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61189. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61190. */
  61191. MeshBuilder.CreateTube = function (name, options, scene) {
  61192. var path = options.path;
  61193. var instance = options.instance;
  61194. var radius = 1.0;
  61195. if (instance) {
  61196. radius = instance.radius;
  61197. }
  61198. if (options.radius !== undefined) {
  61199. radius = options.radius;
  61200. }
  61201. ;
  61202. var tessellation = options.tessellation || 64 | 0;
  61203. var radiusFunction = options.radiusFunction || null;
  61204. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61205. var invertUV = options.invertUV || false;
  61206. var updatable = options.updatable;
  61207. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61208. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61209. // tube geometry
  61210. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61211. var tangents = path3D.getTangents();
  61212. var normals = path3D.getNormals();
  61213. var distances = path3D.getDistances();
  61214. var pi2 = Math.PI * 2;
  61215. var step = pi2 / tessellation * arc;
  61216. var returnRadius = function () { return radius; };
  61217. var radiusFunctionFinal = radiusFunction || returnRadius;
  61218. var circlePath;
  61219. var rad;
  61220. var normal;
  61221. var rotated;
  61222. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61223. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61224. for (var i = 0; i < path.length; i++) {
  61225. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61226. circlePath = Array(); // current circle array
  61227. normal = normals[i]; // current normal
  61228. for (var t = 0; t < tessellation; t++) {
  61229. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61230. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61231. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61232. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61233. circlePath[t] = rotated;
  61234. }
  61235. circlePaths[index] = circlePath;
  61236. index++;
  61237. }
  61238. // cap
  61239. var capPath = function (nbPoints, pathIndex) {
  61240. var pointCap = Array();
  61241. for (var i = 0; i < nbPoints; i++) {
  61242. pointCap.push(path[pathIndex]);
  61243. }
  61244. return pointCap;
  61245. };
  61246. switch (cap) {
  61247. case BABYLON.Mesh.NO_CAP:
  61248. break;
  61249. case BABYLON.Mesh.CAP_START:
  61250. circlePaths[0] = capPath(tessellation, 0);
  61251. circlePaths[1] = circlePaths[2].slice(0);
  61252. break;
  61253. case BABYLON.Mesh.CAP_END:
  61254. circlePaths[index] = circlePaths[index - 1].slice(0);
  61255. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61256. break;
  61257. case BABYLON.Mesh.CAP_ALL:
  61258. circlePaths[0] = capPath(tessellation, 0);
  61259. circlePaths[1] = circlePaths[2].slice(0);
  61260. circlePaths[index] = circlePaths[index - 1].slice(0);
  61261. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61262. break;
  61263. default:
  61264. break;
  61265. }
  61266. return circlePaths;
  61267. };
  61268. var path3D;
  61269. var pathArray;
  61270. if (instance) { // tube update
  61271. var arc = options.arc || instance.arc;
  61272. path3D = (instance.path3D).update(path);
  61273. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61274. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61275. instance.path3D = path3D;
  61276. instance.pathArray = pathArray;
  61277. instance.arc = arc;
  61278. instance.radius = radius;
  61279. return instance;
  61280. }
  61281. // tube creation
  61282. path3D = new BABYLON.Path3D(path);
  61283. var newPathArray = new Array();
  61284. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61285. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61286. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61287. tube.pathArray = pathArray;
  61288. tube.path3D = path3D;
  61289. tube.tessellation = tessellation;
  61290. tube.cap = cap;
  61291. tube.arc = options.arc;
  61292. tube.radius = radius;
  61293. return tube;
  61294. };
  61295. /**
  61296. * Creates a polyhedron mesh
  61297. * * 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
  61298. * * The parameter `size` (positive float, default 1) sets the polygon size
  61299. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61300. * * 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`
  61301. * * 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
  61302. * * 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)`)
  61303. * * 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
  61304. * * 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
  61305. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61306. * * 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
  61307. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61308. * @param name defines the name of the mesh
  61309. * @param options defines the options used to create the mesh
  61310. * @param scene defines the hosting scene
  61311. * @returns the polyhedron mesh
  61312. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61313. */
  61314. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61315. var polyhedron = new BABYLON.Mesh(name, scene);
  61316. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61317. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61318. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61319. vertexData.applyToMesh(polyhedron, options.updatable);
  61320. return polyhedron;
  61321. };
  61322. /**
  61323. * Creates a decal mesh.
  61324. * 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
  61325. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61326. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61327. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61328. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61329. * @param name defines the name of the mesh
  61330. * @param sourceMesh defines the mesh where the decal must be applied
  61331. * @param options defines the options used to create the mesh
  61332. * @param scene defines the hosting scene
  61333. * @returns the decal mesh
  61334. * @see http://doc.babylonjs.com/how_to/decals
  61335. */
  61336. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61337. var indices = sourceMesh.getIndices();
  61338. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61339. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61340. var position = options.position || BABYLON.Vector3.Zero();
  61341. var normal = options.normal || BABYLON.Vector3.Up();
  61342. var size = options.size || BABYLON.Vector3.One();
  61343. var angle = options.angle || 0;
  61344. // Getting correct rotation
  61345. if (!normal) {
  61346. var target = new BABYLON.Vector3(0, 0, 1);
  61347. var camera = sourceMesh.getScene().activeCamera;
  61348. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61349. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61350. }
  61351. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61352. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61353. var pitch = Math.atan2(normal.y, len);
  61354. // Matrix
  61355. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61356. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61357. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61358. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61359. var vertexData = new BABYLON.VertexData();
  61360. vertexData.indices = [];
  61361. vertexData.positions = [];
  61362. vertexData.normals = [];
  61363. vertexData.uvs = [];
  61364. var currentVertexDataIndex = 0;
  61365. var extractDecalVector3 = function (indexId) {
  61366. var result = new BABYLON.PositionNormalVertex();
  61367. if (!indices || !positions || !normals) {
  61368. return result;
  61369. }
  61370. var vertexId = indices[indexId];
  61371. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61372. // Send vector to decal local world
  61373. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61374. // Get normal
  61375. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61376. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61377. return result;
  61378. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61379. var clip = function (vertices, axis) {
  61380. if (vertices.length === 0) {
  61381. return vertices;
  61382. }
  61383. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61384. var clipVertices = function (v0, v1) {
  61385. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61386. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61387. };
  61388. var result = new Array();
  61389. for (var index = 0; index < vertices.length; index += 3) {
  61390. var v1Out;
  61391. var v2Out;
  61392. var v3Out;
  61393. var total = 0;
  61394. var nV1 = null;
  61395. var nV2 = null;
  61396. var nV3 = null;
  61397. var nV4 = null;
  61398. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61399. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61400. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61401. v1Out = d1 > 0;
  61402. v2Out = d2 > 0;
  61403. v3Out = d3 > 0;
  61404. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61405. switch (total) {
  61406. case 0:
  61407. result.push(vertices[index]);
  61408. result.push(vertices[index + 1]);
  61409. result.push(vertices[index + 2]);
  61410. break;
  61411. case 1:
  61412. if (v1Out) {
  61413. nV1 = vertices[index + 1];
  61414. nV2 = vertices[index + 2];
  61415. nV3 = clipVertices(vertices[index], nV1);
  61416. nV4 = clipVertices(vertices[index], nV2);
  61417. }
  61418. if (v2Out) {
  61419. nV1 = vertices[index];
  61420. nV2 = vertices[index + 2];
  61421. nV3 = clipVertices(vertices[index + 1], nV1);
  61422. nV4 = clipVertices(vertices[index + 1], nV2);
  61423. result.push(nV3);
  61424. result.push(nV2.clone());
  61425. result.push(nV1.clone());
  61426. result.push(nV2.clone());
  61427. result.push(nV3.clone());
  61428. result.push(nV4);
  61429. break;
  61430. }
  61431. if (v3Out) {
  61432. nV1 = vertices[index];
  61433. nV2 = vertices[index + 1];
  61434. nV3 = clipVertices(vertices[index + 2], nV1);
  61435. nV4 = clipVertices(vertices[index + 2], nV2);
  61436. }
  61437. if (nV1 && nV2 && nV3 && nV4) {
  61438. result.push(nV1.clone());
  61439. result.push(nV2.clone());
  61440. result.push(nV3);
  61441. result.push(nV4);
  61442. result.push(nV3.clone());
  61443. result.push(nV2.clone());
  61444. }
  61445. break;
  61446. case 2:
  61447. if (!v1Out) {
  61448. nV1 = vertices[index].clone();
  61449. nV2 = clipVertices(nV1, vertices[index + 1]);
  61450. nV3 = clipVertices(nV1, vertices[index + 2]);
  61451. result.push(nV1);
  61452. result.push(nV2);
  61453. result.push(nV3);
  61454. }
  61455. if (!v2Out) {
  61456. nV1 = vertices[index + 1].clone();
  61457. nV2 = clipVertices(nV1, vertices[index + 2]);
  61458. nV3 = clipVertices(nV1, vertices[index]);
  61459. result.push(nV1);
  61460. result.push(nV2);
  61461. result.push(nV3);
  61462. }
  61463. if (!v3Out) {
  61464. nV1 = vertices[index + 2].clone();
  61465. nV2 = clipVertices(nV1, vertices[index]);
  61466. nV3 = clipVertices(nV1, vertices[index + 1]);
  61467. result.push(nV1);
  61468. result.push(nV2);
  61469. result.push(nV3);
  61470. }
  61471. break;
  61472. case 3:
  61473. break;
  61474. }
  61475. }
  61476. return result;
  61477. };
  61478. for (var index = 0; index < indices.length; index += 3) {
  61479. var faceVertices = new Array();
  61480. faceVertices.push(extractDecalVector3(index));
  61481. faceVertices.push(extractDecalVector3(index + 1));
  61482. faceVertices.push(extractDecalVector3(index + 2));
  61483. // Clip
  61484. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61485. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61486. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61487. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61488. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61489. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61490. if (faceVertices.length === 0) {
  61491. continue;
  61492. }
  61493. // Add UVs and get back to world
  61494. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61495. var vertex = faceVertices[vIndex];
  61496. //TODO check for Int32Array | Uint32Array | Uint16Array
  61497. vertexData.indices.push(currentVertexDataIndex);
  61498. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61499. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61500. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61501. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61502. currentVertexDataIndex++;
  61503. }
  61504. }
  61505. // Return mesh
  61506. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61507. vertexData.applyToMesh(decal);
  61508. decal.position = position.clone();
  61509. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61510. return decal;
  61511. };
  61512. // Privates
  61513. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61514. // extrusion geometry
  61515. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61516. var tangents = path3D.getTangents();
  61517. var normals = path3D.getNormals();
  61518. var binormals = path3D.getBinormals();
  61519. var distances = path3D.getDistances();
  61520. var angle = 0;
  61521. var returnScale = function () { return scale !== null ? scale : 1; };
  61522. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61523. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61524. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61525. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61526. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61527. for (var i = 0; i < curve.length; i++) {
  61528. var shapePath = new Array();
  61529. var angleStep = rotate(i, distances[i]);
  61530. var scaleRatio = scl(i, distances[i]);
  61531. for (var p = 0; p < shape.length; p++) {
  61532. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61533. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61534. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61535. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61536. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61537. shapePath[p] = rotated;
  61538. }
  61539. shapePaths[index] = shapePath;
  61540. angle += angleStep;
  61541. index++;
  61542. }
  61543. // cap
  61544. var capPath = function (shapePath) {
  61545. var pointCap = Array();
  61546. var barycenter = BABYLON.Vector3.Zero();
  61547. var i;
  61548. for (i = 0; i < shapePath.length; i++) {
  61549. barycenter.addInPlace(shapePath[i]);
  61550. }
  61551. barycenter.scaleInPlace(1.0 / shapePath.length);
  61552. for (i = 0; i < shapePath.length; i++) {
  61553. pointCap.push(barycenter);
  61554. }
  61555. return pointCap;
  61556. };
  61557. switch (cap) {
  61558. case BABYLON.Mesh.NO_CAP:
  61559. break;
  61560. case BABYLON.Mesh.CAP_START:
  61561. shapePaths[0] = capPath(shapePaths[2]);
  61562. shapePaths[1] = shapePaths[2];
  61563. break;
  61564. case BABYLON.Mesh.CAP_END:
  61565. shapePaths[index] = shapePaths[index - 1];
  61566. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61567. break;
  61568. case BABYLON.Mesh.CAP_ALL:
  61569. shapePaths[0] = capPath(shapePaths[2]);
  61570. shapePaths[1] = shapePaths[2];
  61571. shapePaths[index] = shapePaths[index - 1];
  61572. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61573. break;
  61574. default:
  61575. break;
  61576. }
  61577. return shapePaths;
  61578. };
  61579. var path3D;
  61580. var pathArray;
  61581. if (instance) { // instance update
  61582. path3D = (instance.path3D).update(curve);
  61583. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61584. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61585. return instance;
  61586. }
  61587. // extruded shape creation
  61588. path3D = new BABYLON.Path3D(curve);
  61589. var newShapePaths = new Array();
  61590. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61591. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61592. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61593. extrudedGeneric.pathArray = pathArray;
  61594. extrudedGeneric.path3D = path3D;
  61595. extrudedGeneric.cap = cap;
  61596. return extrudedGeneric;
  61597. };
  61598. return MeshBuilder;
  61599. }());
  61600. BABYLON.MeshBuilder = MeshBuilder;
  61601. })(BABYLON || (BABYLON = {}));
  61602. //# sourceMappingURL=babylon.meshBuilder.js.map
  61603. var BABYLON;
  61604. (function (BABYLON) {
  61605. /**
  61606. * Draco compression (https://google.github.io/draco/)
  61607. */
  61608. var DracoCompression = /** @class */ (function () {
  61609. /**
  61610. * Constructor
  61611. */
  61612. function DracoCompression() {
  61613. }
  61614. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61615. /**
  61616. * Returns true if the decoder is available.
  61617. */
  61618. get: function () {
  61619. if (typeof DracoDecoderModule !== "undefined") {
  61620. return true;
  61621. }
  61622. var decoder = DracoCompression.Configuration.decoder;
  61623. if (decoder) {
  61624. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61625. return true;
  61626. }
  61627. if (decoder.fallbackUrl) {
  61628. return true;
  61629. }
  61630. }
  61631. return false;
  61632. },
  61633. enumerable: true,
  61634. configurable: true
  61635. });
  61636. /**
  61637. * Stop all async operations and release resources.
  61638. */
  61639. DracoCompression.prototype.dispose = function () {
  61640. };
  61641. /**
  61642. * Decode Draco compressed mesh data to vertex data.
  61643. * @param data The array buffer view for the Draco compression data
  61644. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61645. * @returns A promise that resolves with the decoded vertex data
  61646. */
  61647. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61648. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61649. var module = wrappedModule.module;
  61650. var vertexData = new BABYLON.VertexData();
  61651. var buffer = new module.DecoderBuffer();
  61652. buffer.Init(data, data.byteLength);
  61653. var decoder = new module.Decoder();
  61654. var geometry;
  61655. var status;
  61656. try {
  61657. var type = decoder.GetEncodedGeometryType(buffer);
  61658. switch (type) {
  61659. case module.TRIANGULAR_MESH:
  61660. geometry = new module.Mesh();
  61661. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61662. break;
  61663. case module.POINT_CLOUD:
  61664. geometry = new module.PointCloud();
  61665. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61666. break;
  61667. default:
  61668. throw new Error("Invalid geometry type " + type);
  61669. }
  61670. if (!status.ok() || !geometry.ptr) {
  61671. throw new Error(status.error_msg());
  61672. }
  61673. var numPoints = geometry.num_points();
  61674. if (type === module.TRIANGULAR_MESH) {
  61675. var numFaces = geometry.num_faces();
  61676. var faceIndices = new module.DracoInt32Array();
  61677. try {
  61678. var indices = new Uint32Array(numFaces * 3);
  61679. for (var i = 0; i < numFaces; i++) {
  61680. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61681. var offset = i * 3;
  61682. indices[offset + 0] = faceIndices.GetValue(0);
  61683. indices[offset + 1] = faceIndices.GetValue(1);
  61684. indices[offset + 2] = faceIndices.GetValue(2);
  61685. }
  61686. vertexData.indices = indices;
  61687. }
  61688. finally {
  61689. module.destroy(faceIndices);
  61690. }
  61691. }
  61692. for (var kind in attributes) {
  61693. var uniqueId = attributes[kind];
  61694. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61695. var dracoData = new module.DracoFloat32Array();
  61696. try {
  61697. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61698. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61699. for (var i = 0; i < babylonData.length; i++) {
  61700. babylonData[i] = dracoData.GetValue(i);
  61701. }
  61702. vertexData.set(babylonData, kind);
  61703. }
  61704. finally {
  61705. module.destroy(dracoData);
  61706. }
  61707. }
  61708. }
  61709. finally {
  61710. if (geometry) {
  61711. module.destroy(geometry);
  61712. }
  61713. module.destroy(decoder);
  61714. module.destroy(buffer);
  61715. }
  61716. return vertexData;
  61717. });
  61718. };
  61719. DracoCompression._GetDecoderModule = function () {
  61720. if (!DracoCompression._DecoderModulePromise) {
  61721. var promise = null;
  61722. var config_1 = {};
  61723. if (typeof DracoDecoderModule !== "undefined") {
  61724. promise = Promise.resolve();
  61725. }
  61726. else {
  61727. var decoder = DracoCompression.Configuration.decoder;
  61728. if (decoder) {
  61729. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61730. promise = Promise.all([
  61731. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61732. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61733. config_1.wasmBinary = data;
  61734. })
  61735. ]);
  61736. }
  61737. else if (decoder.fallbackUrl) {
  61738. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61739. }
  61740. }
  61741. }
  61742. if (!promise) {
  61743. throw new Error("Draco decoder module is not available");
  61744. }
  61745. DracoCompression._DecoderModulePromise = promise.then(function () {
  61746. return new Promise(function (resolve) {
  61747. config_1.onModuleLoaded = function (decoderModule) {
  61748. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61749. resolve({ module: decoderModule });
  61750. };
  61751. DracoDecoderModule(config_1);
  61752. });
  61753. });
  61754. }
  61755. return DracoCompression._DecoderModulePromise;
  61756. };
  61757. DracoCompression._LoadScriptAsync = function (url) {
  61758. return new Promise(function (resolve, reject) {
  61759. BABYLON.Tools.LoadScript(url, function () {
  61760. resolve();
  61761. }, function (message) {
  61762. reject(new Error(message));
  61763. });
  61764. });
  61765. };
  61766. DracoCompression._LoadFileAsync = function (url) {
  61767. return new Promise(function (resolve, reject) {
  61768. BABYLON.Tools.LoadFile(url, function (data) {
  61769. resolve(data);
  61770. }, undefined, undefined, true, function (request, exception) {
  61771. reject(exception);
  61772. });
  61773. });
  61774. };
  61775. /**
  61776. * The configuration.
  61777. */
  61778. DracoCompression.Configuration = {
  61779. decoder: {
  61780. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61781. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61782. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61783. }
  61784. };
  61785. return DracoCompression;
  61786. }());
  61787. BABYLON.DracoCompression = DracoCompression;
  61788. })(BABYLON || (BABYLON = {}));
  61789. //# sourceMappingURL=babylon.dracoCompression.js.map
  61790. var BABYLON;
  61791. (function (BABYLON) {
  61792. var AudioEngine = /** @class */ (function () {
  61793. function AudioEngine() {
  61794. this._audioContext = null;
  61795. this._audioContextInitialized = false;
  61796. this.canUseWebAudio = false;
  61797. this.WarnedWebAudioUnsupported = false;
  61798. this.unlocked = false;
  61799. this.isMP3supported = false;
  61800. this.isOGGsupported = false;
  61801. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61802. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61803. this.canUseWebAudio = true;
  61804. }
  61805. var audioElem = document.createElement('audio');
  61806. try {
  61807. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61808. this.isMP3supported = true;
  61809. }
  61810. }
  61811. catch (e) {
  61812. // protect error during capability check.
  61813. }
  61814. try {
  61815. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61816. this.isOGGsupported = true;
  61817. }
  61818. }
  61819. catch (e) {
  61820. // protect error during capability check.
  61821. }
  61822. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61823. this._unlockiOSaudio();
  61824. }
  61825. else {
  61826. this.unlocked = true;
  61827. }
  61828. }
  61829. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61830. get: function () {
  61831. if (!this._audioContextInitialized) {
  61832. this._initializeAudioContext();
  61833. }
  61834. return this._audioContext;
  61835. },
  61836. enumerable: true,
  61837. configurable: true
  61838. });
  61839. AudioEngine.prototype._unlockiOSaudio = function () {
  61840. var _this = this;
  61841. var unlockaudio = function () {
  61842. if (!_this.audioContext) {
  61843. return;
  61844. }
  61845. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61846. var source = _this.audioContext.createBufferSource();
  61847. source.buffer = buffer;
  61848. source.connect(_this.audioContext.destination);
  61849. source.start(0);
  61850. setTimeout(function () {
  61851. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61852. _this.unlocked = true;
  61853. window.removeEventListener('touchend', unlockaudio, false);
  61854. if (_this.onAudioUnlocked) {
  61855. _this.onAudioUnlocked();
  61856. }
  61857. }
  61858. }, 0);
  61859. };
  61860. window.addEventListener('touchend', unlockaudio, false);
  61861. };
  61862. AudioEngine.prototype._initializeAudioContext = function () {
  61863. try {
  61864. if (this.canUseWebAudio) {
  61865. this._audioContext = new AudioContext();
  61866. // create a global volume gain node
  61867. this.masterGain = this._audioContext.createGain();
  61868. this.masterGain.gain.value = 1;
  61869. this.masterGain.connect(this._audioContext.destination);
  61870. this._audioContextInitialized = true;
  61871. }
  61872. }
  61873. catch (e) {
  61874. this.canUseWebAudio = false;
  61875. BABYLON.Tools.Error("Web Audio: " + e.message);
  61876. }
  61877. };
  61878. AudioEngine.prototype.dispose = function () {
  61879. if (this.canUseWebAudio && this._audioContextInitialized) {
  61880. if (this._connectedAnalyser && this._audioContext) {
  61881. this._connectedAnalyser.stopDebugCanvas();
  61882. this._connectedAnalyser.dispose();
  61883. this.masterGain.disconnect();
  61884. this.masterGain.connect(this._audioContext.destination);
  61885. this._connectedAnalyser = null;
  61886. }
  61887. this.masterGain.gain.value = 1;
  61888. }
  61889. this.WarnedWebAudioUnsupported = false;
  61890. };
  61891. AudioEngine.prototype.getGlobalVolume = function () {
  61892. if (this.canUseWebAudio && this._audioContextInitialized) {
  61893. return this.masterGain.gain.value;
  61894. }
  61895. else {
  61896. return -1;
  61897. }
  61898. };
  61899. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  61900. if (this.canUseWebAudio && this._audioContextInitialized) {
  61901. this.masterGain.gain.value = newVolume;
  61902. }
  61903. };
  61904. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  61905. if (this._connectedAnalyser) {
  61906. this._connectedAnalyser.stopDebugCanvas();
  61907. }
  61908. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  61909. this._connectedAnalyser = analyser;
  61910. this.masterGain.disconnect();
  61911. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  61912. }
  61913. };
  61914. return AudioEngine;
  61915. }());
  61916. BABYLON.AudioEngine = AudioEngine;
  61917. })(BABYLON || (BABYLON = {}));
  61918. //# sourceMappingURL=babylon.audioEngine.js.map
  61919. var BABYLON;
  61920. (function (BABYLON) {
  61921. var Sound = /** @class */ (function () {
  61922. /**
  61923. * Create a sound and attach it to a scene
  61924. * @param name Name of your sound
  61925. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  61926. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  61927. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  61928. */
  61929. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  61930. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  61931. var _this = this;
  61932. this.autoplay = false;
  61933. this.loop = false;
  61934. this.useCustomAttenuation = false;
  61935. this.spatialSound = false;
  61936. this.refDistance = 1;
  61937. this.rolloffFactor = 1;
  61938. this.maxDistance = 100;
  61939. this.distanceModel = "linear";
  61940. this._panningModel = "equalpower";
  61941. this._playbackRate = 1;
  61942. this._streaming = false;
  61943. this._startTime = 0;
  61944. this._startOffset = 0;
  61945. this._position = BABYLON.Vector3.Zero();
  61946. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  61947. this._volume = 1;
  61948. this._isReadyToPlay = false;
  61949. this.isPlaying = false;
  61950. this.isPaused = false;
  61951. this._isDirectional = false;
  61952. // Used if you'd like to create a directional sound.
  61953. // If not set, the sound will be omnidirectional
  61954. this._coneInnerAngle = 360;
  61955. this._coneOuterAngle = 360;
  61956. this._coneOuterGain = 0;
  61957. this._isOutputConnected = false;
  61958. this._urlType = "Unknown";
  61959. this.name = name;
  61960. this._scene = scene;
  61961. this._readyToPlayCallback = readyToPlayCallback;
  61962. // Default custom attenuation function is a linear attenuation
  61963. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  61964. if (currentDistance < maxDistance) {
  61965. return currentVolume * (1 - currentDistance / maxDistance);
  61966. }
  61967. else {
  61968. return 0;
  61969. }
  61970. };
  61971. if (options) {
  61972. this.autoplay = options.autoplay || false;
  61973. this.loop = options.loop || false;
  61974. // if volume === 0, we need another way to check this option
  61975. if (options.volume !== undefined) {
  61976. this._volume = options.volume;
  61977. }
  61978. this.spatialSound = options.spatialSound || false;
  61979. this.maxDistance = options.maxDistance || 100;
  61980. this.useCustomAttenuation = options.useCustomAttenuation || false;
  61981. this.rolloffFactor = options.rolloffFactor || 1;
  61982. this.refDistance = options.refDistance || 1;
  61983. this.distanceModel = options.distanceModel || "linear";
  61984. this._playbackRate = options.playbackRate || 1;
  61985. this._streaming = options.streaming || false;
  61986. }
  61987. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  61988. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  61989. this._soundGain.gain.value = this._volume;
  61990. this._inputAudioNode = this._soundGain;
  61991. this._ouputAudioNode = this._soundGain;
  61992. if (this.spatialSound) {
  61993. this._createSpatialParameters();
  61994. }
  61995. this._scene.mainSoundTrack.AddSound(this);
  61996. var validParameter = true;
  61997. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  61998. if (urlOrArrayBuffer) {
  61999. try {
  62000. if (typeof (urlOrArrayBuffer) === "string")
  62001. this._urlType = "String";
  62002. if (Array.isArray(urlOrArrayBuffer))
  62003. this._urlType = "Array";
  62004. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62005. this._urlType = "ArrayBuffer";
  62006. var urls = [];
  62007. var codecSupportedFound = false;
  62008. switch (this._urlType) {
  62009. case "ArrayBuffer":
  62010. if (urlOrArrayBuffer.byteLength > 0) {
  62011. codecSupportedFound = true;
  62012. this._soundLoaded(urlOrArrayBuffer);
  62013. }
  62014. break;
  62015. case "String":
  62016. urls.push(urlOrArrayBuffer);
  62017. case "Array":
  62018. if (urls.length === 0)
  62019. urls = urlOrArrayBuffer;
  62020. // If we found a supported format, we load it immediately and stop the loop
  62021. for (var i = 0; i < urls.length; i++) {
  62022. var url = urls[i];
  62023. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62024. codecSupportedFound = true;
  62025. }
  62026. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62027. codecSupportedFound = true;
  62028. }
  62029. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62030. codecSupportedFound = true;
  62031. }
  62032. if (url.indexOf("blob:") !== -1) {
  62033. codecSupportedFound = true;
  62034. }
  62035. if (codecSupportedFound) {
  62036. // Loading sound using XHR2
  62037. if (!this._streaming) {
  62038. this._scene._loadFile(url, function (data) {
  62039. _this._soundLoaded(data);
  62040. }, undefined, true, true, function (exception) {
  62041. if (exception) {
  62042. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62043. }
  62044. BABYLON.Tools.Error("Sound creation aborted.");
  62045. _this._scene.mainSoundTrack.RemoveSound(_this);
  62046. });
  62047. }
  62048. // Streaming sound using HTML5 Audio tag
  62049. else {
  62050. this._htmlAudioElement = new Audio(url);
  62051. this._htmlAudioElement.controls = false;
  62052. this._htmlAudioElement.loop = this.loop;
  62053. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62054. this._htmlAudioElement.preload = "auto";
  62055. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62056. _this._isReadyToPlay = true;
  62057. if (_this.autoplay) {
  62058. _this.play();
  62059. }
  62060. if (_this._readyToPlayCallback) {
  62061. _this._readyToPlayCallback();
  62062. }
  62063. });
  62064. document.body.appendChild(this._htmlAudioElement);
  62065. }
  62066. break;
  62067. }
  62068. }
  62069. break;
  62070. default:
  62071. validParameter = false;
  62072. break;
  62073. }
  62074. if (!validParameter) {
  62075. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62076. }
  62077. else {
  62078. if (!codecSupportedFound) {
  62079. this._isReadyToPlay = true;
  62080. // Simulating a ready to play event to avoid breaking code path
  62081. if (this._readyToPlayCallback) {
  62082. window.setTimeout(function () {
  62083. if (_this._readyToPlayCallback) {
  62084. _this._readyToPlayCallback();
  62085. }
  62086. }, 1000);
  62087. }
  62088. }
  62089. }
  62090. }
  62091. catch (ex) {
  62092. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62093. this._scene.mainSoundTrack.RemoveSound(this);
  62094. }
  62095. }
  62096. }
  62097. else {
  62098. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62099. this._scene.mainSoundTrack.AddSound(this);
  62100. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62101. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62102. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62103. }
  62104. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62105. if (this._readyToPlayCallback) {
  62106. window.setTimeout(function () {
  62107. if (_this._readyToPlayCallback) {
  62108. _this._readyToPlayCallback();
  62109. }
  62110. }, 1000);
  62111. }
  62112. }
  62113. }
  62114. Sound.prototype.dispose = function () {
  62115. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62116. if (this.isPlaying) {
  62117. this.stop();
  62118. }
  62119. this._isReadyToPlay = false;
  62120. if (this.soundTrackId === -1) {
  62121. this._scene.mainSoundTrack.RemoveSound(this);
  62122. }
  62123. else {
  62124. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62125. }
  62126. if (this._soundGain) {
  62127. this._soundGain.disconnect();
  62128. this._soundGain = null;
  62129. }
  62130. if (this._soundPanner) {
  62131. this._soundPanner.disconnect();
  62132. this._soundPanner = null;
  62133. }
  62134. if (this._soundSource) {
  62135. this._soundSource.disconnect();
  62136. this._soundSource = null;
  62137. }
  62138. this._audioBuffer = null;
  62139. if (this._htmlAudioElement) {
  62140. this._htmlAudioElement.pause();
  62141. this._htmlAudioElement.src = "";
  62142. document.body.removeChild(this._htmlAudioElement);
  62143. }
  62144. if (this._connectedMesh && this._registerFunc) {
  62145. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62146. this._connectedMesh = null;
  62147. }
  62148. }
  62149. };
  62150. Sound.prototype.isReady = function () {
  62151. return this._isReadyToPlay;
  62152. };
  62153. Sound.prototype._soundLoaded = function (audioData) {
  62154. var _this = this;
  62155. if (!BABYLON.Engine.audioEngine.audioContext) {
  62156. return;
  62157. }
  62158. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62159. _this._audioBuffer = buffer;
  62160. _this._isReadyToPlay = true;
  62161. if (_this.autoplay) {
  62162. _this.play();
  62163. }
  62164. if (_this._readyToPlayCallback) {
  62165. _this._readyToPlayCallback();
  62166. }
  62167. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62168. };
  62169. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62170. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62171. this._audioBuffer = audioBuffer;
  62172. this._isReadyToPlay = true;
  62173. }
  62174. };
  62175. Sound.prototype.updateOptions = function (options) {
  62176. if (options) {
  62177. this.loop = options.loop || this.loop;
  62178. this.maxDistance = options.maxDistance || this.maxDistance;
  62179. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62180. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62181. this.refDistance = options.refDistance || this.refDistance;
  62182. this.distanceModel = options.distanceModel || this.distanceModel;
  62183. this._playbackRate = options.playbackRate || this._playbackRate;
  62184. this._updateSpatialParameters();
  62185. if (this.isPlaying) {
  62186. if (this._streaming) {
  62187. this._htmlAudioElement.playbackRate = this._playbackRate;
  62188. }
  62189. else {
  62190. if (this._soundSource) {
  62191. this._soundSource.playbackRate.value = this._playbackRate;
  62192. }
  62193. }
  62194. }
  62195. }
  62196. };
  62197. Sound.prototype._createSpatialParameters = function () {
  62198. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62199. if (this._scene.headphone) {
  62200. this._panningModel = "HRTF";
  62201. }
  62202. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62203. this._updateSpatialParameters();
  62204. this._soundPanner.connect(this._ouputAudioNode);
  62205. this._inputAudioNode = this._soundPanner;
  62206. }
  62207. };
  62208. Sound.prototype._updateSpatialParameters = function () {
  62209. if (this.spatialSound && this._soundPanner) {
  62210. if (this.useCustomAttenuation) {
  62211. // Tricks to disable in a way embedded Web Audio attenuation
  62212. this._soundPanner.distanceModel = "linear";
  62213. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62214. this._soundPanner.refDistance = 1;
  62215. this._soundPanner.rolloffFactor = 1;
  62216. this._soundPanner.panningModel = this._panningModel;
  62217. }
  62218. else {
  62219. this._soundPanner.distanceModel = this.distanceModel;
  62220. this._soundPanner.maxDistance = this.maxDistance;
  62221. this._soundPanner.refDistance = this.refDistance;
  62222. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62223. this._soundPanner.panningModel = this._panningModel;
  62224. }
  62225. }
  62226. };
  62227. Sound.prototype.switchPanningModelToHRTF = function () {
  62228. this._panningModel = "HRTF";
  62229. this._switchPanningModel();
  62230. };
  62231. Sound.prototype.switchPanningModelToEqualPower = function () {
  62232. this._panningModel = "equalpower";
  62233. this._switchPanningModel();
  62234. };
  62235. Sound.prototype._switchPanningModel = function () {
  62236. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62237. this._soundPanner.panningModel = this._panningModel;
  62238. }
  62239. };
  62240. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62241. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62242. if (this._isOutputConnected) {
  62243. this._ouputAudioNode.disconnect();
  62244. }
  62245. this._ouputAudioNode.connect(soundTrackAudioNode);
  62246. this._isOutputConnected = true;
  62247. }
  62248. };
  62249. /**
  62250. * Transform this sound into a directional source
  62251. * @param coneInnerAngle Size of the inner cone in degree
  62252. * @param coneOuterAngle Size of the outer cone in degree
  62253. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62254. */
  62255. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62256. if (coneOuterAngle < coneInnerAngle) {
  62257. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62258. return;
  62259. }
  62260. this._coneInnerAngle = coneInnerAngle;
  62261. this._coneOuterAngle = coneOuterAngle;
  62262. this._coneOuterGain = coneOuterGain;
  62263. this._isDirectional = true;
  62264. if (this.isPlaying && this.loop) {
  62265. this.stop();
  62266. this.play();
  62267. }
  62268. };
  62269. Sound.prototype.setPosition = function (newPosition) {
  62270. this._position = newPosition;
  62271. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62272. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62273. }
  62274. };
  62275. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62276. this._localDirection = newLocalDirection;
  62277. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62278. this._updateDirection();
  62279. }
  62280. };
  62281. Sound.prototype._updateDirection = function () {
  62282. if (!this._connectedMesh || !this._soundPanner) {
  62283. return;
  62284. }
  62285. var mat = this._connectedMesh.getWorldMatrix();
  62286. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62287. direction.normalize();
  62288. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62289. };
  62290. Sound.prototype.updateDistanceFromListener = function () {
  62291. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62292. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62293. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62294. }
  62295. };
  62296. Sound.prototype.setAttenuationFunction = function (callback) {
  62297. this._customAttenuationFunction = callback;
  62298. };
  62299. /**
  62300. * Play the sound
  62301. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62302. * @param offset (optional) Start the sound setting it at a specific time
  62303. */
  62304. Sound.prototype.play = function (time, offset) {
  62305. var _this = this;
  62306. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62307. try {
  62308. if (this._startOffset < 0) {
  62309. time = -this._startOffset;
  62310. this._startOffset = 0;
  62311. }
  62312. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62313. if (!this._soundSource || !this._streamingSource) {
  62314. if (this.spatialSound && this._soundPanner) {
  62315. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62316. if (this._isDirectional) {
  62317. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62318. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62319. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62320. if (this._connectedMesh) {
  62321. this._updateDirection();
  62322. }
  62323. else {
  62324. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62325. }
  62326. }
  62327. }
  62328. }
  62329. if (this._streaming) {
  62330. if (!this._streamingSource) {
  62331. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62332. this._htmlAudioElement.onended = function () { _this._onended(); };
  62333. this._htmlAudioElement.playbackRate = this._playbackRate;
  62334. }
  62335. this._streamingSource.disconnect();
  62336. this._streamingSource.connect(this._inputAudioNode);
  62337. this._htmlAudioElement.play();
  62338. }
  62339. else {
  62340. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62341. this._soundSource.buffer = this._audioBuffer;
  62342. this._soundSource.connect(this._inputAudioNode);
  62343. this._soundSource.loop = this.loop;
  62344. this._soundSource.playbackRate.value = this._playbackRate;
  62345. this._soundSource.onended = function () { _this._onended(); };
  62346. if (this._soundSource.buffer) {
  62347. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62348. }
  62349. }
  62350. this._startTime = startTime;
  62351. this.isPlaying = true;
  62352. this.isPaused = false;
  62353. }
  62354. catch (ex) {
  62355. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62356. }
  62357. }
  62358. };
  62359. Sound.prototype._onended = function () {
  62360. this.isPlaying = false;
  62361. if (this.onended) {
  62362. this.onended();
  62363. }
  62364. };
  62365. /**
  62366. * Stop the sound
  62367. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62368. */
  62369. Sound.prototype.stop = function (time) {
  62370. if (this.isPlaying) {
  62371. if (this._streaming) {
  62372. this._htmlAudioElement.pause();
  62373. // Test needed for Firefox or it will generate an Invalid State Error
  62374. if (this._htmlAudioElement.currentTime > 0) {
  62375. this._htmlAudioElement.currentTime = 0;
  62376. }
  62377. }
  62378. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62379. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62380. this._soundSource.stop(stopTime);
  62381. this._soundSource.onended = function () { };
  62382. if (!this.isPaused) {
  62383. this._startOffset = 0;
  62384. }
  62385. }
  62386. this.isPlaying = false;
  62387. }
  62388. };
  62389. Sound.prototype.pause = function () {
  62390. if (this.isPlaying) {
  62391. this.isPaused = true;
  62392. if (this._streaming) {
  62393. this._htmlAudioElement.pause();
  62394. }
  62395. else if (BABYLON.Engine.audioEngine.audioContext) {
  62396. this.stop(0);
  62397. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62398. }
  62399. }
  62400. };
  62401. Sound.prototype.setVolume = function (newVolume, time) {
  62402. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62403. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62404. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62405. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62406. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62407. }
  62408. else {
  62409. this._soundGain.gain.value = newVolume;
  62410. }
  62411. }
  62412. this._volume = newVolume;
  62413. };
  62414. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62415. this._playbackRate = newPlaybackRate;
  62416. if (this.isPlaying) {
  62417. if (this._streaming) {
  62418. this._htmlAudioElement.playbackRate = this._playbackRate;
  62419. }
  62420. else if (this._soundSource) {
  62421. this._soundSource.playbackRate.value = this._playbackRate;
  62422. }
  62423. }
  62424. };
  62425. Sound.prototype.getVolume = function () {
  62426. return this._volume;
  62427. };
  62428. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62429. var _this = this;
  62430. if (this._connectedMesh && this._registerFunc) {
  62431. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62432. this._registerFunc = null;
  62433. }
  62434. this._connectedMesh = meshToConnectTo;
  62435. if (!this.spatialSound) {
  62436. this.spatialSound = true;
  62437. this._createSpatialParameters();
  62438. if (this.isPlaying && this.loop) {
  62439. this.stop();
  62440. this.play();
  62441. }
  62442. }
  62443. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62444. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62445. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62446. };
  62447. Sound.prototype.detachFromMesh = function () {
  62448. if (this._connectedMesh && this._registerFunc) {
  62449. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62450. this._registerFunc = null;
  62451. this._connectedMesh = null;
  62452. }
  62453. };
  62454. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62455. if (!node.getBoundingInfo) {
  62456. return;
  62457. }
  62458. var mesh = node;
  62459. var boundingInfo = mesh.getBoundingInfo();
  62460. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62461. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62462. this._updateDirection();
  62463. }
  62464. };
  62465. Sound.prototype.clone = function () {
  62466. var _this = this;
  62467. if (!this._streaming) {
  62468. var setBufferAndRun = function () {
  62469. if (_this._isReadyToPlay) {
  62470. clonedSound._audioBuffer = _this.getAudioBuffer();
  62471. clonedSound._isReadyToPlay = true;
  62472. if (clonedSound.autoplay) {
  62473. clonedSound.play();
  62474. }
  62475. }
  62476. else {
  62477. window.setTimeout(setBufferAndRun, 300);
  62478. }
  62479. };
  62480. var currentOptions = {
  62481. autoplay: this.autoplay, loop: this.loop,
  62482. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62483. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62484. refDistance: this.refDistance, distanceModel: this.distanceModel
  62485. };
  62486. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62487. if (this.useCustomAttenuation) {
  62488. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62489. }
  62490. clonedSound.setPosition(this._position);
  62491. clonedSound.setPlaybackRate(this._playbackRate);
  62492. setBufferAndRun();
  62493. return clonedSound;
  62494. }
  62495. // Can't clone a streaming sound
  62496. else {
  62497. return null;
  62498. }
  62499. };
  62500. Sound.prototype.getAudioBuffer = function () {
  62501. return this._audioBuffer;
  62502. };
  62503. Sound.prototype.serialize = function () {
  62504. var serializationObject = {
  62505. name: this.name,
  62506. url: this.name,
  62507. autoplay: this.autoplay,
  62508. loop: this.loop,
  62509. volume: this._volume,
  62510. spatialSound: this.spatialSound,
  62511. maxDistance: this.maxDistance,
  62512. rolloffFactor: this.rolloffFactor,
  62513. refDistance: this.refDistance,
  62514. distanceModel: this.distanceModel,
  62515. playbackRate: this._playbackRate,
  62516. panningModel: this._panningModel,
  62517. soundTrackId: this.soundTrackId
  62518. };
  62519. if (this.spatialSound) {
  62520. if (this._connectedMesh)
  62521. serializationObject.connectedMeshId = this._connectedMesh.id;
  62522. serializationObject.position = this._position.asArray();
  62523. serializationObject.refDistance = this.refDistance;
  62524. serializationObject.distanceModel = this.distanceModel;
  62525. serializationObject.isDirectional = this._isDirectional;
  62526. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62527. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62528. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62529. serializationObject.coneOuterGain = this._coneOuterGain;
  62530. }
  62531. return serializationObject;
  62532. };
  62533. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62534. var soundName = parsedSound.name;
  62535. var soundUrl;
  62536. if (parsedSound.url) {
  62537. soundUrl = rootUrl + parsedSound.url;
  62538. }
  62539. else {
  62540. soundUrl = rootUrl + soundName;
  62541. }
  62542. var options = {
  62543. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62544. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62545. rolloffFactor: parsedSound.rolloffFactor,
  62546. refDistance: parsedSound.refDistance,
  62547. distanceModel: parsedSound.distanceModel,
  62548. playbackRate: parsedSound.playbackRate
  62549. };
  62550. var newSound;
  62551. if (!sourceSound) {
  62552. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62553. scene._addPendingData(newSound);
  62554. }
  62555. else {
  62556. var setBufferAndRun = function () {
  62557. if (sourceSound._isReadyToPlay) {
  62558. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62559. newSound._isReadyToPlay = true;
  62560. if (newSound.autoplay) {
  62561. newSound.play();
  62562. }
  62563. }
  62564. else {
  62565. window.setTimeout(setBufferAndRun, 300);
  62566. }
  62567. };
  62568. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62569. setBufferAndRun();
  62570. }
  62571. if (parsedSound.position) {
  62572. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62573. newSound.setPosition(soundPosition);
  62574. }
  62575. if (parsedSound.isDirectional) {
  62576. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62577. if (parsedSound.localDirectionToMesh) {
  62578. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62579. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62580. }
  62581. }
  62582. if (parsedSound.connectedMeshId) {
  62583. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62584. if (connectedMesh) {
  62585. newSound.attachToMesh(connectedMesh);
  62586. }
  62587. }
  62588. return newSound;
  62589. };
  62590. return Sound;
  62591. }());
  62592. BABYLON.Sound = Sound;
  62593. })(BABYLON || (BABYLON = {}));
  62594. //# sourceMappingURL=babylon.sound.js.map
  62595. var BABYLON;
  62596. (function (BABYLON) {
  62597. var SoundTrack = /** @class */ (function () {
  62598. function SoundTrack(scene, options) {
  62599. this.id = -1;
  62600. this._isMainTrack = false;
  62601. this._isInitialized = false;
  62602. this._scene = scene;
  62603. this.soundCollection = new Array();
  62604. this._options = options;
  62605. if (!this._isMainTrack) {
  62606. this._scene.soundTracks.push(this);
  62607. this.id = this._scene.soundTracks.length - 1;
  62608. }
  62609. }
  62610. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62611. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62612. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62613. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62614. if (this._options) {
  62615. if (this._options.volume) {
  62616. this._outputAudioNode.gain.value = this._options.volume;
  62617. }
  62618. if (this._options.mainTrack) {
  62619. this._isMainTrack = this._options.mainTrack;
  62620. }
  62621. }
  62622. this._isInitialized = true;
  62623. }
  62624. };
  62625. SoundTrack.prototype.dispose = function () {
  62626. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62627. if (this._connectedAnalyser) {
  62628. this._connectedAnalyser.stopDebugCanvas();
  62629. }
  62630. while (this.soundCollection.length) {
  62631. this.soundCollection[0].dispose();
  62632. }
  62633. if (this._outputAudioNode) {
  62634. this._outputAudioNode.disconnect();
  62635. }
  62636. this._outputAudioNode = null;
  62637. }
  62638. };
  62639. SoundTrack.prototype.AddSound = function (sound) {
  62640. if (!this._isInitialized) {
  62641. this._initializeSoundTrackAudioGraph();
  62642. }
  62643. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62644. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62645. }
  62646. if (sound.soundTrackId) {
  62647. if (sound.soundTrackId === -1) {
  62648. this._scene.mainSoundTrack.RemoveSound(sound);
  62649. }
  62650. else {
  62651. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62652. }
  62653. }
  62654. this.soundCollection.push(sound);
  62655. sound.soundTrackId = this.id;
  62656. };
  62657. SoundTrack.prototype.RemoveSound = function (sound) {
  62658. var index = this.soundCollection.indexOf(sound);
  62659. if (index !== -1) {
  62660. this.soundCollection.splice(index, 1);
  62661. }
  62662. };
  62663. SoundTrack.prototype.setVolume = function (newVolume) {
  62664. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62665. this._outputAudioNode.gain.value = newVolume;
  62666. }
  62667. };
  62668. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62669. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62670. for (var i = 0; i < this.soundCollection.length; i++) {
  62671. this.soundCollection[i].switchPanningModelToHRTF();
  62672. }
  62673. }
  62674. };
  62675. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62676. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62677. for (var i = 0; i < this.soundCollection.length; i++) {
  62678. this.soundCollection[i].switchPanningModelToEqualPower();
  62679. }
  62680. }
  62681. };
  62682. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62683. if (this._connectedAnalyser) {
  62684. this._connectedAnalyser.stopDebugCanvas();
  62685. }
  62686. this._connectedAnalyser = analyser;
  62687. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62688. this._outputAudioNode.disconnect();
  62689. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62690. }
  62691. };
  62692. return SoundTrack;
  62693. }());
  62694. BABYLON.SoundTrack = SoundTrack;
  62695. })(BABYLON || (BABYLON = {}));
  62696. //# sourceMappingURL=babylon.soundtrack.js.map
  62697. var BABYLON;
  62698. (function (BABYLON) {
  62699. /**
  62700. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62701. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62702. */
  62703. var Analyser = /** @class */ (function () {
  62704. /**
  62705. * Creates a new analyser
  62706. * @param scene defines hosting scene
  62707. */
  62708. function Analyser(scene) {
  62709. /**
  62710. * Gets or sets the smoothing
  62711. * @ignorenaming
  62712. */
  62713. this.SMOOTHING = 0.75;
  62714. /**
  62715. * Gets or sets the FFT table size
  62716. * @ignorenaming
  62717. */
  62718. this.FFT_SIZE = 512;
  62719. /**
  62720. * Gets or sets the bar graph amplitude
  62721. * @ignorenaming
  62722. */
  62723. this.BARGRAPHAMPLITUDE = 256;
  62724. /**
  62725. * Gets or sets the position of the debug canvas
  62726. * @ignorenaming
  62727. */
  62728. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62729. /**
  62730. * Gets or sets the debug canvas size
  62731. * @ignorenaming
  62732. */
  62733. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62734. this._scene = scene;
  62735. this._audioEngine = BABYLON.Engine.audioEngine;
  62736. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62737. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62738. this._webAudioAnalyser.minDecibels = -140;
  62739. this._webAudioAnalyser.maxDecibels = 0;
  62740. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62741. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62742. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62743. }
  62744. }
  62745. /**
  62746. * Get the number of data values you will have to play with for the visualization
  62747. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62748. * @returns a number
  62749. */
  62750. Analyser.prototype.getFrequencyBinCount = function () {
  62751. if (this._audioEngine.canUseWebAudio) {
  62752. return this._webAudioAnalyser.frequencyBinCount;
  62753. }
  62754. else {
  62755. return 0;
  62756. }
  62757. };
  62758. /**
  62759. * Gets the current frequency data as a byte array
  62760. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62761. * @returns a Uint8Array
  62762. */
  62763. Analyser.prototype.getByteFrequencyData = function () {
  62764. if (this._audioEngine.canUseWebAudio) {
  62765. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62766. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62767. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62768. }
  62769. return this._byteFreqs;
  62770. };
  62771. /**
  62772. * Gets the current waveform as a byte array
  62773. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62774. * @returns a Uint8Array
  62775. */
  62776. Analyser.prototype.getByteTimeDomainData = function () {
  62777. if (this._audioEngine.canUseWebAudio) {
  62778. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62779. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62780. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62781. }
  62782. return this._byteTime;
  62783. };
  62784. /**
  62785. * Gets the current frequency data as a float array
  62786. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62787. * @returns a Float32Array
  62788. */
  62789. Analyser.prototype.getFloatFrequencyData = function () {
  62790. if (this._audioEngine.canUseWebAudio) {
  62791. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62792. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62793. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62794. }
  62795. return this._floatFreqs;
  62796. };
  62797. /**
  62798. * Renders the debug canvas
  62799. */
  62800. Analyser.prototype.drawDebugCanvas = function () {
  62801. var _this = this;
  62802. if (this._audioEngine.canUseWebAudio) {
  62803. if (!this._debugCanvas) {
  62804. this._debugCanvas = document.createElement("canvas");
  62805. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62806. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62807. this._debugCanvas.style.position = "absolute";
  62808. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62809. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62810. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62811. document.body.appendChild(this._debugCanvas);
  62812. this._registerFunc = function () {
  62813. _this.drawDebugCanvas();
  62814. };
  62815. this._scene.registerBeforeRender(this._registerFunc);
  62816. }
  62817. if (this._registerFunc && this._debugCanvasContext) {
  62818. var workingArray = this.getByteFrequencyData();
  62819. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62820. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62821. // Draw the frequency domain chart.
  62822. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62823. var value = workingArray[i];
  62824. var percent = value / this.BARGRAPHAMPLITUDE;
  62825. var height = this.DEBUGCANVASSIZE.height * percent;
  62826. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62827. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62828. var hue = i / this.getFrequencyBinCount() * 360;
  62829. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62830. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62831. }
  62832. }
  62833. }
  62834. };
  62835. /**
  62836. * Stops rendering the debug canvas and removes it
  62837. */
  62838. Analyser.prototype.stopDebugCanvas = function () {
  62839. if (this._debugCanvas) {
  62840. if (this._registerFunc) {
  62841. this._scene.unregisterBeforeRender(this._registerFunc);
  62842. this._registerFunc = null;
  62843. }
  62844. document.body.removeChild(this._debugCanvas);
  62845. this._debugCanvas = null;
  62846. this._debugCanvasContext = null;
  62847. }
  62848. };
  62849. /**
  62850. * Connects two audio nodes
  62851. * @param inputAudioNode defines first node to connect
  62852. * @param outputAudioNode defines second node to connect
  62853. */
  62854. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62855. if (this._audioEngine.canUseWebAudio) {
  62856. inputAudioNode.connect(this._webAudioAnalyser);
  62857. this._webAudioAnalyser.connect(outputAudioNode);
  62858. }
  62859. };
  62860. /**
  62861. * Releases all associated resources
  62862. */
  62863. Analyser.prototype.dispose = function () {
  62864. if (this._audioEngine.canUseWebAudio) {
  62865. this._webAudioAnalyser.disconnect();
  62866. }
  62867. };
  62868. return Analyser;
  62869. }());
  62870. BABYLON.Analyser = Analyser;
  62871. })(BABYLON || (BABYLON = {}));
  62872. //# sourceMappingURL=babylon.analyser.js.map
  62873. var BABYLON;
  62874. (function (BABYLON) {
  62875. var CubeTexture = /** @class */ (function (_super) {
  62876. __extends(CubeTexture, _super);
  62877. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  62878. if (extensions === void 0) { extensions = null; }
  62879. if (noMipmap === void 0) { noMipmap = false; }
  62880. if (files === void 0) { files = null; }
  62881. if (onLoad === void 0) { onLoad = null; }
  62882. if (onError === void 0) { onError = null; }
  62883. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  62884. if (prefiltered === void 0) { prefiltered = false; }
  62885. if (forcedExtension === void 0) { forcedExtension = null; }
  62886. var _this = _super.call(this, scene) || this;
  62887. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  62888. /**
  62889. * Gets or sets the center of the bounding box associated with the cube texture
  62890. * It must define where the camera used to render the texture was set
  62891. */
  62892. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  62893. _this._rotationY = 0;
  62894. _this.name = rootUrl;
  62895. _this.url = rootUrl;
  62896. _this._noMipmap = noMipmap;
  62897. _this.hasAlpha = false;
  62898. _this._format = format;
  62899. _this._prefiltered = prefiltered;
  62900. _this.isCube = true;
  62901. _this._textureMatrix = BABYLON.Matrix.Identity();
  62902. if (prefiltered) {
  62903. _this.gammaSpace = false;
  62904. }
  62905. if (!rootUrl && !files) {
  62906. return _this;
  62907. }
  62908. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  62909. var lastDot = rootUrl.lastIndexOf(".");
  62910. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  62911. var isDDS = (extension === ".dds");
  62912. if (!files) {
  62913. if (!isDDS && !extensions) {
  62914. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  62915. }
  62916. files = [];
  62917. if (extensions) {
  62918. for (var index = 0; index < extensions.length; index++) {
  62919. files.push(rootUrl + extensions[index]);
  62920. }
  62921. }
  62922. }
  62923. _this._files = files;
  62924. if (!_this._texture) {
  62925. if (!scene.useDelayedTextureLoading) {
  62926. if (prefiltered) {
  62927. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  62928. }
  62929. else {
  62930. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  62931. }
  62932. }
  62933. else {
  62934. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  62935. }
  62936. }
  62937. else if (onLoad) {
  62938. if (_this._texture.isReady) {
  62939. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  62940. }
  62941. else {
  62942. _this._texture.onLoadedObservable.add(onLoad);
  62943. }
  62944. }
  62945. return _this;
  62946. }
  62947. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  62948. get: function () {
  62949. return this._boundingBoxSize;
  62950. },
  62951. /**
  62952. * Gets or sets the size of the bounding box associated with the cube texture
  62953. * When defined, the cubemap will switch to local mode
  62954. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  62955. * @example https://www.babylonjs-playground.com/#RNASML
  62956. */
  62957. set: function (value) {
  62958. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  62959. return;
  62960. }
  62961. this._boundingBoxSize = value;
  62962. var scene = this.getScene();
  62963. if (scene) {
  62964. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  62965. }
  62966. },
  62967. enumerable: true,
  62968. configurable: true
  62969. });
  62970. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  62971. /**
  62972. * Gets texture matrix rotation angle around Y axis radians.
  62973. */
  62974. get: function () {
  62975. return this._rotationY;
  62976. },
  62977. /**
  62978. * Sets texture matrix rotation angle around Y axis in radians.
  62979. */
  62980. set: function (value) {
  62981. this._rotationY = value;
  62982. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  62983. },
  62984. enumerable: true,
  62985. configurable: true
  62986. });
  62987. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  62988. var rootUrlKey = "";
  62989. files.forEach(function (url) { return rootUrlKey += url; });
  62990. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  62991. };
  62992. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  62993. if (forcedExtension === void 0) { forcedExtension = null; }
  62994. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  62995. };
  62996. // Methods
  62997. CubeTexture.prototype.delayLoad = function () {
  62998. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  62999. return;
  63000. }
  63001. var scene = this.getScene();
  63002. if (!scene) {
  63003. return;
  63004. }
  63005. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63006. this._texture = this._getFromCache(this.url, this._noMipmap);
  63007. if (!this._texture) {
  63008. if (this._prefiltered) {
  63009. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  63010. }
  63011. else {
  63012. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63013. }
  63014. }
  63015. };
  63016. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63017. return this._textureMatrix;
  63018. };
  63019. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63020. this._textureMatrix = value;
  63021. };
  63022. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63023. var texture = BABYLON.SerializationHelper.Parse(function () {
  63024. var prefiltered = false;
  63025. if (parsedTexture.prefiltered) {
  63026. prefiltered = parsedTexture.prefiltered;
  63027. }
  63028. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63029. }, parsedTexture, scene);
  63030. // Local Cubemaps
  63031. if (parsedTexture.boundingBoxPosition) {
  63032. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63033. }
  63034. if (parsedTexture.boundingBoxSize) {
  63035. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63036. }
  63037. // Animations
  63038. if (parsedTexture.animations) {
  63039. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63040. var parsedAnimation = parsedTexture.animations[animationIndex];
  63041. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63042. }
  63043. }
  63044. return texture;
  63045. };
  63046. CubeTexture.prototype.clone = function () {
  63047. var _this = this;
  63048. return BABYLON.SerializationHelper.Clone(function () {
  63049. var scene = _this.getScene();
  63050. if (!scene) {
  63051. return _this;
  63052. }
  63053. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63054. }, this);
  63055. };
  63056. __decorate([
  63057. BABYLON.serialize("rotationY")
  63058. ], CubeTexture.prototype, "_rotationY", void 0);
  63059. return CubeTexture;
  63060. }(BABYLON.BaseTexture));
  63061. BABYLON.CubeTexture = CubeTexture;
  63062. })(BABYLON || (BABYLON = {}));
  63063. //# sourceMappingURL=babylon.cubeTexture.js.map
  63064. var BABYLON;
  63065. (function (BABYLON) {
  63066. var RenderTargetTexture = /** @class */ (function (_super) {
  63067. __extends(RenderTargetTexture, _super);
  63068. /**
  63069. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63070. * or used a shadow, depth texture...
  63071. * @param name The friendly name of the texture
  63072. * @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)
  63073. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63074. * @param generateMipMaps True if mip maps need to be generated after render.
  63075. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63076. * @param type The type of the buffer in the RTT (int, half float, float...)
  63077. * @param isCube True if a cube texture needs to be created
  63078. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63079. * @param generateDepthBuffer True to generate a depth buffer
  63080. * @param generateStencilBuffer True to generate a stencil buffer
  63081. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63082. */
  63083. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63084. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63085. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63086. if (isCube === void 0) { isCube = false; }
  63087. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63088. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63089. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63090. if (isMulti === void 0) { isMulti = false; }
  63091. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63092. _this.isCube = isCube;
  63093. /**
  63094. * Use this list to define the list of mesh you want to render.
  63095. */
  63096. _this.renderList = new Array();
  63097. _this.renderParticles = true;
  63098. _this.renderSprites = false;
  63099. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63100. _this.ignoreCameraViewport = false;
  63101. // Events
  63102. /**
  63103. * An event triggered when the texture is unbind.
  63104. */
  63105. _this.onBeforeBindObservable = new BABYLON.Observable();
  63106. /**
  63107. * An event triggered when the texture is unbind.
  63108. */
  63109. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63110. /**
  63111. * An event triggered before rendering the texture
  63112. */
  63113. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63114. /**
  63115. * An event triggered after rendering the texture
  63116. */
  63117. _this.onAfterRenderObservable = new BABYLON.Observable();
  63118. /**
  63119. * An event triggered after the texture clear
  63120. */
  63121. _this.onClearObservable = new BABYLON.Observable();
  63122. _this._currentRefreshId = -1;
  63123. _this._refreshRate = 1;
  63124. _this._samples = 1;
  63125. /**
  63126. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63127. * It must define where the camera used to render the texture is set
  63128. */
  63129. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63130. scene = _this.getScene();
  63131. if (!scene) {
  63132. return _this;
  63133. }
  63134. _this._engine = scene.getEngine();
  63135. _this.name = name;
  63136. _this.isRenderTarget = true;
  63137. _this._initialSizeParameter = size;
  63138. _this._processSizeParameter(size);
  63139. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63140. });
  63141. _this._generateMipMaps = generateMipMaps ? true : false;
  63142. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63143. // Rendering groups
  63144. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63145. if (isMulti) {
  63146. return _this;
  63147. }
  63148. _this._renderTargetOptions = {
  63149. generateMipMaps: generateMipMaps,
  63150. type: type,
  63151. samplingMode: samplingMode,
  63152. generateDepthBuffer: generateDepthBuffer,
  63153. generateStencilBuffer: generateStencilBuffer
  63154. };
  63155. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63156. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63157. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63158. }
  63159. if (isCube) {
  63160. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63161. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63162. _this._textureMatrix = BABYLON.Matrix.Identity();
  63163. }
  63164. else {
  63165. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63166. }
  63167. return _this;
  63168. }
  63169. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63170. get: function () {
  63171. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63172. },
  63173. enumerable: true,
  63174. configurable: true
  63175. });
  63176. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63177. get: function () {
  63178. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63179. },
  63180. enumerable: true,
  63181. configurable: true
  63182. });
  63183. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63184. get: function () {
  63185. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63186. },
  63187. enumerable: true,
  63188. configurable: true
  63189. });
  63190. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63191. set: function (callback) {
  63192. if (this._onAfterUnbindObserver) {
  63193. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63194. }
  63195. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63196. },
  63197. enumerable: true,
  63198. configurable: true
  63199. });
  63200. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63201. set: function (callback) {
  63202. if (this._onBeforeRenderObserver) {
  63203. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63204. }
  63205. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63206. },
  63207. enumerable: true,
  63208. configurable: true
  63209. });
  63210. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63211. set: function (callback) {
  63212. if (this._onAfterRenderObserver) {
  63213. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63214. }
  63215. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63216. },
  63217. enumerable: true,
  63218. configurable: true
  63219. });
  63220. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63221. set: function (callback) {
  63222. if (this._onClearObserver) {
  63223. this.onClearObservable.remove(this._onClearObserver);
  63224. }
  63225. this._onClearObserver = this.onClearObservable.add(callback);
  63226. },
  63227. enumerable: true,
  63228. configurable: true
  63229. });
  63230. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63231. get: function () {
  63232. return this._renderTargetOptions;
  63233. },
  63234. enumerable: true,
  63235. configurable: true
  63236. });
  63237. RenderTargetTexture.prototype._onRatioRescale = function () {
  63238. if (this._sizeRatio) {
  63239. this.resize(this._initialSizeParameter);
  63240. }
  63241. };
  63242. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63243. get: function () {
  63244. return this._boundingBoxSize;
  63245. },
  63246. /**
  63247. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63248. * When defined, the cubemap will switch to local mode
  63249. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63250. * @example https://www.babylonjs-playground.com/#RNASML
  63251. */
  63252. set: function (value) {
  63253. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63254. return;
  63255. }
  63256. this._boundingBoxSize = value;
  63257. var scene = this.getScene();
  63258. if (scene) {
  63259. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63260. }
  63261. },
  63262. enumerable: true,
  63263. configurable: true
  63264. });
  63265. /**
  63266. * Creates a depth stencil texture.
  63267. * This is only available in WebGL 2 or with the depth texture extension available.
  63268. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63269. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63270. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63271. */
  63272. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63273. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63274. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63275. if (generateStencil === void 0) { generateStencil = false; }
  63276. if (!this.getScene()) {
  63277. return;
  63278. }
  63279. var engine = this.getScene().getEngine();
  63280. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63281. bilinearFiltering: bilinearFiltering,
  63282. comparisonFunction: comparisonFunction,
  63283. generateStencil: generateStencil,
  63284. isCube: this.isCube
  63285. });
  63286. engine.setFrameBufferDepthStencilTexture(this);
  63287. };
  63288. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63289. if (size.ratio) {
  63290. this._sizeRatio = size.ratio;
  63291. this._size = {
  63292. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63293. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63294. };
  63295. }
  63296. else {
  63297. this._size = size;
  63298. }
  63299. };
  63300. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63301. get: function () {
  63302. return this._samples;
  63303. },
  63304. set: function (value) {
  63305. if (this._samples === value) {
  63306. return;
  63307. }
  63308. var scene = this.getScene();
  63309. if (!scene) {
  63310. return;
  63311. }
  63312. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63313. },
  63314. enumerable: true,
  63315. configurable: true
  63316. });
  63317. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63318. this._currentRefreshId = -1;
  63319. };
  63320. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63321. get: function () {
  63322. return this._refreshRate;
  63323. },
  63324. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63325. set: function (value) {
  63326. this._refreshRate = value;
  63327. this.resetRefreshCounter();
  63328. },
  63329. enumerable: true,
  63330. configurable: true
  63331. });
  63332. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63333. if (!this._postProcessManager) {
  63334. var scene = this.getScene();
  63335. if (!scene) {
  63336. return;
  63337. }
  63338. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63339. this._postProcesses = new Array();
  63340. }
  63341. this._postProcesses.push(postProcess);
  63342. this._postProcesses[0].autoClear = false;
  63343. };
  63344. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63345. if (!this._postProcesses) {
  63346. return;
  63347. }
  63348. if (dispose) {
  63349. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63350. var postProcess = _a[_i];
  63351. postProcess.dispose();
  63352. }
  63353. }
  63354. this._postProcesses = [];
  63355. };
  63356. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63357. if (!this._postProcesses) {
  63358. return;
  63359. }
  63360. var index = this._postProcesses.indexOf(postProcess);
  63361. if (index === -1) {
  63362. return;
  63363. }
  63364. this._postProcesses.splice(index, 1);
  63365. if (this._postProcesses.length > 0) {
  63366. this._postProcesses[0].autoClear = false;
  63367. }
  63368. };
  63369. RenderTargetTexture.prototype._shouldRender = function () {
  63370. if (this._currentRefreshId === -1) { // At least render once
  63371. this._currentRefreshId = 1;
  63372. return true;
  63373. }
  63374. if (this.refreshRate === this._currentRefreshId) {
  63375. this._currentRefreshId = 1;
  63376. return true;
  63377. }
  63378. this._currentRefreshId++;
  63379. return false;
  63380. };
  63381. RenderTargetTexture.prototype.getRenderSize = function () {
  63382. if (this._size.width) {
  63383. return this._size.width;
  63384. }
  63385. return this._size;
  63386. };
  63387. RenderTargetTexture.prototype.getRenderWidth = function () {
  63388. if (this._size.width) {
  63389. return this._size.width;
  63390. }
  63391. return this._size;
  63392. };
  63393. RenderTargetTexture.prototype.getRenderHeight = function () {
  63394. if (this._size.width) {
  63395. return this._size.height;
  63396. }
  63397. return this._size;
  63398. };
  63399. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63400. get: function () {
  63401. return true;
  63402. },
  63403. enumerable: true,
  63404. configurable: true
  63405. });
  63406. RenderTargetTexture.prototype.scale = function (ratio) {
  63407. var newSize = this.getRenderSize() * ratio;
  63408. this.resize(newSize);
  63409. };
  63410. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63411. if (this.isCube) {
  63412. return this._textureMatrix;
  63413. }
  63414. return _super.prototype.getReflectionTextureMatrix.call(this);
  63415. };
  63416. RenderTargetTexture.prototype.resize = function (size) {
  63417. this.releaseInternalTexture();
  63418. var scene = this.getScene();
  63419. if (!scene) {
  63420. return;
  63421. }
  63422. this._processSizeParameter(size);
  63423. if (this.isCube) {
  63424. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63425. }
  63426. else {
  63427. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63428. }
  63429. };
  63430. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63431. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63432. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63433. var scene = this.getScene();
  63434. if (!scene) {
  63435. return;
  63436. }
  63437. var engine = scene.getEngine();
  63438. if (this.useCameraPostProcesses !== undefined) {
  63439. useCameraPostProcess = this.useCameraPostProcesses;
  63440. }
  63441. if (this._waitingRenderList) {
  63442. this.renderList = [];
  63443. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63444. var id = this._waitingRenderList[index];
  63445. var mesh_1 = scene.getMeshByID(id);
  63446. if (mesh_1) {
  63447. this.renderList.push(mesh_1);
  63448. }
  63449. }
  63450. delete this._waitingRenderList;
  63451. }
  63452. // Is predicate defined?
  63453. if (this.renderListPredicate) {
  63454. if (this.renderList) {
  63455. this.renderList.splice(0); // Clear previous renderList
  63456. }
  63457. else {
  63458. this.renderList = [];
  63459. }
  63460. var scene = this.getScene();
  63461. if (!scene) {
  63462. return;
  63463. }
  63464. var sceneMeshes = scene.meshes;
  63465. for (var index = 0; index < sceneMeshes.length; index++) {
  63466. var mesh = sceneMeshes[index];
  63467. if (this.renderListPredicate(mesh)) {
  63468. this.renderList.push(mesh);
  63469. }
  63470. }
  63471. }
  63472. this.onBeforeBindObservable.notifyObservers(this);
  63473. // Set custom projection.
  63474. // Needs to be before binding to prevent changing the aspect ratio.
  63475. var camera;
  63476. if (this.activeCamera) {
  63477. camera = this.activeCamera;
  63478. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63479. if (this.activeCamera !== scene.activeCamera) {
  63480. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63481. }
  63482. }
  63483. else {
  63484. camera = scene.activeCamera;
  63485. if (camera) {
  63486. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63487. }
  63488. }
  63489. // Prepare renderingManager
  63490. this._renderingManager.reset();
  63491. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63492. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63493. var sceneRenderId = scene.getRenderId();
  63494. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63495. var mesh = currentRenderList[meshIndex];
  63496. if (mesh) {
  63497. if (!mesh.isReady(this.refreshRate === 0)) {
  63498. this.resetRefreshCounter();
  63499. continue;
  63500. }
  63501. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63502. var isMasked = void 0;
  63503. if (!this.renderList && camera) {
  63504. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63505. }
  63506. else {
  63507. isMasked = false;
  63508. }
  63509. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63510. mesh._activate(sceneRenderId);
  63511. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63512. var subMesh = mesh.subMeshes[subIndex];
  63513. scene._activeIndices.addCount(subMesh.indexCount, false);
  63514. this._renderingManager.dispatch(subMesh, mesh);
  63515. }
  63516. }
  63517. }
  63518. }
  63519. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63520. var particleSystem = scene.particleSystems[particleIndex];
  63521. var emitter = particleSystem.emitter;
  63522. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63523. continue;
  63524. }
  63525. if (currentRenderList.indexOf(emitter) >= 0) {
  63526. this._renderingManager.dispatchParticles(particleSystem);
  63527. }
  63528. }
  63529. if (this.isCube) {
  63530. for (var face = 0; face < 6; face++) {
  63531. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63532. scene.incrementRenderId();
  63533. scene.resetCachedMaterial();
  63534. }
  63535. }
  63536. else {
  63537. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63538. }
  63539. this.onAfterUnbindObservable.notifyObservers(this);
  63540. if (scene.activeCamera) {
  63541. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63542. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63543. }
  63544. engine.setViewport(scene.activeCamera.viewport);
  63545. }
  63546. scene.resetCachedMaterial();
  63547. };
  63548. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63549. var minimum = 128;
  63550. var x = renderDimension * scale;
  63551. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63552. // Ensure we don't exceed the render dimension (while staying POT)
  63553. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63554. };
  63555. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63556. var _this = this;
  63557. if (!this._texture) {
  63558. return;
  63559. }
  63560. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63561. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63562. });
  63563. };
  63564. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63565. var scene = this.getScene();
  63566. if (!scene) {
  63567. return;
  63568. }
  63569. var engine = scene.getEngine();
  63570. if (!this._texture) {
  63571. return;
  63572. }
  63573. // Bind
  63574. if (this._postProcessManager) {
  63575. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63576. }
  63577. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63578. if (this._texture) {
  63579. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63580. }
  63581. }
  63582. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63583. // Clear
  63584. if (this.onClearObservable.hasObservers()) {
  63585. this.onClearObservable.notifyObservers(engine);
  63586. }
  63587. else {
  63588. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63589. }
  63590. if (!this._doNotChangeAspectRatio) {
  63591. scene.updateTransformMatrix(true);
  63592. }
  63593. // Render
  63594. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63595. if (this._postProcessManager) {
  63596. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63597. }
  63598. else if (useCameraPostProcess) {
  63599. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63600. }
  63601. if (!this._doNotChangeAspectRatio) {
  63602. scene.updateTransformMatrix(true);
  63603. }
  63604. // Dump ?
  63605. if (dumpForDebug) {
  63606. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63607. }
  63608. // Unbind
  63609. if (!this.isCube || faceIndex === 5) {
  63610. if (this.isCube) {
  63611. if (faceIndex === 5) {
  63612. engine.generateMipMapsForCubemap(this._texture);
  63613. }
  63614. }
  63615. this.unbindFrameBuffer(engine, faceIndex);
  63616. }
  63617. else {
  63618. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63619. }
  63620. };
  63621. /**
  63622. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63623. * This allowed control for front to back rendering or reversly depending of the special needs.
  63624. *
  63625. * @param renderingGroupId The rendering group id corresponding to its index
  63626. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63627. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63628. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63629. */
  63630. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63631. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63632. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63633. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63634. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63635. };
  63636. /**
  63637. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63638. *
  63639. * @param renderingGroupId The rendering group id corresponding to its index
  63640. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63641. */
  63642. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63643. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63644. };
  63645. RenderTargetTexture.prototype.clone = function () {
  63646. var textureSize = this.getSize();
  63647. 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);
  63648. // Base texture
  63649. newTexture.hasAlpha = this.hasAlpha;
  63650. newTexture.level = this.level;
  63651. // RenderTarget Texture
  63652. newTexture.coordinatesMode = this.coordinatesMode;
  63653. if (this.renderList) {
  63654. newTexture.renderList = this.renderList.slice(0);
  63655. }
  63656. return newTexture;
  63657. };
  63658. RenderTargetTexture.prototype.serialize = function () {
  63659. if (!this.name) {
  63660. return null;
  63661. }
  63662. var serializationObject = _super.prototype.serialize.call(this);
  63663. serializationObject.renderTargetSize = this.getRenderSize();
  63664. serializationObject.renderList = [];
  63665. if (this.renderList) {
  63666. for (var index = 0; index < this.renderList.length; index++) {
  63667. serializationObject.renderList.push(this.renderList[index].id);
  63668. }
  63669. }
  63670. return serializationObject;
  63671. };
  63672. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63673. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63674. var objBuffer = this.getInternalTexture();
  63675. var scene = this.getScene();
  63676. if (objBuffer && scene) {
  63677. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63678. }
  63679. };
  63680. RenderTargetTexture.prototype.dispose = function () {
  63681. if (this._postProcessManager) {
  63682. this._postProcessManager.dispose();
  63683. this._postProcessManager = null;
  63684. }
  63685. this.clearPostProcesses(true);
  63686. if (this._resizeObserver) {
  63687. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63688. this._resizeObserver = null;
  63689. }
  63690. this.renderList = null;
  63691. // Remove from custom render targets
  63692. var scene = this.getScene();
  63693. if (!scene) {
  63694. return;
  63695. }
  63696. var index = scene.customRenderTargets.indexOf(this);
  63697. if (index >= 0) {
  63698. scene.customRenderTargets.splice(index, 1);
  63699. }
  63700. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63701. var camera = _a[_i];
  63702. index = camera.customRenderTargets.indexOf(this);
  63703. if (index >= 0) {
  63704. camera.customRenderTargets.splice(index, 1);
  63705. }
  63706. }
  63707. _super.prototype.dispose.call(this);
  63708. };
  63709. RenderTargetTexture.prototype._rebuild = function () {
  63710. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63711. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63712. }
  63713. if (this._postProcessManager) {
  63714. this._postProcessManager._rebuild();
  63715. }
  63716. };
  63717. /**
  63718. * Clear the info related to rendering groups preventing retention point in material dispose.
  63719. */
  63720. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63721. if (this._renderingManager) {
  63722. this._renderingManager.freeRenderingGroups();
  63723. }
  63724. };
  63725. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63726. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63727. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63728. return RenderTargetTexture;
  63729. }(BABYLON.Texture));
  63730. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63731. })(BABYLON || (BABYLON = {}));
  63732. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63733. var BABYLON;
  63734. (function (BABYLON) {
  63735. ;
  63736. var MultiRenderTarget = /** @class */ (function (_super) {
  63737. __extends(MultiRenderTarget, _super);
  63738. function MultiRenderTarget(name, size, count, scene, options) {
  63739. var _this = this;
  63740. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63741. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63742. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63743. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63744. _this._engine = scene.getEngine();
  63745. if (!_this.isSupported) {
  63746. _this.dispose();
  63747. return;
  63748. }
  63749. var types = [];
  63750. var samplingModes = [];
  63751. for (var i = 0; i < count; i++) {
  63752. if (options && options.types && options.types[i] !== undefined) {
  63753. types.push(options.types[i]);
  63754. }
  63755. else {
  63756. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63757. }
  63758. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63759. samplingModes.push(options.samplingModes[i]);
  63760. }
  63761. else {
  63762. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63763. }
  63764. }
  63765. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63766. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63767. _this._size = size;
  63768. _this._multiRenderTargetOptions = {
  63769. samplingModes: samplingModes,
  63770. generateMipMaps: generateMipMaps,
  63771. generateDepthBuffer: generateDepthBuffer,
  63772. generateStencilBuffer: generateStencilBuffer,
  63773. generateDepthTexture: generateDepthTexture,
  63774. types: types,
  63775. textureCount: count
  63776. };
  63777. _this._createInternalTextures();
  63778. _this._createTextures();
  63779. return _this;
  63780. }
  63781. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63782. get: function () {
  63783. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63784. },
  63785. enumerable: true,
  63786. configurable: true
  63787. });
  63788. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63789. get: function () {
  63790. return this._textures;
  63791. },
  63792. enumerable: true,
  63793. configurable: true
  63794. });
  63795. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63796. get: function () {
  63797. return this._textures[this._textures.length - 1];
  63798. },
  63799. enumerable: true,
  63800. configurable: true
  63801. });
  63802. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63803. set: function (wrap) {
  63804. if (this._textures) {
  63805. for (var i = 0; i < this._textures.length; i++) {
  63806. this._textures[i].wrapU = wrap;
  63807. }
  63808. }
  63809. },
  63810. enumerable: true,
  63811. configurable: true
  63812. });
  63813. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63814. set: function (wrap) {
  63815. if (this._textures) {
  63816. for (var i = 0; i < this._textures.length; i++) {
  63817. this._textures[i].wrapV = wrap;
  63818. }
  63819. }
  63820. },
  63821. enumerable: true,
  63822. configurable: true
  63823. });
  63824. MultiRenderTarget.prototype._rebuild = function () {
  63825. this.releaseInternalTextures();
  63826. this._createInternalTextures();
  63827. for (var i = 0; i < this._internalTextures.length; i++) {
  63828. var texture = this._textures[i];
  63829. texture._texture = this._internalTextures[i];
  63830. }
  63831. // Keeps references to frame buffer and stencil/depth buffer
  63832. this._texture = this._internalTextures[0];
  63833. };
  63834. MultiRenderTarget.prototype._createInternalTextures = function () {
  63835. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63836. };
  63837. MultiRenderTarget.prototype._createTextures = function () {
  63838. this._textures = [];
  63839. for (var i = 0; i < this._internalTextures.length; i++) {
  63840. var texture = new BABYLON.Texture(null, this.getScene());
  63841. texture._texture = this._internalTextures[i];
  63842. this._textures.push(texture);
  63843. }
  63844. // Keeps references to frame buffer and stencil/depth buffer
  63845. this._texture = this._internalTextures[0];
  63846. };
  63847. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63848. get: function () {
  63849. return this._samples;
  63850. },
  63851. set: function (value) {
  63852. if (this._samples === value) {
  63853. return;
  63854. }
  63855. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63856. },
  63857. enumerable: true,
  63858. configurable: true
  63859. });
  63860. MultiRenderTarget.prototype.resize = function (size) {
  63861. this.releaseInternalTextures();
  63862. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63863. this._createInternalTextures();
  63864. };
  63865. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63866. var _this = this;
  63867. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  63868. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63869. });
  63870. };
  63871. MultiRenderTarget.prototype.dispose = function () {
  63872. this.releaseInternalTextures();
  63873. _super.prototype.dispose.call(this);
  63874. };
  63875. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  63876. if (!this._internalTextures) {
  63877. return;
  63878. }
  63879. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  63880. if (this._internalTextures[i] !== undefined) {
  63881. this._internalTextures[i].dispose();
  63882. this._internalTextures.splice(i, 1);
  63883. }
  63884. }
  63885. };
  63886. return MultiRenderTarget;
  63887. }(BABYLON.RenderTargetTexture));
  63888. BABYLON.MultiRenderTarget = MultiRenderTarget;
  63889. })(BABYLON || (BABYLON = {}));
  63890. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  63891. var BABYLON;
  63892. (function (BABYLON) {
  63893. var MirrorTexture = /** @class */ (function (_super) {
  63894. __extends(MirrorTexture, _super);
  63895. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  63896. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63897. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  63898. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63899. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  63900. _this.scene = scene;
  63901. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  63902. _this._transformMatrix = BABYLON.Matrix.Zero();
  63903. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  63904. _this._adaptiveBlurKernel = 0;
  63905. _this._blurKernelX = 0;
  63906. _this._blurKernelY = 0;
  63907. _this._blurRatio = 1.0;
  63908. _this.ignoreCameraViewport = true;
  63909. _this._updateGammaSpace();
  63910. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  63911. _this._updateGammaSpace;
  63912. });
  63913. _this.onBeforeRenderObservable.add(function () {
  63914. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  63915. _this._savedViewMatrix = scene.getViewMatrix();
  63916. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  63917. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  63918. scene.clipPlane = _this.mirrorPlane;
  63919. scene.getEngine().cullBackFaces = false;
  63920. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  63921. });
  63922. _this.onAfterRenderObservable.add(function () {
  63923. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  63924. scene.getEngine().cullBackFaces = true;
  63925. scene._mirroredCameraPosition = null;
  63926. delete scene.clipPlane;
  63927. });
  63928. return _this;
  63929. }
  63930. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  63931. get: function () {
  63932. return this._blurRatio;
  63933. },
  63934. set: function (value) {
  63935. if (this._blurRatio === value) {
  63936. return;
  63937. }
  63938. this._blurRatio = value;
  63939. this._preparePostProcesses();
  63940. },
  63941. enumerable: true,
  63942. configurable: true
  63943. });
  63944. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  63945. set: function (value) {
  63946. this._adaptiveBlurKernel = value;
  63947. this._autoComputeBlurKernel();
  63948. },
  63949. enumerable: true,
  63950. configurable: true
  63951. });
  63952. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  63953. set: function (value) {
  63954. this.blurKernelX = value;
  63955. this.blurKernelY = value;
  63956. },
  63957. enumerable: true,
  63958. configurable: true
  63959. });
  63960. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  63961. get: function () {
  63962. return this._blurKernelX;
  63963. },
  63964. set: function (value) {
  63965. if (this._blurKernelX === value) {
  63966. return;
  63967. }
  63968. this._blurKernelX = value;
  63969. this._preparePostProcesses();
  63970. },
  63971. enumerable: true,
  63972. configurable: true
  63973. });
  63974. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  63975. get: function () {
  63976. return this._blurKernelY;
  63977. },
  63978. set: function (value) {
  63979. if (this._blurKernelY === value) {
  63980. return;
  63981. }
  63982. this._blurKernelY = value;
  63983. this._preparePostProcesses();
  63984. },
  63985. enumerable: true,
  63986. configurable: true
  63987. });
  63988. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  63989. var engine = this.getScene().getEngine();
  63990. var dw = this.getRenderWidth() / engine.getRenderWidth();
  63991. var dh = this.getRenderHeight() / engine.getRenderHeight();
  63992. this.blurKernelX = this._adaptiveBlurKernel * dw;
  63993. this.blurKernelY = this._adaptiveBlurKernel * dh;
  63994. };
  63995. MirrorTexture.prototype._onRatioRescale = function () {
  63996. if (this._sizeRatio) {
  63997. this.resize(this._initialSizeParameter);
  63998. if (!this._adaptiveBlurKernel) {
  63999. this._preparePostProcesses();
  64000. }
  64001. }
  64002. if (this._adaptiveBlurKernel) {
  64003. this._autoComputeBlurKernel();
  64004. }
  64005. };
  64006. MirrorTexture.prototype._updateGammaSpace = function () {
  64007. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64008. };
  64009. MirrorTexture.prototype._preparePostProcesses = function () {
  64010. this.clearPostProcesses(true);
  64011. if (this._blurKernelX && this._blurKernelY) {
  64012. var engine = this.getScene().getEngine();
  64013. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64014. 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);
  64015. this._blurX.autoClear = false;
  64016. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64017. this._blurX.inputTexture = this._texture;
  64018. }
  64019. else {
  64020. this._blurX.alwaysForcePOT = true;
  64021. }
  64022. 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);
  64023. this._blurY.autoClear = false;
  64024. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64025. this.addPostProcess(this._blurX);
  64026. this.addPostProcess(this._blurY);
  64027. }
  64028. else {
  64029. if (this._blurY) {
  64030. this.removePostProcess(this._blurY);
  64031. this._blurY.dispose();
  64032. this._blurY = null;
  64033. }
  64034. if (this._blurX) {
  64035. this.removePostProcess(this._blurX);
  64036. this._blurX.dispose();
  64037. this._blurX = null;
  64038. }
  64039. }
  64040. };
  64041. MirrorTexture.prototype.clone = function () {
  64042. var scene = this.getScene();
  64043. if (!scene) {
  64044. return this;
  64045. }
  64046. var textureSize = this.getSize();
  64047. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64048. // Base texture
  64049. newTexture.hasAlpha = this.hasAlpha;
  64050. newTexture.level = this.level;
  64051. // Mirror Texture
  64052. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64053. if (this.renderList) {
  64054. newTexture.renderList = this.renderList.slice(0);
  64055. }
  64056. return newTexture;
  64057. };
  64058. MirrorTexture.prototype.serialize = function () {
  64059. if (!this.name) {
  64060. return null;
  64061. }
  64062. var serializationObject = _super.prototype.serialize.call(this);
  64063. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64064. return serializationObject;
  64065. };
  64066. MirrorTexture.prototype.dispose = function () {
  64067. _super.prototype.dispose.call(this);
  64068. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64069. };
  64070. return MirrorTexture;
  64071. }(BABYLON.RenderTargetTexture));
  64072. BABYLON.MirrorTexture = MirrorTexture;
  64073. })(BABYLON || (BABYLON = {}));
  64074. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64075. var BABYLON;
  64076. (function (BABYLON) {
  64077. /**
  64078. * Creates a refraction texture used by refraction channel of the standard material.
  64079. * @param name the texture name
  64080. * @param size size of the underlying texture
  64081. * @param scene root scene
  64082. */
  64083. var RefractionTexture = /** @class */ (function (_super) {
  64084. __extends(RefractionTexture, _super);
  64085. function RefractionTexture(name, size, scene, generateMipMaps) {
  64086. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64087. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64088. _this.depth = 2.0;
  64089. _this.onBeforeRenderObservable.add(function () {
  64090. scene.clipPlane = _this.refractionPlane;
  64091. });
  64092. _this.onAfterRenderObservable.add(function () {
  64093. delete scene.clipPlane;
  64094. });
  64095. return _this;
  64096. }
  64097. RefractionTexture.prototype.clone = function () {
  64098. var scene = this.getScene();
  64099. if (!scene) {
  64100. return this;
  64101. }
  64102. var textureSize = this.getSize();
  64103. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64104. // Base texture
  64105. newTexture.hasAlpha = this.hasAlpha;
  64106. newTexture.level = this.level;
  64107. // Refraction Texture
  64108. newTexture.refractionPlane = this.refractionPlane.clone();
  64109. if (this.renderList) {
  64110. newTexture.renderList = this.renderList.slice(0);
  64111. }
  64112. newTexture.depth = this.depth;
  64113. return newTexture;
  64114. };
  64115. RefractionTexture.prototype.serialize = function () {
  64116. if (!this.name) {
  64117. return null;
  64118. }
  64119. var serializationObject = _super.prototype.serialize.call(this);
  64120. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64121. serializationObject.depth = this.depth;
  64122. return serializationObject;
  64123. };
  64124. return RefractionTexture;
  64125. }(BABYLON.RenderTargetTexture));
  64126. BABYLON.RefractionTexture = RefractionTexture;
  64127. })(BABYLON || (BABYLON = {}));
  64128. //# sourceMappingURL=babylon.refractionTexture.js.map
  64129. var BABYLON;
  64130. (function (BABYLON) {
  64131. /**
  64132. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64133. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64134. */
  64135. var DynamicTexture = /** @class */ (function (_super) {
  64136. __extends(DynamicTexture, _super);
  64137. /**
  64138. * Creates a {BABYLON.DynamicTexture}
  64139. * @param name defines the name of the texture
  64140. * @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
  64141. * @param scene defines the scene where you want the texture
  64142. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64143. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64144. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64145. */
  64146. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64147. if (scene === void 0) { scene = null; }
  64148. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64149. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64150. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64151. _this.name = name;
  64152. _this._engine = _this.getScene().getEngine();
  64153. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64154. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64155. _this._generateMipMaps = generateMipMaps;
  64156. if (options.getContext) {
  64157. _this._canvas = options;
  64158. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64159. }
  64160. else {
  64161. _this._canvas = document.createElement("canvas");
  64162. if (options.width || options.width === 0) {
  64163. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64164. }
  64165. else {
  64166. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64167. }
  64168. }
  64169. var textureSize = _this.getSize();
  64170. _this._canvas.width = textureSize.width;
  64171. _this._canvas.height = textureSize.height;
  64172. _this._context = _this._canvas.getContext("2d");
  64173. return _this;
  64174. }
  64175. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64176. /**
  64177. * Gets the current state of canRescale
  64178. */
  64179. get: function () {
  64180. return true;
  64181. },
  64182. enumerable: true,
  64183. configurable: true
  64184. });
  64185. DynamicTexture.prototype._recreate = function (textureSize) {
  64186. this._canvas.width = textureSize.width;
  64187. this._canvas.height = textureSize.height;
  64188. this.releaseInternalTexture();
  64189. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64190. };
  64191. /**
  64192. * Scales the texture
  64193. * @param ratio the scale factor to apply to both width and height
  64194. */
  64195. DynamicTexture.prototype.scale = function (ratio) {
  64196. var textureSize = this.getSize();
  64197. textureSize.width *= ratio;
  64198. textureSize.height *= ratio;
  64199. this._recreate(textureSize);
  64200. };
  64201. /**
  64202. * Resizes the texture
  64203. * @param width the new width
  64204. * @param height the new height
  64205. */
  64206. DynamicTexture.prototype.scaleTo = function (width, height) {
  64207. var textureSize = this.getSize();
  64208. textureSize.width = width;
  64209. textureSize.height = height;
  64210. this._recreate(textureSize);
  64211. };
  64212. /**
  64213. * Gets the context of the canvas used by the texture
  64214. * @returns the canvas context of the dynamic texture
  64215. */
  64216. DynamicTexture.prototype.getContext = function () {
  64217. return this._context;
  64218. };
  64219. /**
  64220. * Clears the texture
  64221. */
  64222. DynamicTexture.prototype.clear = function () {
  64223. var size = this.getSize();
  64224. this._context.fillRect(0, 0, size.width, size.height);
  64225. };
  64226. /**
  64227. * Updates the texture
  64228. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64229. */
  64230. DynamicTexture.prototype.update = function (invertY) {
  64231. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  64232. };
  64233. /**
  64234. * Draws text onto the texture
  64235. * @param text defines the text to be drawn
  64236. * @param x defines the placement of the text from the left
  64237. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64238. * @param font defines the font to be used with font-style, font-size, font-name
  64239. * @param color defines the color used for the text
  64240. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64241. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64242. * @param update defines whether texture is immediately update (default is true)
  64243. */
  64244. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64245. if (update === void 0) { update = true; }
  64246. var size = this.getSize();
  64247. if (clearColor) {
  64248. this._context.fillStyle = clearColor;
  64249. this._context.fillRect(0, 0, size.width, size.height);
  64250. }
  64251. this._context.font = font;
  64252. if (x === null || x === undefined) {
  64253. var textSize = this._context.measureText(text);
  64254. x = (size.width - textSize.width) / 2;
  64255. }
  64256. if (y === null || y === undefined) {
  64257. var fontSize = parseInt((font.replace(/\D/g, '')));
  64258. ;
  64259. y = (size.height / 2) + (fontSize / 3.65);
  64260. }
  64261. this._context.fillStyle = color;
  64262. this._context.fillText(text, x, y);
  64263. if (update) {
  64264. this.update(invertY);
  64265. }
  64266. };
  64267. /**
  64268. * Clones the texture
  64269. * @returns the clone of the texture.
  64270. */
  64271. DynamicTexture.prototype.clone = function () {
  64272. var scene = this.getScene();
  64273. if (!scene) {
  64274. return this;
  64275. }
  64276. var textureSize = this.getSize();
  64277. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64278. // Base texture
  64279. newTexture.hasAlpha = this.hasAlpha;
  64280. newTexture.level = this.level;
  64281. // Dynamic Texture
  64282. newTexture.wrapU = this.wrapU;
  64283. newTexture.wrapV = this.wrapV;
  64284. return newTexture;
  64285. };
  64286. /** @hidden */
  64287. DynamicTexture.prototype._rebuild = function () {
  64288. this.update();
  64289. };
  64290. return DynamicTexture;
  64291. }(BABYLON.Texture));
  64292. BABYLON.DynamicTexture = DynamicTexture;
  64293. })(BABYLON || (BABYLON = {}));
  64294. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64295. var BABYLON;
  64296. (function (BABYLON) {
  64297. var VideoTexture = /** @class */ (function (_super) {
  64298. __extends(VideoTexture, _super);
  64299. /**
  64300. * Creates a video texture.
  64301. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64302. * @param {string | null} name optional name, will detect from video source, if not defined
  64303. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64304. * @param {BABYLON.Scene} scene is obviously the current scene.
  64305. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64306. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64307. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64308. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64309. */
  64310. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64311. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64312. if (invertY === void 0) { invertY = false; }
  64313. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64314. if (settings === void 0) { settings = {
  64315. autoPlay: true,
  64316. loop: true,
  64317. autoUpdateTexture: true,
  64318. }; }
  64319. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64320. _this._stillImageCaptured = false;
  64321. _this._createInternalTexture = function () {
  64322. if (_this._texture != null) {
  64323. return;
  64324. }
  64325. if (!_this._engine.needPOTTextures ||
  64326. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64327. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64328. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64329. }
  64330. else {
  64331. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64332. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64333. _this._generateMipMaps = false;
  64334. }
  64335. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64336. if (!_this.video.autoplay) {
  64337. var oldHandler_1 = _this.video.onplaying;
  64338. _this.video.onplaying = function () {
  64339. _this.video.onplaying = oldHandler_1;
  64340. _this._texture.isReady = true;
  64341. _this._updateInternalTexture();
  64342. _this.video.pause();
  64343. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64344. _this.onLoadObservable.notifyObservers(_this);
  64345. }
  64346. };
  64347. _this.video.play();
  64348. }
  64349. else {
  64350. _this._texture.isReady = true;
  64351. _this._updateInternalTexture();
  64352. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64353. _this.onLoadObservable.notifyObservers(_this);
  64354. }
  64355. }
  64356. };
  64357. _this.reset = function () {
  64358. if (_this._texture == null) {
  64359. return;
  64360. }
  64361. _this._texture.dispose();
  64362. _this._texture = null;
  64363. };
  64364. _this._updateInternalTexture = function (e) {
  64365. if (_this._texture == null || !_this._texture.isReady) {
  64366. return;
  64367. }
  64368. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64369. return;
  64370. }
  64371. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64372. };
  64373. _this._engine = _this.getScene().getEngine();
  64374. _this._generateMipMaps = generateMipMaps;
  64375. _this._samplingMode = samplingMode;
  64376. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64377. _this.name = name || _this._getName(src);
  64378. _this.video = _this._getVideo(src);
  64379. if (settings.autoPlay !== undefined) {
  64380. _this.video.autoplay = settings.autoPlay;
  64381. }
  64382. if (settings.loop !== undefined) {
  64383. _this.video.loop = settings.loop;
  64384. }
  64385. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64386. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64387. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64388. _this.video.addEventListener("emptied", _this.reset);
  64389. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64390. _this._createInternalTexture();
  64391. }
  64392. return _this;
  64393. }
  64394. VideoTexture.prototype._getName = function (src) {
  64395. if (src instanceof HTMLVideoElement) {
  64396. return src.currentSrc;
  64397. }
  64398. if (typeof src === "object") {
  64399. return src.toString();
  64400. }
  64401. return src;
  64402. };
  64403. ;
  64404. VideoTexture.prototype._getVideo = function (src) {
  64405. if (src instanceof HTMLVideoElement) {
  64406. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64407. return src;
  64408. }
  64409. var video = document.createElement("video");
  64410. if (typeof src === "string") {
  64411. BABYLON.Tools.SetCorsBehavior(src, video);
  64412. video.src = src;
  64413. }
  64414. else {
  64415. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64416. src.forEach(function (url) {
  64417. var source = document.createElement("source");
  64418. source.src = url;
  64419. video.appendChild(source);
  64420. });
  64421. }
  64422. return video;
  64423. };
  64424. ;
  64425. /**
  64426. * Internal method to initiate `update`.
  64427. */
  64428. VideoTexture.prototype._rebuild = function () {
  64429. this.update();
  64430. };
  64431. /**
  64432. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64433. */
  64434. VideoTexture.prototype.update = function () {
  64435. if (!this.autoUpdateTexture) {
  64436. // Expecting user to call `updateTexture` manually
  64437. return;
  64438. }
  64439. this.updateTexture(true);
  64440. };
  64441. /**
  64442. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64443. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64444. */
  64445. VideoTexture.prototype.updateTexture = function (isVisible) {
  64446. if (!isVisible) {
  64447. return;
  64448. }
  64449. if (this.video.paused && this._stillImageCaptured) {
  64450. return;
  64451. }
  64452. this._stillImageCaptured = true;
  64453. this._updateInternalTexture();
  64454. };
  64455. /**
  64456. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64457. * @param url New url.
  64458. */
  64459. VideoTexture.prototype.updateURL = function (url) {
  64460. this.video.src = url;
  64461. };
  64462. VideoTexture.prototype.dispose = function () {
  64463. _super.prototype.dispose.call(this);
  64464. this.video.removeEventListener("canplay", this._createInternalTexture);
  64465. this.video.removeEventListener("paused", this._updateInternalTexture);
  64466. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64467. this.video.removeEventListener("emptied", this.reset);
  64468. this.video.pause();
  64469. };
  64470. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64471. var video = document.createElement("video");
  64472. var constraintsDeviceId;
  64473. if (constraints && constraints.deviceId) {
  64474. constraintsDeviceId = {
  64475. exact: constraints.deviceId,
  64476. };
  64477. }
  64478. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64479. if (navigator.mediaDevices) {
  64480. navigator.mediaDevices.getUserMedia({ video: constraints })
  64481. .then(function (stream) {
  64482. if (video.mozSrcObject !== undefined) {
  64483. // hack for Firefox < 19
  64484. video.mozSrcObject = stream;
  64485. }
  64486. else {
  64487. video.srcObject = stream;
  64488. }
  64489. var onPlaying = function () {
  64490. if (onReady) {
  64491. onReady(new VideoTexture("video", video, scene, true, true));
  64492. }
  64493. video.removeEventListener("playing", onPlaying);
  64494. };
  64495. video.addEventListener("playing", onPlaying);
  64496. video.play();
  64497. })
  64498. .catch(function (err) {
  64499. BABYLON.Tools.Error(err.name);
  64500. });
  64501. }
  64502. else {
  64503. navigator.getUserMedia =
  64504. navigator.getUserMedia ||
  64505. navigator.webkitGetUserMedia ||
  64506. navigator.mozGetUserMedia ||
  64507. navigator.msGetUserMedia;
  64508. if (navigator.getUserMedia) {
  64509. navigator.getUserMedia({
  64510. video: {
  64511. deviceId: constraintsDeviceId,
  64512. width: {
  64513. min: (constraints && constraints.minWidth) || 256,
  64514. max: (constraints && constraints.maxWidth) || 640,
  64515. },
  64516. height: {
  64517. min: (constraints && constraints.minHeight) || 256,
  64518. max: (constraints && constraints.maxHeight) || 480,
  64519. },
  64520. },
  64521. }, function (stream) {
  64522. if (video.mozSrcObject !== undefined) {
  64523. // hack for Firefox < 19
  64524. video.mozSrcObject = stream;
  64525. }
  64526. else {
  64527. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64528. }
  64529. video.play();
  64530. if (onReady) {
  64531. onReady(new VideoTexture("video", video, scene, true, true));
  64532. }
  64533. }, function (e) {
  64534. BABYLON.Tools.Error(e.name);
  64535. });
  64536. }
  64537. }
  64538. };
  64539. return VideoTexture;
  64540. }(BABYLON.Texture));
  64541. BABYLON.VideoTexture = VideoTexture;
  64542. })(BABYLON || (BABYLON = {}));
  64543. //# sourceMappingURL=babylon.videoTexture.js.map
  64544. var BABYLON;
  64545. (function (BABYLON) {
  64546. var RawTexture = /** @class */ (function (_super) {
  64547. __extends(RawTexture, _super);
  64548. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64549. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64550. if (invertY === void 0) { invertY = false; }
  64551. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64552. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64553. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64554. _this.format = format;
  64555. _this._engine = scene.getEngine();
  64556. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64557. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64558. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64559. return _this;
  64560. }
  64561. RawTexture.prototype.update = function (data) {
  64562. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64563. };
  64564. // Statics
  64565. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64566. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64567. if (invertY === void 0) { invertY = false; }
  64568. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64569. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64570. };
  64571. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64572. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64573. if (invertY === void 0) { invertY = false; }
  64574. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64575. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64576. };
  64577. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64578. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64579. if (invertY === void 0) { invertY = false; }
  64580. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64581. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64582. };
  64583. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64584. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64585. if (invertY === void 0) { invertY = false; }
  64586. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64587. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64588. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64589. };
  64590. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64591. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64592. if (invertY === void 0) { invertY = false; }
  64593. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64594. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64595. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64596. };
  64597. return RawTexture;
  64598. }(BABYLON.Texture));
  64599. BABYLON.RawTexture = RawTexture;
  64600. })(BABYLON || (BABYLON = {}));
  64601. //# sourceMappingURL=babylon.rawTexture.js.map
  64602. var BABYLON;
  64603. (function (BABYLON) {
  64604. /**
  64605. * Class used to store 3D textures containing user data
  64606. */
  64607. var RawTexture3D = /** @class */ (function (_super) {
  64608. __extends(RawTexture3D, _super);
  64609. /**
  64610. * Create a new RawTexture3D
  64611. * @param data defines the data of the texture
  64612. * @param width defines the width of the texture
  64613. * @param height defines the height of the texture
  64614. * @param depth defines the depth of the texture
  64615. * @param format defines the texture format to use
  64616. * @param scene defines the hosting scene
  64617. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64618. * @param invertY defines if texture must be stored with Y axis inverted
  64619. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64620. */
  64621. function RawTexture3D(data, width, height, depth,
  64622. /** Gets or sets the texture format to use*/
  64623. format, scene, generateMipMaps, invertY, samplingMode) {
  64624. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64625. if (invertY === void 0) { invertY = false; }
  64626. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64627. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64628. _this.format = format;
  64629. _this._engine = scene.getEngine();
  64630. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64631. _this.is3D = true;
  64632. return _this;
  64633. }
  64634. /**
  64635. * Update the texture with new data
  64636. * @param data defines the data to store in the texture
  64637. */
  64638. RawTexture3D.prototype.update = function (data) {
  64639. if (!this._texture) {
  64640. return;
  64641. }
  64642. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64643. };
  64644. return RawTexture3D;
  64645. }(BABYLON.Texture));
  64646. BABYLON.RawTexture3D = RawTexture3D;
  64647. })(BABYLON || (BABYLON = {}));
  64648. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64649. var BABYLON;
  64650. (function (BABYLON) {
  64651. /**
  64652. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64653. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64654. */
  64655. var PostProcess = /** @class */ (function () {
  64656. /**
  64657. * Creates a new instance PostProcess
  64658. * @param name The name of the PostProcess.
  64659. * @param fragmentUrl The url of the fragment shader to be used.
  64660. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64661. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64662. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64663. * @param camera The camera to apply the render pass to.
  64664. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64665. * @param engine The engine which the post process will be applied. (default: current engine)
  64666. * @param reusable If the post process can be reused on the same frame. (default: false)
  64667. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64668. * @param textureType Type of textures used when performing the post process. (default: 0)
  64669. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64670. * @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
  64671. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64672. */
  64673. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64674. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64675. if (defines === void 0) { defines = null; }
  64676. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64677. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64678. if (blockCompilation === void 0) { blockCompilation = false; }
  64679. this.name = name;
  64680. /**
  64681. * Width of the texture to apply the post process on
  64682. */
  64683. this.width = -1;
  64684. /**
  64685. * Height of the texture to apply the post process on
  64686. */
  64687. this.height = -1;
  64688. /**
  64689. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64690. */
  64691. this._outputTexture = null;
  64692. /**
  64693. * If the buffer needs to be cleared before applying the post process. (default: true)
  64694. * Should be set to false if shader will overwrite all previous pixels.
  64695. */
  64696. this.autoClear = true;
  64697. /**
  64698. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64699. */
  64700. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64701. /**
  64702. * Animations to be used for the post processing
  64703. */
  64704. this.animations = new Array();
  64705. /**
  64706. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64707. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64708. */
  64709. this.enablePixelPerfectMode = false;
  64710. /**
  64711. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64712. */
  64713. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64714. /**
  64715. * Force textures to be a power of two (default: false)
  64716. */
  64717. this.alwaysForcePOT = false;
  64718. /**
  64719. * Number of sample textures (default: 1)
  64720. */
  64721. this.samples = 1;
  64722. /**
  64723. * Modify the scale of the post process to be the same as the viewport (default: false)
  64724. */
  64725. this.adaptScaleToCurrentViewport = false;
  64726. this._reusable = false;
  64727. /**
  64728. * Smart array of input and output textures for the post process.
  64729. */
  64730. this._textures = new BABYLON.SmartArray(2);
  64731. /**
  64732. * The index in _textures that corresponds to the output texture.
  64733. */
  64734. this._currentRenderTextureInd = 0;
  64735. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64736. this._texelSize = BABYLON.Vector2.Zero();
  64737. // Events
  64738. /**
  64739. * An event triggered when the postprocess is activated.
  64740. */
  64741. this.onActivateObservable = new BABYLON.Observable();
  64742. /**
  64743. * An event triggered when the postprocess changes its size.
  64744. */
  64745. this.onSizeChangedObservable = new BABYLON.Observable();
  64746. /**
  64747. * An event triggered when the postprocess applies its effect.
  64748. */
  64749. this.onApplyObservable = new BABYLON.Observable();
  64750. /**
  64751. * An event triggered before rendering the postprocess
  64752. */
  64753. this.onBeforeRenderObservable = new BABYLON.Observable();
  64754. /**
  64755. * An event triggered after rendering the postprocess
  64756. */
  64757. this.onAfterRenderObservable = new BABYLON.Observable();
  64758. if (camera != null) {
  64759. this._camera = camera;
  64760. this._scene = camera.getScene();
  64761. camera.attachPostProcess(this);
  64762. this._engine = this._scene.getEngine();
  64763. this._scene.postProcesses.push(this);
  64764. }
  64765. else if (engine) {
  64766. this._engine = engine;
  64767. this._engine.postProcesses.push(this);
  64768. }
  64769. this._options = options;
  64770. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64771. this._reusable = reusable || false;
  64772. this._textureType = textureType;
  64773. this._samplers = samplers || [];
  64774. this._samplers.push("textureSampler");
  64775. this._fragmentUrl = fragmentUrl;
  64776. this._vertexUrl = vertexUrl;
  64777. this._parameters = parameters || [];
  64778. this._parameters.push("scale");
  64779. this._indexParameters = indexParameters;
  64780. if (!blockCompilation) {
  64781. this.updateEffect(defines);
  64782. }
  64783. }
  64784. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64785. /**
  64786. * A function that is added to the onActivateObservable
  64787. */
  64788. set: function (callback) {
  64789. if (this._onActivateObserver) {
  64790. this.onActivateObservable.remove(this._onActivateObserver);
  64791. }
  64792. if (callback) {
  64793. this._onActivateObserver = this.onActivateObservable.add(callback);
  64794. }
  64795. },
  64796. enumerable: true,
  64797. configurable: true
  64798. });
  64799. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64800. /**
  64801. * A function that is added to the onSizeChangedObservable
  64802. */
  64803. set: function (callback) {
  64804. if (this._onSizeChangedObserver) {
  64805. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64806. }
  64807. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64808. },
  64809. enumerable: true,
  64810. configurable: true
  64811. });
  64812. Object.defineProperty(PostProcess.prototype, "onApply", {
  64813. /**
  64814. * A function that is added to the onApplyObservable
  64815. */
  64816. set: function (callback) {
  64817. if (this._onApplyObserver) {
  64818. this.onApplyObservable.remove(this._onApplyObserver);
  64819. }
  64820. this._onApplyObserver = this.onApplyObservable.add(callback);
  64821. },
  64822. enumerable: true,
  64823. configurable: true
  64824. });
  64825. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64826. /**
  64827. * A function that is added to the onBeforeRenderObservable
  64828. */
  64829. set: function (callback) {
  64830. if (this._onBeforeRenderObserver) {
  64831. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64832. }
  64833. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64834. },
  64835. enumerable: true,
  64836. configurable: true
  64837. });
  64838. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  64839. /**
  64840. * A function that is added to the onAfterRenderObservable
  64841. */
  64842. set: function (callback) {
  64843. if (this._onAfterRenderObserver) {
  64844. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64845. }
  64846. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64847. },
  64848. enumerable: true,
  64849. configurable: true
  64850. });
  64851. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  64852. /**
  64853. * 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
  64854. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  64855. */
  64856. get: function () {
  64857. return this._textures.data[this._currentRenderTextureInd];
  64858. },
  64859. set: function (value) {
  64860. this._forcedOutputTexture = value;
  64861. },
  64862. enumerable: true,
  64863. configurable: true
  64864. });
  64865. /**
  64866. * Gets the camera which post process is applied to.
  64867. * @returns The camera the post process is applied to.
  64868. */
  64869. PostProcess.prototype.getCamera = function () {
  64870. return this._camera;
  64871. };
  64872. Object.defineProperty(PostProcess.prototype, "texelSize", {
  64873. /**
  64874. * Gets the texel size of the postprocess.
  64875. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  64876. */
  64877. get: function () {
  64878. if (this._shareOutputWithPostProcess) {
  64879. return this._shareOutputWithPostProcess.texelSize;
  64880. }
  64881. if (this._forcedOutputTexture) {
  64882. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  64883. }
  64884. return this._texelSize;
  64885. },
  64886. enumerable: true,
  64887. configurable: true
  64888. });
  64889. /**
  64890. * Gets the engine which this post process belongs to.
  64891. * @returns The engine the post process was enabled with.
  64892. */
  64893. PostProcess.prototype.getEngine = function () {
  64894. return this._engine;
  64895. };
  64896. /**
  64897. * The effect that is created when initializing the post process.
  64898. * @returns The created effect corrisponding the the postprocess.
  64899. */
  64900. PostProcess.prototype.getEffect = function () {
  64901. return this._effect;
  64902. };
  64903. /**
  64904. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  64905. * @param postProcess The post process to share the output with.
  64906. * @returns This post process.
  64907. */
  64908. PostProcess.prototype.shareOutputWith = function (postProcess) {
  64909. this._disposeTextures();
  64910. this._shareOutputWithPostProcess = postProcess;
  64911. return this;
  64912. };
  64913. /**
  64914. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  64915. * This should be called if the post process that shares output with this post process is disabled/disposed.
  64916. */
  64917. PostProcess.prototype.useOwnOutput = function () {
  64918. if (this._textures.length == 0) {
  64919. this._textures = new BABYLON.SmartArray(2);
  64920. }
  64921. this._shareOutputWithPostProcess = null;
  64922. };
  64923. /**
  64924. * Updates the effect with the current post process compile time values and recompiles the shader.
  64925. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  64926. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  64927. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  64928. * @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
  64929. * @param onCompiled Called when the shader has been compiled.
  64930. * @param onError Called if there is an error when compiling a shader.
  64931. */
  64932. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  64933. if (defines === void 0) { defines = null; }
  64934. if (uniforms === void 0) { uniforms = null; }
  64935. if (samplers === void 0) { samplers = null; }
  64936. 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);
  64937. };
  64938. /**
  64939. * The post process is reusable if it can be used multiple times within one frame.
  64940. * @returns If the post process is reusable
  64941. */
  64942. PostProcess.prototype.isReusable = function () {
  64943. return this._reusable;
  64944. };
  64945. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  64946. PostProcess.prototype.markTextureDirty = function () {
  64947. this.width = -1;
  64948. };
  64949. /**
  64950. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  64951. * 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.
  64952. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  64953. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  64954. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  64955. * @returns The target texture that was bound to be written to.
  64956. */
  64957. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  64958. var _this = this;
  64959. if (sourceTexture === void 0) { sourceTexture = null; }
  64960. camera = camera || this._camera;
  64961. var scene = camera.getScene();
  64962. var engine = scene.getEngine();
  64963. var maxSize = engine.getCaps().maxTextureSize;
  64964. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  64965. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  64966. // 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
  64967. var webVRCamera = camera.parent;
  64968. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  64969. requiredWidth /= 2;
  64970. }
  64971. var desiredWidth = (this._options.width || requiredWidth);
  64972. var desiredHeight = this._options.height || requiredHeight;
  64973. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  64974. if (this.adaptScaleToCurrentViewport) {
  64975. var currentViewport = engine.currentViewport;
  64976. if (currentViewport) {
  64977. desiredWidth *= currentViewport.width;
  64978. desiredHeight *= currentViewport.height;
  64979. }
  64980. }
  64981. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  64982. if (!this._options.width) {
  64983. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  64984. }
  64985. if (!this._options.height) {
  64986. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  64987. }
  64988. }
  64989. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  64990. if (this._textures.length > 0) {
  64991. for (var i = 0; i < this._textures.length; i++) {
  64992. this._engine._releaseTexture(this._textures.data[i]);
  64993. }
  64994. this._textures.reset();
  64995. }
  64996. this.width = desiredWidth;
  64997. this.height = desiredHeight;
  64998. var textureSize = { width: this.width, height: this.height };
  64999. var textureOptions = {
  65000. generateMipMaps: false,
  65001. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65002. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65003. samplingMode: this.renderTargetSamplingMode,
  65004. type: this._textureType
  65005. };
  65006. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65007. if (this._reusable) {
  65008. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65009. }
  65010. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65011. this.onSizeChangedObservable.notifyObservers(this);
  65012. }
  65013. this._textures.forEach(function (texture) {
  65014. if (texture.samples !== _this.samples) {
  65015. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65016. }
  65017. });
  65018. }
  65019. var target;
  65020. if (this._shareOutputWithPostProcess) {
  65021. target = this._shareOutputWithPostProcess.inputTexture;
  65022. }
  65023. else if (this._forcedOutputTexture) {
  65024. target = this._forcedOutputTexture;
  65025. this.width = this._forcedOutputTexture.width;
  65026. this.height = this._forcedOutputTexture.height;
  65027. }
  65028. else {
  65029. target = this.inputTexture;
  65030. }
  65031. // Bind the input of this post process to be used as the output of the previous post process.
  65032. if (this.enablePixelPerfectMode) {
  65033. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65034. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  65035. }
  65036. else {
  65037. this._scaleRatio.copyFromFloats(1, 1);
  65038. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  65039. }
  65040. this.onActivateObservable.notifyObservers(camera);
  65041. // Clear
  65042. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65043. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65044. }
  65045. if (this._reusable) {
  65046. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65047. }
  65048. return target;
  65049. };
  65050. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65051. /**
  65052. * If the post process is supported.
  65053. */
  65054. get: function () {
  65055. return this._effect.isSupported;
  65056. },
  65057. enumerable: true,
  65058. configurable: true
  65059. });
  65060. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65061. /**
  65062. * The aspect ratio of the output texture.
  65063. */
  65064. get: function () {
  65065. if (this._shareOutputWithPostProcess) {
  65066. return this._shareOutputWithPostProcess.aspectRatio;
  65067. }
  65068. if (this._forcedOutputTexture) {
  65069. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65070. }
  65071. return this.width / this.height;
  65072. },
  65073. enumerable: true,
  65074. configurable: true
  65075. });
  65076. /**
  65077. * Get a value indicating if the post-process is ready to be used
  65078. * @returns true if the post-process is ready (shader is compiled)
  65079. */
  65080. PostProcess.prototype.isReady = function () {
  65081. return this._effect && this._effect.isReady();
  65082. };
  65083. /**
  65084. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65085. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65086. */
  65087. PostProcess.prototype.apply = function () {
  65088. // Check
  65089. if (!this._effect || !this._effect.isReady())
  65090. return null;
  65091. // States
  65092. this._engine.enableEffect(this._effect);
  65093. this._engine.setState(false);
  65094. this._engine.setDepthBuffer(false);
  65095. this._engine.setDepthWrite(false);
  65096. // Alpha
  65097. this._engine.setAlphaMode(this.alphaMode);
  65098. if (this.alphaConstants) {
  65099. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65100. }
  65101. // Bind the output texture of the preivous post process as the input to this post process.
  65102. var source;
  65103. if (this._shareOutputWithPostProcess) {
  65104. source = this._shareOutputWithPostProcess.inputTexture;
  65105. }
  65106. else if (this._forcedOutputTexture) {
  65107. source = this._forcedOutputTexture;
  65108. }
  65109. else {
  65110. source = this.inputTexture;
  65111. }
  65112. this._effect._bindTexture("textureSampler", source);
  65113. // Parameters
  65114. this._effect.setVector2("scale", this._scaleRatio);
  65115. this.onApplyObservable.notifyObservers(this._effect);
  65116. return this._effect;
  65117. };
  65118. PostProcess.prototype._disposeTextures = function () {
  65119. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65120. return;
  65121. }
  65122. if (this._textures.length > 0) {
  65123. for (var i = 0; i < this._textures.length; i++) {
  65124. this._engine._releaseTexture(this._textures.data[i]);
  65125. }
  65126. }
  65127. this._textures.dispose();
  65128. };
  65129. /**
  65130. * Disposes the post process.
  65131. * @param camera The camera to dispose the post process on.
  65132. */
  65133. PostProcess.prototype.dispose = function (camera) {
  65134. camera = camera || this._camera;
  65135. this._disposeTextures();
  65136. if (this._scene) {
  65137. var index_1 = this._scene.postProcesses.indexOf(this);
  65138. if (index_1 !== -1) {
  65139. this._scene.postProcesses.splice(index_1, 1);
  65140. }
  65141. }
  65142. else {
  65143. var index_2 = this._engine.postProcesses.indexOf(this);
  65144. if (index_2 !== -1) {
  65145. this._engine.postProcesses.splice(index_2, 1);
  65146. }
  65147. }
  65148. if (!camera) {
  65149. return;
  65150. }
  65151. camera.detachPostProcess(this);
  65152. var index = camera._postProcesses.indexOf(this);
  65153. if (index === 0 && camera._postProcesses.length > 0) {
  65154. var firstPostProcess = this._camera._getFirstPostProcess();
  65155. if (firstPostProcess) {
  65156. firstPostProcess.markTextureDirty();
  65157. }
  65158. }
  65159. this.onActivateObservable.clear();
  65160. this.onAfterRenderObservable.clear();
  65161. this.onApplyObservable.clear();
  65162. this.onBeforeRenderObservable.clear();
  65163. this.onSizeChangedObservable.clear();
  65164. };
  65165. return PostProcess;
  65166. }());
  65167. BABYLON.PostProcess = PostProcess;
  65168. })(BABYLON || (BABYLON = {}));
  65169. //# sourceMappingURL=babylon.postProcess.js.map
  65170. var BABYLON;
  65171. (function (BABYLON) {
  65172. var PassPostProcess = /** @class */ (function (_super) {
  65173. __extends(PassPostProcess, _super);
  65174. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65175. if (camera === void 0) { camera = null; }
  65176. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65177. if (blockCompilation === void 0) { blockCompilation = false; }
  65178. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65179. }
  65180. return PassPostProcess;
  65181. }(BABYLON.PostProcess));
  65182. BABYLON.PassPostProcess = PassPostProcess;
  65183. })(BABYLON || (BABYLON = {}));
  65184. //# sourceMappingURL=babylon.passPostProcess.js.map
  65185. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65186. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65187. s = arguments[i];
  65188. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65189. t[p] = s[p];
  65190. }
  65191. return t;
  65192. };
  65193. var BABYLON;
  65194. (function (BABYLON) {
  65195. /**
  65196. * Default implementation IShadowGenerator.
  65197. * This is the main object responsible of generating shadows in the framework.
  65198. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65199. */
  65200. var ShadowGenerator = /** @class */ (function () {
  65201. /**
  65202. * Creates a ShadowGenerator object.
  65203. * A ShadowGenerator is the required tool to use the shadows.
  65204. * Each light casting shadows needs to use its own ShadowGenerator.
  65205. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65206. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65207. * @param light The light object generating the shadows.
  65208. * @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.
  65209. */
  65210. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65211. this._bias = 0.00005;
  65212. this._normalBias = 0;
  65213. this._blurBoxOffset = 1;
  65214. this._blurScale = 2;
  65215. this._blurKernel = 1;
  65216. this._useKernelBlur = false;
  65217. this._filter = ShadowGenerator.FILTER_NONE;
  65218. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65219. this._contactHardeningLightSizeUVRatio = 0.1;
  65220. this._darkness = 0;
  65221. this._transparencyShadow = false;
  65222. /**
  65223. * Controls the extent to which the shadows fade out at the edge of the frustum
  65224. * Used only by directionals and spots
  65225. */
  65226. this.frustumEdgeFalloff = 0;
  65227. /**
  65228. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65229. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65230. * It might on the other hand introduce peter panning.
  65231. */
  65232. this.forceBackFacesOnly = false;
  65233. this._lightDirection = BABYLON.Vector3.Zero();
  65234. this._viewMatrix = BABYLON.Matrix.Zero();
  65235. this._projectionMatrix = BABYLON.Matrix.Zero();
  65236. this._transformMatrix = BABYLON.Matrix.Zero();
  65237. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65238. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65239. this._currentFaceIndex = 0;
  65240. this._currentFaceIndexCache = 0;
  65241. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65242. this._mapSize = mapSize;
  65243. this._light = light;
  65244. this._scene = light.getScene();
  65245. light._shadowGenerator = this;
  65246. // Texture type fallback from float to int if not supported.
  65247. var caps = this._scene.getEngine().getCaps();
  65248. if (!useFullFloatFirst) {
  65249. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65250. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65251. }
  65252. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65253. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65254. }
  65255. else {
  65256. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65257. }
  65258. }
  65259. else {
  65260. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65261. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65262. }
  65263. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65264. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65265. }
  65266. else {
  65267. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65268. }
  65269. }
  65270. this._initializeGenerator();
  65271. this._applyFilterValues();
  65272. }
  65273. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65274. /**
  65275. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65276. */
  65277. get: function () {
  65278. return this._bias;
  65279. },
  65280. /**
  65281. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65282. */
  65283. set: function (bias) {
  65284. this._bias = bias;
  65285. },
  65286. enumerable: true,
  65287. configurable: true
  65288. });
  65289. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65290. /**
  65291. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65292. */
  65293. get: function () {
  65294. return this._normalBias;
  65295. },
  65296. /**
  65297. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65298. */
  65299. set: function (normalBias) {
  65300. this._normalBias = normalBias;
  65301. },
  65302. enumerable: true,
  65303. configurable: true
  65304. });
  65305. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65306. /**
  65307. * Gets the blur box offset: offset applied during the blur pass.
  65308. * Only usefull if useKernelBlur = false
  65309. */
  65310. get: function () {
  65311. return this._blurBoxOffset;
  65312. },
  65313. /**
  65314. * Sets the blur box offset: offset applied during the blur pass.
  65315. * Only usefull if useKernelBlur = false
  65316. */
  65317. set: function (value) {
  65318. if (this._blurBoxOffset === value) {
  65319. return;
  65320. }
  65321. this._blurBoxOffset = value;
  65322. this._disposeBlurPostProcesses();
  65323. },
  65324. enumerable: true,
  65325. configurable: true
  65326. });
  65327. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65328. /**
  65329. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65330. * 2 means half of the size.
  65331. */
  65332. get: function () {
  65333. return this._blurScale;
  65334. },
  65335. /**
  65336. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65337. * 2 means half of the size.
  65338. */
  65339. set: function (value) {
  65340. if (this._blurScale === value) {
  65341. return;
  65342. }
  65343. this._blurScale = value;
  65344. this._disposeBlurPostProcesses();
  65345. },
  65346. enumerable: true,
  65347. configurable: true
  65348. });
  65349. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65350. /**
  65351. * Gets the blur kernel: kernel size of the blur pass.
  65352. * Only usefull if useKernelBlur = true
  65353. */
  65354. get: function () {
  65355. return this._blurKernel;
  65356. },
  65357. /**
  65358. * Sets the blur kernel: kernel size of the blur pass.
  65359. * Only usefull if useKernelBlur = true
  65360. */
  65361. set: function (value) {
  65362. if (this._blurKernel === value) {
  65363. return;
  65364. }
  65365. this._blurKernel = value;
  65366. this._disposeBlurPostProcesses();
  65367. },
  65368. enumerable: true,
  65369. configurable: true
  65370. });
  65371. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65372. /**
  65373. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65374. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65375. */
  65376. get: function () {
  65377. return this._useKernelBlur;
  65378. },
  65379. /**
  65380. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65381. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65382. */
  65383. set: function (value) {
  65384. if (this._useKernelBlur === value) {
  65385. return;
  65386. }
  65387. this._useKernelBlur = value;
  65388. this._disposeBlurPostProcesses();
  65389. },
  65390. enumerable: true,
  65391. configurable: true
  65392. });
  65393. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65394. /**
  65395. * Gets the depth scale used in ESM mode.
  65396. */
  65397. get: function () {
  65398. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65399. },
  65400. /**
  65401. * Sets the depth scale used in ESM mode.
  65402. * This can override the scale stored on the light.
  65403. */
  65404. set: function (value) {
  65405. this._depthScale = value;
  65406. },
  65407. enumerable: true,
  65408. configurable: true
  65409. });
  65410. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65411. /**
  65412. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65413. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65414. */
  65415. get: function () {
  65416. return this._filter;
  65417. },
  65418. /**
  65419. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65420. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65421. */
  65422. set: function (value) {
  65423. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65424. if (this._light.needCube()) {
  65425. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65426. this.useExponentialShadowMap = true;
  65427. return;
  65428. }
  65429. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65430. this.useCloseExponentialShadowMap = true;
  65431. return;
  65432. }
  65433. // PCF on cubemap would also be expensive
  65434. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65435. this.usePoissonSampling = true;
  65436. return;
  65437. }
  65438. }
  65439. // Weblg1 fallback for PCF.
  65440. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65441. if (this._scene.getEngine().webGLVersion === 1) {
  65442. this.usePoissonSampling = true;
  65443. return;
  65444. }
  65445. }
  65446. if (this._filter === value) {
  65447. return;
  65448. }
  65449. this._filter = value;
  65450. this._disposeBlurPostProcesses();
  65451. this._applyFilterValues();
  65452. this._light._markMeshesAsLightDirty();
  65453. },
  65454. enumerable: true,
  65455. configurable: true
  65456. });
  65457. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65458. /**
  65459. * Gets if the current filter is set to Poisson Sampling.
  65460. */
  65461. get: function () {
  65462. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65463. },
  65464. /**
  65465. * Sets the current filter to Poisson Sampling.
  65466. */
  65467. set: function (value) {
  65468. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65469. return;
  65470. }
  65471. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65472. },
  65473. enumerable: true,
  65474. configurable: true
  65475. });
  65476. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65477. /**
  65478. * Gets if the current filter is set to VSM.
  65479. * DEPRECATED. Should use useExponentialShadowMap instead.
  65480. */
  65481. get: function () {
  65482. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65483. return this.useExponentialShadowMap;
  65484. },
  65485. /**
  65486. * Sets the current filter is to VSM.
  65487. * DEPRECATED. Should use useExponentialShadowMap instead.
  65488. */
  65489. set: function (value) {
  65490. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65491. this.useExponentialShadowMap = value;
  65492. },
  65493. enumerable: true,
  65494. configurable: true
  65495. });
  65496. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65497. /**
  65498. * Gets if the current filter is set to blurred VSM.
  65499. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65500. */
  65501. get: function () {
  65502. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65503. return this.useBlurExponentialShadowMap;
  65504. },
  65505. /**
  65506. * Sets the current filter is to blurred VSM.
  65507. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65508. */
  65509. set: function (value) {
  65510. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65511. this.useBlurExponentialShadowMap = value;
  65512. },
  65513. enumerable: true,
  65514. configurable: true
  65515. });
  65516. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65517. /**
  65518. * Gets if the current filter is set to ESM.
  65519. */
  65520. get: function () {
  65521. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65522. },
  65523. /**
  65524. * Sets the current filter is to ESM.
  65525. */
  65526. set: function (value) {
  65527. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65528. return;
  65529. }
  65530. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65531. },
  65532. enumerable: true,
  65533. configurable: true
  65534. });
  65535. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65536. /**
  65537. * Gets if the current filter is set to filtered ESM.
  65538. */
  65539. get: function () {
  65540. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65541. },
  65542. /**
  65543. * Gets if the current filter is set to filtered ESM.
  65544. */
  65545. set: function (value) {
  65546. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65547. return;
  65548. }
  65549. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65550. },
  65551. enumerable: true,
  65552. configurable: true
  65553. });
  65554. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65555. /**
  65556. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65557. * exponential to prevent steep falloff artifacts).
  65558. */
  65559. get: function () {
  65560. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65561. },
  65562. /**
  65563. * Sets the current filter to "close ESM" (using the inverse of the
  65564. * exponential to prevent steep falloff artifacts).
  65565. */
  65566. set: function (value) {
  65567. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65568. return;
  65569. }
  65570. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65571. },
  65572. enumerable: true,
  65573. configurable: true
  65574. });
  65575. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65576. /**
  65577. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65578. * exponential to prevent steep falloff artifacts).
  65579. */
  65580. get: function () {
  65581. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65582. },
  65583. /**
  65584. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65585. * exponential to prevent steep falloff artifacts).
  65586. */
  65587. set: function (value) {
  65588. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65589. return;
  65590. }
  65591. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65592. },
  65593. enumerable: true,
  65594. configurable: true
  65595. });
  65596. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65597. /**
  65598. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65599. */
  65600. get: function () {
  65601. return this.filter === ShadowGenerator.FILTER_PCF;
  65602. },
  65603. /**
  65604. * Sets the current filter to "PCF" (percentage closer filtering).
  65605. */
  65606. set: function (value) {
  65607. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65608. return;
  65609. }
  65610. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65611. },
  65612. enumerable: true,
  65613. configurable: true
  65614. });
  65615. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65616. /**
  65617. * Gets the PCF or PCSS Quality.
  65618. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65619. */
  65620. get: function () {
  65621. return this._filteringQuality;
  65622. },
  65623. /**
  65624. * Sets the PCF or PCSS Quality.
  65625. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65626. */
  65627. set: function (filteringQuality) {
  65628. this._filteringQuality = filteringQuality;
  65629. },
  65630. enumerable: true,
  65631. configurable: true
  65632. });
  65633. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65634. /**
  65635. * Gets if the current filter is set to "PCSS" (contact hardening).
  65636. */
  65637. get: function () {
  65638. return this.filter === ShadowGenerator.FILTER_PCSS;
  65639. },
  65640. /**
  65641. * Sets the current filter to "PCSS" (contact hardening).
  65642. */
  65643. set: function (value) {
  65644. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65645. return;
  65646. }
  65647. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65648. },
  65649. enumerable: true,
  65650. configurable: true
  65651. });
  65652. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65653. /**
  65654. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65655. * Using a ratio helps keeping shape stability independently of the map size.
  65656. *
  65657. * It does not account for the light projection as it was having too much
  65658. * instability during the light setup or during light position changes.
  65659. *
  65660. * Only valid if useContactHardeningShadow is true.
  65661. */
  65662. get: function () {
  65663. return this._contactHardeningLightSizeUVRatio;
  65664. },
  65665. /**
  65666. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65667. * Using a ratio helps keeping shape stability independently of the map size.
  65668. *
  65669. * It does not account for the light projection as it was having too much
  65670. * instability during the light setup or during light position changes.
  65671. *
  65672. * Only valid if useContactHardeningShadow is true.
  65673. */
  65674. set: function (contactHardeningLightSizeUVRatio) {
  65675. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65676. },
  65677. enumerable: true,
  65678. configurable: true
  65679. });
  65680. /**
  65681. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65682. * 0 means strongest and 1 would means no shadow.
  65683. * @returns the darkness.
  65684. */
  65685. ShadowGenerator.prototype.getDarkness = function () {
  65686. return this._darkness;
  65687. };
  65688. /**
  65689. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65690. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65691. * @returns the shadow generator allowing fluent coding.
  65692. */
  65693. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65694. if (darkness >= 1.0)
  65695. this._darkness = 1.0;
  65696. else if (darkness <= 0.0)
  65697. this._darkness = 0.0;
  65698. else
  65699. this._darkness = darkness;
  65700. return this;
  65701. };
  65702. /**
  65703. * Sets the ability to have transparent shadow (boolean).
  65704. * @param transparent True if transparent else False
  65705. * @returns the shadow generator allowing fluent coding
  65706. */
  65707. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65708. this._transparencyShadow = transparent;
  65709. return this;
  65710. };
  65711. /**
  65712. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65713. * @returns The render target texture if present otherwise, null
  65714. */
  65715. ShadowGenerator.prototype.getShadowMap = function () {
  65716. return this._shadowMap;
  65717. };
  65718. /**
  65719. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65720. * @returns The render target texture if the shadow map is present otherwise, null
  65721. */
  65722. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65723. if (this._shadowMap2) {
  65724. return this._shadowMap2;
  65725. }
  65726. return this._shadowMap;
  65727. };
  65728. /**
  65729. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65730. * @param mesh Mesh to add
  65731. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65732. * @returns the Shadow Generator itself
  65733. */
  65734. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65735. if (includeDescendants === void 0) { includeDescendants = true; }
  65736. if (!this._shadowMap) {
  65737. return this;
  65738. }
  65739. if (!this._shadowMap.renderList) {
  65740. this._shadowMap.renderList = [];
  65741. }
  65742. this._shadowMap.renderList.push(mesh);
  65743. if (includeDescendants) {
  65744. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65745. }
  65746. return this;
  65747. var _a;
  65748. };
  65749. /**
  65750. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65751. * @param mesh Mesh to remove
  65752. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65753. * @returns the Shadow Generator itself
  65754. */
  65755. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65756. if (includeDescendants === void 0) { includeDescendants = true; }
  65757. if (!this._shadowMap || !this._shadowMap.renderList) {
  65758. return this;
  65759. }
  65760. var index = this._shadowMap.renderList.indexOf(mesh);
  65761. if (index !== -1) {
  65762. this._shadowMap.renderList.splice(index, 1);
  65763. }
  65764. if (includeDescendants) {
  65765. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65766. var child = _a[_i];
  65767. this.removeShadowCaster(child);
  65768. }
  65769. }
  65770. return this;
  65771. };
  65772. /**
  65773. * Returns the associated light object.
  65774. * @returns the light generating the shadow
  65775. */
  65776. ShadowGenerator.prototype.getLight = function () {
  65777. return this._light;
  65778. };
  65779. ShadowGenerator.prototype._initializeGenerator = function () {
  65780. this._light._markMeshesAsLightDirty();
  65781. this._initializeShadowMap();
  65782. };
  65783. ShadowGenerator.prototype._initializeShadowMap = function () {
  65784. var _this = this;
  65785. // Render target
  65786. var engine = this._scene.getEngine();
  65787. if (engine.webGLVersion > 1) {
  65788. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65789. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65790. }
  65791. else {
  65792. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65793. }
  65794. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65795. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65796. this._shadowMap.anisotropicFilteringLevel = 1;
  65797. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65798. this._shadowMap.renderParticles = false;
  65799. this._shadowMap.ignoreCameraViewport = true;
  65800. // Record Face Index before render.
  65801. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65802. _this._currentFaceIndex = faceIndex;
  65803. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65804. engine.setColorWrite(false);
  65805. }
  65806. });
  65807. // Custom render function.
  65808. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65809. // Blur if required afer render.
  65810. this._shadowMap.onAfterUnbindObservable.add(function () {
  65811. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65812. engine.setColorWrite(true);
  65813. }
  65814. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65815. return;
  65816. }
  65817. var shadowMap = _this.getShadowMapForRendering();
  65818. if (shadowMap) {
  65819. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65820. }
  65821. });
  65822. // Clear according to the chosen filter.
  65823. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65824. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65825. this._shadowMap.onClearObservable.add(function (engine) {
  65826. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65827. engine.clear(clearOne, false, true, false);
  65828. }
  65829. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65830. engine.clear(clearZero, true, true, false);
  65831. }
  65832. else {
  65833. engine.clear(clearOne, true, true, false);
  65834. }
  65835. });
  65836. };
  65837. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65838. var _this = this;
  65839. var engine = this._scene.getEngine();
  65840. var targetSize = this._mapSize / this.blurScale;
  65841. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  65842. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  65843. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65844. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65845. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65846. }
  65847. if (this.useKernelBlur) {
  65848. 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);
  65849. this._kernelBlurXPostprocess.width = targetSize;
  65850. this._kernelBlurXPostprocess.height = targetSize;
  65851. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  65852. effect.setTexture("textureSampler", _this._shadowMap);
  65853. });
  65854. 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);
  65855. this._kernelBlurXPostprocess.autoClear = false;
  65856. this._kernelBlurYPostprocess.autoClear = false;
  65857. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65858. this._kernelBlurXPostprocess.packedFloat = true;
  65859. this._kernelBlurYPostprocess.packedFloat = true;
  65860. }
  65861. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  65862. }
  65863. else {
  65864. 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);
  65865. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  65866. effect.setFloat2("screenSize", targetSize, targetSize);
  65867. effect.setTexture("textureSampler", _this._shadowMap);
  65868. });
  65869. this._boxBlurPostprocess.autoClear = false;
  65870. this._blurPostProcesses = [this._boxBlurPostprocess];
  65871. }
  65872. };
  65873. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65874. var index;
  65875. var engine = this._scene.getEngine();
  65876. if (depthOnlySubMeshes.length) {
  65877. engine.setColorWrite(false);
  65878. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65879. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  65880. }
  65881. engine.setColorWrite(true);
  65882. }
  65883. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65884. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  65885. }
  65886. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65887. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  65888. }
  65889. if (this._transparencyShadow) {
  65890. for (index = 0; index < transparentSubMeshes.length; index++) {
  65891. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  65892. }
  65893. }
  65894. };
  65895. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  65896. var _this = this;
  65897. var mesh = subMesh.getRenderingMesh();
  65898. var scene = this._scene;
  65899. var engine = scene.getEngine();
  65900. var material = subMesh.getMaterial();
  65901. if (!material) {
  65902. return;
  65903. }
  65904. // Culling
  65905. engine.setState(material.backFaceCulling);
  65906. // Managing instances
  65907. var batch = mesh._getInstancesRenderList(subMesh._id);
  65908. if (batch.mustReturn) {
  65909. return;
  65910. }
  65911. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  65912. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  65913. engine.enableEffect(this._effect);
  65914. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  65915. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  65916. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  65917. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  65918. this._effect.setVector3("lightData", this._cachedDirection);
  65919. }
  65920. else {
  65921. this._effect.setVector3("lightData", this._cachedPosition);
  65922. }
  65923. if (scene.activeCamera) {
  65924. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  65925. }
  65926. // Alpha test
  65927. if (material && material.needAlphaTesting()) {
  65928. var alphaTexture = material.getAlphaTestTexture();
  65929. if (alphaTexture) {
  65930. this._effect.setTexture("diffuseSampler", alphaTexture);
  65931. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  65932. }
  65933. }
  65934. // Bones
  65935. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65936. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  65937. }
  65938. // Morph targets
  65939. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  65940. if (this.forceBackFacesOnly) {
  65941. engine.setState(true, 0, false, true);
  65942. }
  65943. // Draw
  65944. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65945. if (this.forceBackFacesOnly) {
  65946. engine.setState(true, 0, false, false);
  65947. }
  65948. }
  65949. else {
  65950. // Need to reset refresh rate of the shadowMap
  65951. if (this._shadowMap) {
  65952. this._shadowMap.resetRefreshCounter();
  65953. }
  65954. }
  65955. };
  65956. ShadowGenerator.prototype._applyFilterValues = function () {
  65957. if (!this._shadowMap) {
  65958. return;
  65959. }
  65960. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  65961. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65962. }
  65963. else {
  65964. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65965. }
  65966. };
  65967. /**
  65968. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  65969. * @param onCompiled Callback triggered at the and of the effects compilation
  65970. * @param options Sets of optional options forcing the compilation with different modes
  65971. */
  65972. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  65973. var _this = this;
  65974. var localOptions = __assign({ useInstances: false }, options);
  65975. var shadowMap = this.getShadowMap();
  65976. if (!shadowMap) {
  65977. if (onCompiled) {
  65978. onCompiled(this);
  65979. }
  65980. return;
  65981. }
  65982. var renderList = shadowMap.renderList;
  65983. if (!renderList) {
  65984. if (onCompiled) {
  65985. onCompiled(this);
  65986. }
  65987. return;
  65988. }
  65989. var subMeshes = new Array();
  65990. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  65991. var mesh = renderList_1[_i];
  65992. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  65993. }
  65994. if (subMeshes.length === 0) {
  65995. if (onCompiled) {
  65996. onCompiled(this);
  65997. }
  65998. return;
  65999. }
  66000. var currentIndex = 0;
  66001. var checkReady = function () {
  66002. if (!_this._scene || !_this._scene.getEngine()) {
  66003. return;
  66004. }
  66005. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66006. currentIndex++;
  66007. if (currentIndex >= subMeshes.length) {
  66008. if (onCompiled) {
  66009. onCompiled(_this);
  66010. }
  66011. return;
  66012. }
  66013. }
  66014. setTimeout(checkReady, 16);
  66015. };
  66016. checkReady();
  66017. };
  66018. /**
  66019. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66020. * @param options Sets of optional options forcing the compilation with different modes
  66021. * @returns A promise that resolves when the compilation completes
  66022. */
  66023. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66024. var _this = this;
  66025. return new Promise(function (resolve) {
  66026. _this.forceCompilation(function () {
  66027. resolve();
  66028. }, options);
  66029. });
  66030. };
  66031. /**
  66032. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66033. * @param subMesh The submesh we want to render in the shadow map
  66034. * @param useInstances Defines wether will draw in the map using instances
  66035. * @returns true if ready otherwise, false
  66036. */
  66037. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66038. var defines = [];
  66039. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66040. defines.push("#define FLOAT");
  66041. }
  66042. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66043. defines.push("#define ESM");
  66044. }
  66045. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66046. defines.push("#define DEPTHTEXTURE");
  66047. }
  66048. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66049. var mesh = subMesh.getMesh();
  66050. var material = subMesh.getMaterial();
  66051. // Normal bias.
  66052. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66053. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66054. defines.push("#define NORMAL");
  66055. if (mesh.nonUniformScaling) {
  66056. defines.push("#define NONUNIFORMSCALING");
  66057. }
  66058. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66059. defines.push("#define DIRECTIONINLIGHTDATA");
  66060. }
  66061. }
  66062. // Alpha test
  66063. if (material && material.needAlphaTesting()) {
  66064. var alphaTexture = material.getAlphaTestTexture();
  66065. if (alphaTexture) {
  66066. defines.push("#define ALPHATEST");
  66067. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66068. attribs.push(BABYLON.VertexBuffer.UVKind);
  66069. defines.push("#define UV1");
  66070. }
  66071. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66072. if (alphaTexture.coordinatesIndex === 1) {
  66073. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66074. defines.push("#define UV2");
  66075. }
  66076. }
  66077. }
  66078. }
  66079. // Bones
  66080. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66081. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66082. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66083. if (mesh.numBoneInfluencers > 4) {
  66084. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66085. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66086. }
  66087. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66088. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66089. }
  66090. else {
  66091. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66092. }
  66093. // Morph targets
  66094. var manager = mesh.morphTargetManager;
  66095. var morphInfluencers = 0;
  66096. if (manager) {
  66097. if (manager.numInfluencers > 0) {
  66098. defines.push("#define MORPHTARGETS");
  66099. morphInfluencers = manager.numInfluencers;
  66100. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66101. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66102. }
  66103. }
  66104. // Instances
  66105. if (useInstances) {
  66106. defines.push("#define INSTANCES");
  66107. attribs.push("world0");
  66108. attribs.push("world1");
  66109. attribs.push("world2");
  66110. attribs.push("world3");
  66111. }
  66112. // Get correct effect
  66113. var join = defines.join("\n");
  66114. if (this._cachedDefines !== join) {
  66115. this._cachedDefines = join;
  66116. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66117. }
  66118. if (!this._effect.isReady()) {
  66119. return false;
  66120. }
  66121. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66122. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66123. this._initializeBlurRTTAndPostProcesses();
  66124. }
  66125. }
  66126. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66127. return false;
  66128. }
  66129. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66130. return false;
  66131. }
  66132. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66133. return false;
  66134. }
  66135. return true;
  66136. };
  66137. /**
  66138. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66139. * @param defines Defines of the material we want to update
  66140. * @param lightIndex Index of the light in the enabled light list of the material
  66141. */
  66142. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66143. var scene = this._scene;
  66144. var light = this._light;
  66145. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66146. return;
  66147. }
  66148. defines["SHADOW" + lightIndex] = true;
  66149. if (this.useContactHardeningShadow) {
  66150. defines["SHADOWPCSS" + lightIndex] = true;
  66151. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66152. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66153. }
  66154. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66155. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66156. }
  66157. // else default to high.
  66158. }
  66159. if (this.usePercentageCloserFiltering) {
  66160. defines["SHADOWPCF" + lightIndex] = true;
  66161. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66162. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66163. }
  66164. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66165. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66166. }
  66167. // else default to high.
  66168. }
  66169. else if (this.usePoissonSampling) {
  66170. defines["SHADOWPOISSON" + lightIndex] = true;
  66171. }
  66172. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66173. defines["SHADOWESM" + lightIndex] = true;
  66174. }
  66175. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66176. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66177. }
  66178. if (light.needCube()) {
  66179. defines["SHADOWCUBE" + lightIndex] = true;
  66180. }
  66181. };
  66182. /**
  66183. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66184. * defined in the generator but impacting the effect).
  66185. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66186. * @param effect The effect we are binfing the information for
  66187. */
  66188. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66189. var light = this._light;
  66190. var scene = this._scene;
  66191. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66192. return;
  66193. }
  66194. var camera = scene.activeCamera;
  66195. if (!camera) {
  66196. return;
  66197. }
  66198. var shadowMap = this.getShadowMap();
  66199. if (!shadowMap) {
  66200. return;
  66201. }
  66202. if (!light.needCube()) {
  66203. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66204. }
  66205. // Only PCF uses depth stencil texture.
  66206. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66207. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66208. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66209. }
  66210. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66211. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66212. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66213. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66214. }
  66215. else {
  66216. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66217. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66218. }
  66219. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66220. };
  66221. /**
  66222. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66223. * (eq to shadow prjection matrix * light transform matrix)
  66224. * @returns The transform matrix used to create the shadow map
  66225. */
  66226. ShadowGenerator.prototype.getTransformMatrix = function () {
  66227. var scene = this._scene;
  66228. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66229. return this._transformMatrix;
  66230. }
  66231. this._currentRenderID = scene.getRenderId();
  66232. this._currentFaceIndexCache = this._currentFaceIndex;
  66233. var lightPosition = this._light.position;
  66234. if (this._light.computeTransformedInformation()) {
  66235. lightPosition = this._light.transformedPosition;
  66236. }
  66237. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66238. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66239. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66240. }
  66241. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66242. this._cachedPosition.copyFrom(lightPosition);
  66243. this._cachedDirection.copyFrom(this._lightDirection);
  66244. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66245. var shadowMap = this.getShadowMap();
  66246. if (shadowMap) {
  66247. var renderList = shadowMap.renderList;
  66248. if (renderList) {
  66249. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66250. }
  66251. }
  66252. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66253. }
  66254. return this._transformMatrix;
  66255. };
  66256. /**
  66257. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66258. * Cube and 2D textures for instance.
  66259. */
  66260. ShadowGenerator.prototype.recreateShadowMap = function () {
  66261. var shadowMap = this._shadowMap;
  66262. if (!shadowMap) {
  66263. return;
  66264. }
  66265. // Track render list.
  66266. var renderList = shadowMap.renderList;
  66267. // Clean up existing data.
  66268. this._disposeRTTandPostProcesses();
  66269. // Reinitializes.
  66270. this._initializeGenerator();
  66271. // Reaffect the filter to ensure a correct fallback if necessary.
  66272. this.filter = this.filter;
  66273. // Reaffect the filter.
  66274. this._applyFilterValues();
  66275. // Reaffect Render List.
  66276. this._shadowMap.renderList = renderList;
  66277. };
  66278. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66279. if (this._shadowMap2) {
  66280. this._shadowMap2.dispose();
  66281. this._shadowMap2 = null;
  66282. }
  66283. if (this._boxBlurPostprocess) {
  66284. this._boxBlurPostprocess.dispose();
  66285. this._boxBlurPostprocess = null;
  66286. }
  66287. if (this._kernelBlurXPostprocess) {
  66288. this._kernelBlurXPostprocess.dispose();
  66289. this._kernelBlurXPostprocess = null;
  66290. }
  66291. if (this._kernelBlurYPostprocess) {
  66292. this._kernelBlurYPostprocess.dispose();
  66293. this._kernelBlurYPostprocess = null;
  66294. }
  66295. this._blurPostProcesses = [];
  66296. };
  66297. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66298. if (this._shadowMap) {
  66299. this._shadowMap.dispose();
  66300. this._shadowMap = null;
  66301. }
  66302. this._disposeBlurPostProcesses();
  66303. };
  66304. /**
  66305. * Disposes the ShadowGenerator.
  66306. * Returns nothing.
  66307. */
  66308. ShadowGenerator.prototype.dispose = function () {
  66309. this._disposeRTTandPostProcesses();
  66310. if (this._light) {
  66311. this._light._shadowGenerator = null;
  66312. this._light._markMeshesAsLightDirty();
  66313. }
  66314. };
  66315. /**
  66316. * Serializes the shadow generator setup to a json object.
  66317. * @returns The serialized JSON object
  66318. */
  66319. ShadowGenerator.prototype.serialize = function () {
  66320. var serializationObject = {};
  66321. var shadowMap = this.getShadowMap();
  66322. if (!shadowMap) {
  66323. return serializationObject;
  66324. }
  66325. serializationObject.lightId = this._light.id;
  66326. serializationObject.mapSize = shadowMap.getRenderSize();
  66327. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66328. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66329. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66330. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66331. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66332. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66333. serializationObject.depthScale = this.depthScale;
  66334. serializationObject.darkness = this.getDarkness();
  66335. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66336. serializationObject.blurKernel = this.blurKernel;
  66337. serializationObject.blurScale = this.blurScale;
  66338. serializationObject.useKernelBlur = this.useKernelBlur;
  66339. serializationObject.transparencyShadow = this._transparencyShadow;
  66340. serializationObject.bias = this.bias;
  66341. serializationObject.normalBias = this.normalBias;
  66342. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66343. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66344. serializationObject.filteringQuality = this.filteringQuality;
  66345. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66346. serializationObject.renderList = [];
  66347. if (shadowMap.renderList) {
  66348. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66349. var mesh = shadowMap.renderList[meshIndex];
  66350. serializationObject.renderList.push(mesh.id);
  66351. }
  66352. }
  66353. return serializationObject;
  66354. };
  66355. /**
  66356. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66357. * @param parsedShadowGenerator The JSON object to parse
  66358. * @param scene The scene to create the shadow map for
  66359. * @returns The parsed shadow generator
  66360. */
  66361. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66362. //casting to point light, as light is missing the position attr and typescript complains.
  66363. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66364. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66365. var shadowMap = shadowGenerator.getShadowMap();
  66366. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66367. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66368. meshes.forEach(function (mesh) {
  66369. if (!shadowMap) {
  66370. return;
  66371. }
  66372. if (!shadowMap.renderList) {
  66373. shadowMap.renderList = [];
  66374. }
  66375. shadowMap.renderList.push(mesh);
  66376. });
  66377. }
  66378. if (parsedShadowGenerator.usePoissonSampling) {
  66379. shadowGenerator.usePoissonSampling = true;
  66380. }
  66381. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66382. shadowGenerator.useExponentialShadowMap = true;
  66383. }
  66384. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66385. shadowGenerator.useBlurExponentialShadowMap = true;
  66386. }
  66387. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66388. shadowGenerator.useCloseExponentialShadowMap = true;
  66389. }
  66390. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66391. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66392. }
  66393. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66394. shadowGenerator.usePercentageCloserFiltering = true;
  66395. }
  66396. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66397. shadowGenerator.useContactHardeningShadow = true;
  66398. }
  66399. if (parsedShadowGenerator.filteringQuality) {
  66400. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66401. }
  66402. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66403. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66404. }
  66405. // Backward compat
  66406. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66407. shadowGenerator.useExponentialShadowMap = true;
  66408. }
  66409. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66410. shadowGenerator.useBlurExponentialShadowMap = true;
  66411. }
  66412. if (parsedShadowGenerator.depthScale) {
  66413. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66414. }
  66415. if (parsedShadowGenerator.blurScale) {
  66416. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66417. }
  66418. if (parsedShadowGenerator.blurBoxOffset) {
  66419. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66420. }
  66421. if (parsedShadowGenerator.useKernelBlur) {
  66422. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66423. }
  66424. if (parsedShadowGenerator.blurKernel) {
  66425. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66426. }
  66427. if (parsedShadowGenerator.bias !== undefined) {
  66428. shadowGenerator.bias = parsedShadowGenerator.bias;
  66429. }
  66430. if (parsedShadowGenerator.normalBias !== undefined) {
  66431. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66432. }
  66433. if (parsedShadowGenerator.darkness) {
  66434. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66435. }
  66436. if (parsedShadowGenerator.transparencyShadow) {
  66437. shadowGenerator.setTransparencyShadow(true);
  66438. }
  66439. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66440. return shadowGenerator;
  66441. };
  66442. /**
  66443. * Shadow generator mode None: no filtering applied.
  66444. */
  66445. ShadowGenerator.FILTER_NONE = 0;
  66446. /**
  66447. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66448. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66449. */
  66450. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66451. /**
  66452. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66453. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66454. */
  66455. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66456. /**
  66457. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66458. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66459. */
  66460. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66461. /**
  66462. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66463. * edge artifacts on steep falloff.
  66464. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66465. */
  66466. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66467. /**
  66468. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66469. * edge artifacts on steep falloff.
  66470. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66471. */
  66472. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66473. /**
  66474. * Shadow generator mode PCF: Percentage Closer Filtering
  66475. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66476. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66477. */
  66478. ShadowGenerator.FILTER_PCF = 6;
  66479. /**
  66480. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66481. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66482. * Contact Hardening
  66483. */
  66484. ShadowGenerator.FILTER_PCSS = 7;
  66485. /**
  66486. * Reserved for PCF and PCSS
  66487. * Highest Quality.
  66488. *
  66489. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66490. *
  66491. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66492. */
  66493. ShadowGenerator.QUALITY_HIGH = 0;
  66494. /**
  66495. * Reserved for PCF and PCSS
  66496. * Good tradeoff for quality/perf cross devices
  66497. *
  66498. * Execute PCF on a 3*3 kernel.
  66499. *
  66500. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66501. */
  66502. ShadowGenerator.QUALITY_MEDIUM = 1;
  66503. /**
  66504. * Reserved for PCF and PCSS
  66505. * The lowest quality but the fastest.
  66506. *
  66507. * Execute PCF on a 1*1 kernel.
  66508. *
  66509. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66510. */
  66511. ShadowGenerator.QUALITY_LOW = 2;
  66512. return ShadowGenerator;
  66513. }());
  66514. BABYLON.ShadowGenerator = ShadowGenerator;
  66515. })(BABYLON || (BABYLON = {}));
  66516. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66517. var BABYLON;
  66518. (function (BABYLON) {
  66519. var DefaultLoadingScreen = /** @class */ (function () {
  66520. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66521. if (_loadingText === void 0) { _loadingText = ""; }
  66522. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66523. var _this = this;
  66524. this._renderingCanvas = _renderingCanvas;
  66525. this._loadingText = _loadingText;
  66526. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66527. // Resize
  66528. this._resizeLoadingUI = function () {
  66529. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66530. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66531. if (!_this._loadingDiv) {
  66532. return;
  66533. }
  66534. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66535. _this._loadingDiv.style.left = canvasRect.left + "px";
  66536. _this._loadingDiv.style.top = canvasRect.top + "px";
  66537. _this._loadingDiv.style.width = canvasRect.width + "px";
  66538. _this._loadingDiv.style.height = canvasRect.height + "px";
  66539. };
  66540. }
  66541. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66542. if (this._loadingDiv) {
  66543. // Do not add a loading screen if there is already one
  66544. return;
  66545. }
  66546. this._loadingDiv = document.createElement("div");
  66547. this._loadingDiv.id = "babylonjsLoadingDiv";
  66548. this._loadingDiv.style.opacity = "0";
  66549. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66550. this._loadingDiv.style.pointerEvents = "none";
  66551. // Loading text
  66552. this._loadingTextDiv = document.createElement("div");
  66553. this._loadingTextDiv.style.position = "absolute";
  66554. this._loadingTextDiv.style.left = "0";
  66555. this._loadingTextDiv.style.top = "50%";
  66556. this._loadingTextDiv.style.marginTop = "80px";
  66557. this._loadingTextDiv.style.width = "100%";
  66558. this._loadingTextDiv.style.height = "20px";
  66559. this._loadingTextDiv.style.fontFamily = "Arial";
  66560. this._loadingTextDiv.style.fontSize = "14px";
  66561. this._loadingTextDiv.style.color = "white";
  66562. this._loadingTextDiv.style.textAlign = "center";
  66563. this._loadingTextDiv.innerHTML = "Loading";
  66564. this._loadingDiv.appendChild(this._loadingTextDiv);
  66565. //set the predefined text
  66566. this._loadingTextDiv.innerHTML = this._loadingText;
  66567. // Generating keyframes
  66568. var style = document.createElement('style');
  66569. style.type = 'text/css';
  66570. 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 }";
  66571. style.innerHTML = keyFrames;
  66572. document.getElementsByTagName('head')[0].appendChild(style);
  66573. // Loading img
  66574. var imgBack = new Image();
  66575. 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";
  66576. imgBack.style.position = "absolute";
  66577. imgBack.style.left = "50%";
  66578. imgBack.style.top = "50%";
  66579. imgBack.style.marginLeft = "-60px";
  66580. imgBack.style.marginTop = "-60px";
  66581. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66582. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66583. imgBack.style.transformOrigin = "50% 50%";
  66584. imgBack.style.webkitTransformOrigin = "50% 50%";
  66585. this._loadingDiv.appendChild(imgBack);
  66586. this._resizeLoadingUI();
  66587. window.addEventListener("resize", this._resizeLoadingUI);
  66588. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66589. document.body.appendChild(this._loadingDiv);
  66590. this._loadingDiv.style.opacity = "1";
  66591. };
  66592. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66593. var _this = this;
  66594. if (!this._loadingDiv) {
  66595. return;
  66596. }
  66597. var onTransitionEnd = function () {
  66598. if (!_this._loadingDiv) {
  66599. return;
  66600. }
  66601. document.body.removeChild(_this._loadingDiv);
  66602. window.removeEventListener("resize", _this._resizeLoadingUI);
  66603. _this._loadingDiv = null;
  66604. };
  66605. this._loadingDiv.style.opacity = "0";
  66606. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66607. };
  66608. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66609. set: function (text) {
  66610. this._loadingText = text;
  66611. if (this._loadingTextDiv) {
  66612. this._loadingTextDiv.innerHTML = this._loadingText;
  66613. }
  66614. },
  66615. enumerable: true,
  66616. configurable: true
  66617. });
  66618. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66619. get: function () {
  66620. return this._loadingDivBackgroundColor;
  66621. },
  66622. set: function (color) {
  66623. this._loadingDivBackgroundColor = color;
  66624. if (!this._loadingDiv) {
  66625. return;
  66626. }
  66627. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66628. },
  66629. enumerable: true,
  66630. configurable: true
  66631. });
  66632. return DefaultLoadingScreen;
  66633. }());
  66634. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66635. })(BABYLON || (BABYLON = {}));
  66636. //# sourceMappingURL=babylon.loadingScreen.js.map
  66637. var BABYLON;
  66638. (function (BABYLON) {
  66639. var SceneLoaderProgressEvent = /** @class */ (function () {
  66640. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66641. this.lengthComputable = lengthComputable;
  66642. this.loaded = loaded;
  66643. this.total = total;
  66644. }
  66645. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66646. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66647. };
  66648. return SceneLoaderProgressEvent;
  66649. }());
  66650. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66651. var SceneLoader = /** @class */ (function () {
  66652. function SceneLoader() {
  66653. }
  66654. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66655. get: function () {
  66656. return 0;
  66657. },
  66658. enumerable: true,
  66659. configurable: true
  66660. });
  66661. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66662. get: function () {
  66663. return 1;
  66664. },
  66665. enumerable: true,
  66666. configurable: true
  66667. });
  66668. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66669. get: function () {
  66670. return 2;
  66671. },
  66672. enumerable: true,
  66673. configurable: true
  66674. });
  66675. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66676. get: function () {
  66677. return 3;
  66678. },
  66679. enumerable: true,
  66680. configurable: true
  66681. });
  66682. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66683. get: function () {
  66684. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66685. },
  66686. set: function (value) {
  66687. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66688. },
  66689. enumerable: true,
  66690. configurable: true
  66691. });
  66692. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66693. get: function () {
  66694. return SceneLoader._ShowLoadingScreen;
  66695. },
  66696. set: function (value) {
  66697. SceneLoader._ShowLoadingScreen = value;
  66698. },
  66699. enumerable: true,
  66700. configurable: true
  66701. });
  66702. Object.defineProperty(SceneLoader, "loggingLevel", {
  66703. get: function () {
  66704. return SceneLoader._loggingLevel;
  66705. },
  66706. set: function (value) {
  66707. SceneLoader._loggingLevel = value;
  66708. },
  66709. enumerable: true,
  66710. configurable: true
  66711. });
  66712. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66713. get: function () {
  66714. return SceneLoader._CleanBoneMatrixWeights;
  66715. },
  66716. set: function (value) {
  66717. SceneLoader._CleanBoneMatrixWeights = value;
  66718. },
  66719. enumerable: true,
  66720. configurable: true
  66721. });
  66722. SceneLoader._getDefaultPlugin = function () {
  66723. return SceneLoader._registeredPlugins[".babylon"];
  66724. };
  66725. SceneLoader._getPluginForExtension = function (extension) {
  66726. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66727. if (registeredPlugin) {
  66728. return registeredPlugin;
  66729. }
  66730. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  66731. return SceneLoader._getDefaultPlugin();
  66732. };
  66733. SceneLoader._getPluginForDirectLoad = function (data) {
  66734. for (var extension in SceneLoader._registeredPlugins) {
  66735. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66736. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66737. return SceneLoader._registeredPlugins[extension];
  66738. }
  66739. }
  66740. return SceneLoader._getDefaultPlugin();
  66741. };
  66742. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66743. if (sceneFilename.name) {
  66744. sceneFilename = sceneFilename.name;
  66745. }
  66746. var queryStringPosition = sceneFilename.indexOf("?");
  66747. if (queryStringPosition !== -1) {
  66748. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66749. }
  66750. var dotPosition = sceneFilename.lastIndexOf(".");
  66751. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66752. return SceneLoader._getPluginForExtension(extension);
  66753. };
  66754. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66755. SceneLoader._getDirectLoad = function (sceneFilename) {
  66756. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66757. return sceneFilename.substr(5);
  66758. }
  66759. return null;
  66760. };
  66761. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66762. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66763. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66764. var plugin;
  66765. if (registeredPlugin.plugin.createPlugin) {
  66766. plugin = registeredPlugin.plugin.createPlugin();
  66767. }
  66768. else {
  66769. plugin = registeredPlugin.plugin;
  66770. }
  66771. var useArrayBuffer = registeredPlugin.isBinary;
  66772. var database;
  66773. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66774. var dataCallback = function (data, responseURL) {
  66775. if (scene.isDisposed) {
  66776. onError("Scene has been disposed");
  66777. return;
  66778. }
  66779. scene.database = database;
  66780. onSuccess(plugin, data, responseURL);
  66781. };
  66782. var request = null;
  66783. var pluginDisposed = false;
  66784. var onDisposeObservable = plugin.onDisposeObservable;
  66785. if (onDisposeObservable) {
  66786. onDisposeObservable.add(function () {
  66787. pluginDisposed = true;
  66788. if (request) {
  66789. request.abort();
  66790. request = null;
  66791. }
  66792. onDispose();
  66793. });
  66794. }
  66795. var manifestChecked = function () {
  66796. if (pluginDisposed) {
  66797. return;
  66798. }
  66799. var url = rootUrl + sceneFilename;
  66800. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66801. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66802. } : undefined, database, useArrayBuffer, function (request, exception) {
  66803. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66804. });
  66805. };
  66806. if (directLoad) {
  66807. dataCallback(directLoad);
  66808. return plugin;
  66809. }
  66810. if (rootUrl.indexOf("file:") === -1) {
  66811. var engine = scene.getEngine();
  66812. var canUseOfflineSupport = engine.enableOfflineSupport;
  66813. if (canUseOfflineSupport) {
  66814. // Also check for exceptions
  66815. var exceptionFound = false;
  66816. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66817. var regex = _a[_i];
  66818. if (regex.test(rootUrl + sceneFilename)) {
  66819. exceptionFound = true;
  66820. break;
  66821. }
  66822. }
  66823. canUseOfflineSupport = !exceptionFound;
  66824. }
  66825. if (canUseOfflineSupport) {
  66826. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66827. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  66828. }
  66829. else {
  66830. manifestChecked();
  66831. }
  66832. }
  66833. // Loading file from disk via input file or drag'n'drop
  66834. else {
  66835. var fileOrString = sceneFilename;
  66836. if (fileOrString.name) { // File
  66837. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66838. }
  66839. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  66840. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  66841. }
  66842. else {
  66843. onError("Unable to find file named " + sceneFilename);
  66844. }
  66845. }
  66846. return plugin;
  66847. };
  66848. // Public functions
  66849. SceneLoader.GetPluginForExtension = function (extension) {
  66850. return SceneLoader._getPluginForExtension(extension).plugin;
  66851. };
  66852. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  66853. return !!SceneLoader._registeredPlugins[extension];
  66854. };
  66855. SceneLoader.RegisterPlugin = function (plugin) {
  66856. if (typeof plugin.extensions === "string") {
  66857. var extension = plugin.extensions;
  66858. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66859. plugin: plugin,
  66860. isBinary: false
  66861. };
  66862. }
  66863. else {
  66864. var extensions = plugin.extensions;
  66865. Object.keys(extensions).forEach(function (extension) {
  66866. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66867. plugin: plugin,
  66868. isBinary: extensions[extension].isBinary
  66869. };
  66870. });
  66871. }
  66872. };
  66873. /**
  66874. * Import meshes into a scene
  66875. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66876. * @param rootUrl a string that defines the root url for scene and resources
  66877. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66878. * @param scene the instance of BABYLON.Scene to append to
  66879. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  66880. * @param onProgress a callback with a progress event for each file being loaded
  66881. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66882. * @param pluginExtension the extension used to determine the plugin
  66883. * @returns The loaded plugin
  66884. */
  66885. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  66886. if (onSuccess === void 0) { onSuccess = null; }
  66887. if (onProgress === void 0) { onProgress = null; }
  66888. if (onError === void 0) { onError = null; }
  66889. if (pluginExtension === void 0) { pluginExtension = null; }
  66890. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  66891. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  66892. return null;
  66893. }
  66894. var loadingToken = {};
  66895. scene._addPendingData(loadingToken);
  66896. var disposeHandler = function () {
  66897. scene._removePendingData(loadingToken);
  66898. };
  66899. var errorHandler = function (message, exception) {
  66900. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  66901. if (onError) {
  66902. onError(scene, errorMessage, exception);
  66903. }
  66904. else {
  66905. BABYLON.Tools.Error(errorMessage);
  66906. // should the exception be thrown?
  66907. }
  66908. disposeHandler();
  66909. };
  66910. var progressHandler = onProgress ? function (event) {
  66911. try {
  66912. onProgress(event);
  66913. }
  66914. catch (e) {
  66915. errorHandler("Error in onProgress callback", e);
  66916. }
  66917. } : undefined;
  66918. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  66919. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  66920. if (onSuccess) {
  66921. try {
  66922. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  66923. }
  66924. catch (e) {
  66925. errorHandler("Error in onSuccess callback", e);
  66926. }
  66927. }
  66928. scene._removePendingData(loadingToken);
  66929. };
  66930. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  66931. if (plugin.rewriteRootURL) {
  66932. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  66933. }
  66934. if (sceneFilename === "") {
  66935. if (sceneFilename === "") {
  66936. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  66937. }
  66938. }
  66939. if (plugin.importMesh) {
  66940. var syncedPlugin = plugin;
  66941. var meshes = new Array();
  66942. var particleSystems = new Array();
  66943. var skeletons = new Array();
  66944. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  66945. return;
  66946. }
  66947. scene.loadingPluginName = plugin.name;
  66948. successHandler(meshes, particleSystems, skeletons, []);
  66949. }
  66950. else {
  66951. var asyncedPlugin = plugin;
  66952. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  66953. scene.loadingPluginName = plugin.name;
  66954. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  66955. }).catch(function (error) {
  66956. errorHandler(error.message, error);
  66957. });
  66958. }
  66959. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  66960. };
  66961. /**
  66962. * Import meshes into a scene
  66963. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  66964. * @param rootUrl a string that defines the root url for scene and resources
  66965. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66966. * @param scene the instance of BABYLON.Scene to append to
  66967. * @param onProgress a callback with a progress event for each file being loaded
  66968. * @param pluginExtension the extension used to determine the plugin
  66969. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  66970. */
  66971. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  66972. if (onProgress === void 0) { onProgress = null; }
  66973. if (pluginExtension === void 0) { pluginExtension = null; }
  66974. return new Promise(function (resolve, reject) {
  66975. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  66976. resolve({
  66977. meshes: meshes,
  66978. particleSystems: particleSystems,
  66979. skeletons: skeletons,
  66980. animationGroups: animationGroups
  66981. });
  66982. }, onProgress, function (scene, message, exception) {
  66983. reject(exception || new Error(message));
  66984. });
  66985. });
  66986. };
  66987. /**
  66988. * Load a scene
  66989. * @param rootUrl a string that defines the root url for scene and resources
  66990. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  66991. * @param engine is the instance of BABYLON.Engine to use to create the scene
  66992. * @param onSuccess a callback with the scene when import succeeds
  66993. * @param onProgress a callback with a progress event for each file being loaded
  66994. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  66995. * @param pluginExtension the extension used to determine the plugin
  66996. * @returns The loaded plugin
  66997. */
  66998. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  66999. if (onSuccess === void 0) { onSuccess = null; }
  67000. if (onProgress === void 0) { onProgress = null; }
  67001. if (onError === void 0) { onError = null; }
  67002. if (pluginExtension === void 0) { pluginExtension = null; }
  67003. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67004. };
  67005. /**
  67006. * Load a scene
  67007. * @param rootUrl a string that defines the root url for scene and resources
  67008. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67009. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67010. * @param onProgress a callback with a progress event for each file being loaded
  67011. * @param pluginExtension the extension used to determine the plugin
  67012. * @returns The loaded scene
  67013. */
  67014. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67015. if (onProgress === void 0) { onProgress = null; }
  67016. if (pluginExtension === void 0) { pluginExtension = null; }
  67017. return new Promise(function (resolve, reject) {
  67018. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67019. resolve(scene);
  67020. }, onProgress, function (scene, message, exception) {
  67021. reject(exception || new Error(message));
  67022. }, pluginExtension);
  67023. });
  67024. };
  67025. /**
  67026. * Append a scene
  67027. * @param rootUrl a string that defines the root url for scene and resources
  67028. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67029. * @param scene is the instance of BABYLON.Scene to append to
  67030. * @param onSuccess a callback with the scene when import succeeds
  67031. * @param onProgress a callback with a progress event for each file being loaded
  67032. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67033. * @param pluginExtension the extension used to determine the plugin
  67034. * @returns The loaded plugin
  67035. */
  67036. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67037. if (onSuccess === void 0) { onSuccess = null; }
  67038. if (onProgress === void 0) { onProgress = null; }
  67039. if (onError === void 0) { onError = null; }
  67040. if (pluginExtension === void 0) { pluginExtension = null; }
  67041. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67042. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67043. return null;
  67044. }
  67045. if (SceneLoader.ShowLoadingScreen) {
  67046. scene.getEngine().displayLoadingUI();
  67047. }
  67048. var loadingToken = {};
  67049. scene._addPendingData(loadingToken);
  67050. var disposeHandler = function () {
  67051. scene._removePendingData(loadingToken);
  67052. scene.getEngine().hideLoadingUI();
  67053. };
  67054. var errorHandler = function (message, exception) {
  67055. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67056. if (onError) {
  67057. onError(scene, errorMessage, exception);
  67058. }
  67059. else {
  67060. BABYLON.Tools.Error(errorMessage);
  67061. // should the exception be thrown?
  67062. }
  67063. disposeHandler();
  67064. };
  67065. var progressHandler = onProgress ? function (event) {
  67066. try {
  67067. onProgress(event);
  67068. }
  67069. catch (e) {
  67070. errorHandler("Error in onProgress callback", e);
  67071. }
  67072. } : undefined;
  67073. var successHandler = function () {
  67074. if (onSuccess) {
  67075. try {
  67076. onSuccess(scene);
  67077. }
  67078. catch (e) {
  67079. errorHandler("Error in onSuccess callback", e);
  67080. }
  67081. }
  67082. scene._removePendingData(loadingToken);
  67083. };
  67084. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67085. if (sceneFilename === "") {
  67086. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67087. }
  67088. if (plugin.load) {
  67089. var syncedPlugin = plugin;
  67090. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67091. return;
  67092. }
  67093. scene.loadingPluginName = plugin.name;
  67094. successHandler();
  67095. }
  67096. else {
  67097. var asyncedPlugin = plugin;
  67098. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67099. scene.loadingPluginName = plugin.name;
  67100. successHandler();
  67101. }).catch(function (error) {
  67102. errorHandler(error.message, error);
  67103. });
  67104. }
  67105. if (SceneLoader.ShowLoadingScreen) {
  67106. scene.executeWhenReady(function () {
  67107. scene.getEngine().hideLoadingUI();
  67108. });
  67109. }
  67110. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67111. };
  67112. /**
  67113. * Append a scene
  67114. * @param rootUrl a string that defines the root url for scene and resources
  67115. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67116. * @param scene is the instance of BABYLON.Scene to append to
  67117. * @param onProgress a callback with a progress event for each file being loaded
  67118. * @param pluginExtension the extension used to determine the plugin
  67119. * @returns The given scene
  67120. */
  67121. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67122. if (onProgress === void 0) { onProgress = null; }
  67123. if (pluginExtension === void 0) { pluginExtension = null; }
  67124. return new Promise(function (resolve, reject) {
  67125. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67126. resolve(scene);
  67127. }, onProgress, function (scene, message, exception) {
  67128. reject(exception || new Error(message));
  67129. }, pluginExtension);
  67130. });
  67131. };
  67132. /**
  67133. * Load a scene into an asset container
  67134. * @param rootUrl a string that defines the root url for scene and resources
  67135. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67136. * @param scene is the instance of BABYLON.Scene to append to
  67137. * @param onSuccess a callback with the scene when import succeeds
  67138. * @param onProgress a callback with a progress event for each file being loaded
  67139. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67140. * @param pluginExtension the extension used to determine the plugin
  67141. * @returns The loaded plugin
  67142. */
  67143. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67144. if (onSuccess === void 0) { onSuccess = null; }
  67145. if (onProgress === void 0) { onProgress = null; }
  67146. if (onError === void 0) { onError = null; }
  67147. if (pluginExtension === void 0) { pluginExtension = null; }
  67148. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67149. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67150. return null;
  67151. }
  67152. var loadingToken = {};
  67153. scene._addPendingData(loadingToken);
  67154. var disposeHandler = function () {
  67155. scene._removePendingData(loadingToken);
  67156. };
  67157. var errorHandler = function (message, exception) {
  67158. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67159. if (onError) {
  67160. onError(scene, errorMessage, exception);
  67161. }
  67162. else {
  67163. BABYLON.Tools.Error(errorMessage);
  67164. // should the exception be thrown?
  67165. }
  67166. disposeHandler();
  67167. };
  67168. var progressHandler = onProgress ? function (event) {
  67169. try {
  67170. onProgress(event);
  67171. }
  67172. catch (e) {
  67173. errorHandler("Error in onProgress callback", e);
  67174. }
  67175. } : undefined;
  67176. var successHandler = function (assets) {
  67177. if (onSuccess) {
  67178. try {
  67179. onSuccess(assets);
  67180. }
  67181. catch (e) {
  67182. errorHandler("Error in onSuccess callback", e);
  67183. }
  67184. }
  67185. scene._removePendingData(loadingToken);
  67186. };
  67187. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67188. if (plugin.loadAssetContainer) {
  67189. var syncedPlugin = plugin;
  67190. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67191. if (!assetContainer) {
  67192. return;
  67193. }
  67194. scene.loadingPluginName = plugin.name;
  67195. successHandler(assetContainer);
  67196. }
  67197. else if (plugin.loadAssetContainerAsync) {
  67198. var asyncedPlugin = plugin;
  67199. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67200. scene.loadingPluginName = plugin.name;
  67201. successHandler(assetContainer);
  67202. }).catch(function (error) {
  67203. errorHandler(error.message, error);
  67204. });
  67205. }
  67206. else {
  67207. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67208. }
  67209. if (SceneLoader.ShowLoadingScreen) {
  67210. scene.executeWhenReady(function () {
  67211. scene.getEngine().hideLoadingUI();
  67212. });
  67213. }
  67214. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67215. };
  67216. /**
  67217. * Load a scene into an asset container
  67218. * @param rootUrl a string that defines the root url for scene and resources
  67219. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67220. * @param scene is the instance of BABYLON.Scene to append to
  67221. * @param onProgress a callback with a progress event for each file being loaded
  67222. * @param pluginExtension the extension used to determine the plugin
  67223. * @returns The loaded asset container
  67224. */
  67225. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67226. if (onProgress === void 0) { onProgress = null; }
  67227. if (pluginExtension === void 0) { pluginExtension = null; }
  67228. return new Promise(function (resolve, reject) {
  67229. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67230. resolve(assetContainer);
  67231. }, onProgress, function (scene, message, exception) {
  67232. reject(exception || new Error(message));
  67233. }, pluginExtension);
  67234. });
  67235. };
  67236. // Flags
  67237. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67238. SceneLoader._ShowLoadingScreen = true;
  67239. SceneLoader._CleanBoneMatrixWeights = false;
  67240. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67241. // Members
  67242. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67243. SceneLoader._registeredPlugins = {};
  67244. return SceneLoader;
  67245. }());
  67246. BABYLON.SceneLoader = SceneLoader;
  67247. ;
  67248. })(BABYLON || (BABYLON = {}));
  67249. //# sourceMappingURL=babylon.sceneLoader.js.map
  67250. var BABYLON;
  67251. (function (BABYLON) {
  67252. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67253. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67254. var parsedMaterial = parsedData.materials[index];
  67255. if (parsedMaterial.id === id) {
  67256. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67257. }
  67258. }
  67259. return null;
  67260. };
  67261. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67262. for (var i in names) {
  67263. if (mesh.name === names[i]) {
  67264. hierarchyIds.push(mesh.id);
  67265. return true;
  67266. }
  67267. }
  67268. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67269. hierarchyIds.push(mesh.id);
  67270. return true;
  67271. }
  67272. return false;
  67273. };
  67274. var logOperation = function (operation, producer) {
  67275. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67276. };
  67277. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67278. if (addToScene === void 0) { addToScene = false; }
  67279. var container = new BABYLON.AssetContainer(scene);
  67280. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67281. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67282. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67283. // and avoid problems with multiple concurrent .babylon loads.
  67284. var log = "importScene has failed JSON parse";
  67285. try {
  67286. var parsedData = JSON.parse(data);
  67287. log = "";
  67288. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67289. var index;
  67290. var cache;
  67291. // Lights
  67292. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67293. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67294. var parsedLight = parsedData.lights[index];
  67295. var light = BABYLON.Light.Parse(parsedLight, scene);
  67296. if (light) {
  67297. container.lights.push(light);
  67298. log += (index === 0 ? "\n\tLights:" : "");
  67299. log += "\n\t\t" + light.toString(fullDetails);
  67300. }
  67301. }
  67302. }
  67303. // Animations
  67304. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67305. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67306. var parsedAnimation = parsedData.animations[index];
  67307. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67308. scene.animations.push(animation);
  67309. container.animations.push(animation);
  67310. log += (index === 0 ? "\n\tAnimations:" : "");
  67311. log += "\n\t\t" + animation.toString(fullDetails);
  67312. }
  67313. }
  67314. // Materials
  67315. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67316. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67317. var parsedMaterial = parsedData.materials[index];
  67318. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67319. container.materials.push(mat);
  67320. log += (index === 0 ? "\n\tMaterials:" : "");
  67321. log += "\n\t\t" + mat.toString(fullDetails);
  67322. }
  67323. }
  67324. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67325. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67326. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67327. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67328. container.multiMaterials.push(mmat);
  67329. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67330. log += "\n\t\t" + mmat.toString(fullDetails);
  67331. }
  67332. }
  67333. // Morph targets
  67334. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67335. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67336. var managerData = _a[_i];
  67337. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67338. }
  67339. }
  67340. // Skeletons
  67341. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67342. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67343. var parsedSkeleton = parsedData.skeletons[index];
  67344. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67345. container.skeletons.push(skeleton);
  67346. log += (index === 0 ? "\n\tSkeletons:" : "");
  67347. log += "\n\t\t" + skeleton.toString(fullDetails);
  67348. }
  67349. }
  67350. // Geometries
  67351. var geometries = parsedData.geometries;
  67352. if (geometries !== undefined && geometries !== null) {
  67353. var addedGeometry = new Array();
  67354. // Boxes
  67355. var boxes = geometries.boxes;
  67356. if (boxes !== undefined && boxes !== null) {
  67357. for (index = 0, cache = boxes.length; index < cache; index++) {
  67358. var parsedBox = boxes[index];
  67359. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67360. }
  67361. }
  67362. // Spheres
  67363. var spheres = geometries.spheres;
  67364. if (spheres !== undefined && spheres !== null) {
  67365. for (index = 0, cache = spheres.length; index < cache; index++) {
  67366. var parsedSphere = spheres[index];
  67367. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67368. }
  67369. }
  67370. // Cylinders
  67371. var cylinders = geometries.cylinders;
  67372. if (cylinders !== undefined && cylinders !== null) {
  67373. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67374. var parsedCylinder = cylinders[index];
  67375. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67376. }
  67377. }
  67378. // Toruses
  67379. var toruses = geometries.toruses;
  67380. if (toruses !== undefined && toruses !== null) {
  67381. for (index = 0, cache = toruses.length; index < cache; index++) {
  67382. var parsedTorus = toruses[index];
  67383. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67384. }
  67385. }
  67386. // Grounds
  67387. var grounds = geometries.grounds;
  67388. if (grounds !== undefined && grounds !== null) {
  67389. for (index = 0, cache = grounds.length; index < cache; index++) {
  67390. var parsedGround = grounds[index];
  67391. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67392. }
  67393. }
  67394. // Planes
  67395. var planes = geometries.planes;
  67396. if (planes !== undefined && planes !== null) {
  67397. for (index = 0, cache = planes.length; index < cache; index++) {
  67398. var parsedPlane = planes[index];
  67399. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67400. }
  67401. }
  67402. // TorusKnots
  67403. var torusKnots = geometries.torusKnots;
  67404. if (torusKnots !== undefined && torusKnots !== null) {
  67405. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67406. var parsedTorusKnot = torusKnots[index];
  67407. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67408. }
  67409. }
  67410. // VertexData
  67411. var vertexData = geometries.vertexData;
  67412. if (vertexData !== undefined && vertexData !== null) {
  67413. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67414. var parsedVertexData = vertexData[index];
  67415. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67416. }
  67417. }
  67418. addedGeometry.forEach(function (g) {
  67419. if (g) {
  67420. container.geometries.push(g);
  67421. }
  67422. });
  67423. }
  67424. // Transform nodes
  67425. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67426. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67427. var parsedTransformNode = parsedData.transformNodes[index];
  67428. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67429. container.transformNodes.push(node);
  67430. }
  67431. }
  67432. // Meshes
  67433. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67434. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67435. var parsedMesh = parsedData.meshes[index];
  67436. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67437. container.meshes.push(mesh);
  67438. log += (index === 0 ? "\n\tMeshes:" : "");
  67439. log += "\n\t\t" + mesh.toString(fullDetails);
  67440. }
  67441. }
  67442. // Cameras
  67443. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67444. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67445. var parsedCamera = parsedData.cameras[index];
  67446. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67447. container.cameras.push(camera);
  67448. log += (index === 0 ? "\n\tCameras:" : "");
  67449. log += "\n\t\t" + camera.toString(fullDetails);
  67450. }
  67451. }
  67452. // Browsing all the graph to connect the dots
  67453. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67454. var camera = scene.cameras[index];
  67455. if (camera._waitingParentId) {
  67456. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67457. camera._waitingParentId = null;
  67458. }
  67459. }
  67460. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67461. var light_1 = scene.lights[index];
  67462. if (light_1 && light_1._waitingParentId) {
  67463. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67464. light_1._waitingParentId = null;
  67465. }
  67466. }
  67467. // Sounds
  67468. // TODO: add sound
  67469. var loadedSounds = [];
  67470. var loadedSound;
  67471. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67472. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67473. var parsedSound = parsedData.sounds[index];
  67474. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67475. if (!parsedSound.url)
  67476. parsedSound.url = parsedSound.name;
  67477. if (!loadedSounds[parsedSound.url]) {
  67478. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67479. loadedSounds[parsedSound.url] = loadedSound;
  67480. container.sounds.push(loadedSound);
  67481. }
  67482. else {
  67483. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67484. }
  67485. }
  67486. else {
  67487. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67488. }
  67489. }
  67490. }
  67491. loadedSounds = [];
  67492. // Connect parents & children and parse actions
  67493. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67494. var transformNode = scene.transformNodes[index];
  67495. if (transformNode._waitingParentId) {
  67496. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67497. transformNode._waitingParentId = null;
  67498. }
  67499. }
  67500. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67501. var mesh = scene.meshes[index];
  67502. if (mesh._waitingParentId) {
  67503. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67504. mesh._waitingParentId = null;
  67505. }
  67506. if (mesh._waitingActions) {
  67507. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67508. mesh._waitingActions = null;
  67509. }
  67510. }
  67511. // freeze world matrix application
  67512. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67513. var currentMesh = scene.meshes[index];
  67514. if (currentMesh._waitingFreezeWorldMatrix) {
  67515. currentMesh.freezeWorldMatrix();
  67516. currentMesh._waitingFreezeWorldMatrix = null;
  67517. }
  67518. else {
  67519. currentMesh.computeWorldMatrix(true);
  67520. }
  67521. }
  67522. // Particles Systems
  67523. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67524. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67525. var parsedParticleSystem = parsedData.particleSystems[index];
  67526. if (parsedParticleSystem.activeParticleCount) {
  67527. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67528. container.particleSystems.push(ps);
  67529. }
  67530. else {
  67531. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67532. container.particleSystems.push(ps);
  67533. }
  67534. }
  67535. }
  67536. // Lens flares
  67537. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67538. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67539. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67540. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67541. container.lensFlareSystems.push(lf);
  67542. }
  67543. }
  67544. // Shadows
  67545. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67546. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67547. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67548. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67549. container.shadowGenerators.push(sg);
  67550. }
  67551. }
  67552. // Lights exclusions / inclusions
  67553. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67554. var light_2 = scene.lights[index];
  67555. // Excluded check
  67556. if (light_2._excludedMeshesIds.length > 0) {
  67557. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67558. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67559. if (excludedMesh) {
  67560. light_2.excludedMeshes.push(excludedMesh);
  67561. }
  67562. }
  67563. light_2._excludedMeshesIds = [];
  67564. }
  67565. // Included check
  67566. if (light_2._includedOnlyMeshesIds.length > 0) {
  67567. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67568. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67569. if (includedOnlyMesh) {
  67570. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67571. }
  67572. }
  67573. light_2._includedOnlyMeshesIds = [];
  67574. }
  67575. }
  67576. // Effect layers
  67577. if (parsedData.effectLayers) {
  67578. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67579. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67580. container.effectLayers.push(effectLayer);
  67581. }
  67582. }
  67583. // Actions (scene)
  67584. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67585. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67586. }
  67587. if (!addToScene) {
  67588. container.removeAllFromScene();
  67589. }
  67590. }
  67591. catch (err) {
  67592. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67593. if (onError) {
  67594. onError(msg, err);
  67595. }
  67596. else {
  67597. BABYLON.Tools.Log(msg);
  67598. throw err;
  67599. }
  67600. }
  67601. finally {
  67602. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67603. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67604. }
  67605. }
  67606. return container;
  67607. };
  67608. BABYLON.SceneLoader.RegisterPlugin({
  67609. name: "babylon.js",
  67610. extensions: ".babylon",
  67611. canDirectLoad: function (data) {
  67612. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67613. return true;
  67614. }
  67615. return false;
  67616. },
  67617. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67618. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67619. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67620. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67621. // and avoid problems with multiple concurrent .babylon loads.
  67622. var log = "importMesh has failed JSON parse";
  67623. try {
  67624. var parsedData = JSON.parse(data);
  67625. log = "";
  67626. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67627. if (!meshesNames) {
  67628. meshesNames = null;
  67629. }
  67630. else if (!Array.isArray(meshesNames)) {
  67631. meshesNames = [meshesNames];
  67632. }
  67633. var hierarchyIds = new Array();
  67634. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67635. var loadedSkeletonsIds = [];
  67636. var loadedMaterialsIds = [];
  67637. var index;
  67638. var cache;
  67639. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67640. var parsedMesh = parsedData.meshes[index];
  67641. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67642. if (meshesNames !== null) {
  67643. // Remove found mesh name from list.
  67644. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67645. }
  67646. //Geometry?
  67647. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67648. //does the file contain geometries?
  67649. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67650. //find the correct geometry and add it to the scene
  67651. var found = false;
  67652. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67653. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67654. return;
  67655. }
  67656. else {
  67657. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67658. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67659. switch (geometryType) {
  67660. case "boxes":
  67661. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67662. break;
  67663. case "spheres":
  67664. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67665. break;
  67666. case "cylinders":
  67667. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67668. break;
  67669. case "toruses":
  67670. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67671. break;
  67672. case "grounds":
  67673. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67674. break;
  67675. case "planes":
  67676. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67677. break;
  67678. case "torusKnots":
  67679. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67680. break;
  67681. case "vertexData":
  67682. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67683. break;
  67684. }
  67685. found = true;
  67686. }
  67687. });
  67688. }
  67689. });
  67690. if (found === false) {
  67691. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67692. }
  67693. }
  67694. }
  67695. // Material ?
  67696. if (parsedMesh.materialId) {
  67697. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67698. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67699. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67700. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67701. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67702. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67703. var subMatId = parsedMultiMaterial.materials[matIndex];
  67704. loadedMaterialsIds.push(subMatId);
  67705. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67706. if (mat) {
  67707. log += "\n\tMaterial " + mat.toString(fullDetails);
  67708. }
  67709. }
  67710. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67711. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67712. if (mmat) {
  67713. materialFound = true;
  67714. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67715. }
  67716. break;
  67717. }
  67718. }
  67719. }
  67720. if (materialFound === false) {
  67721. loadedMaterialsIds.push(parsedMesh.materialId);
  67722. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67723. if (!mat) {
  67724. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67725. }
  67726. else {
  67727. log += "\n\tMaterial " + mat.toString(fullDetails);
  67728. }
  67729. }
  67730. }
  67731. // Skeleton ?
  67732. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67733. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67734. if (skeletonAlreadyLoaded === false) {
  67735. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67736. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67737. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67738. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67739. skeletons.push(skeleton);
  67740. loadedSkeletonsIds.push(parsedSkeleton.id);
  67741. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67742. }
  67743. }
  67744. }
  67745. }
  67746. // Morph targets ?
  67747. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67748. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67749. var managerData = _a[_i];
  67750. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67751. }
  67752. }
  67753. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67754. meshes.push(mesh);
  67755. log += "\n\tMesh " + mesh.toString(fullDetails);
  67756. }
  67757. }
  67758. // Connecting parents
  67759. var currentMesh;
  67760. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67761. currentMesh = scene.meshes[index];
  67762. if (currentMesh._waitingParentId) {
  67763. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67764. currentMesh._waitingParentId = null;
  67765. }
  67766. }
  67767. // freeze and compute world matrix application
  67768. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67769. currentMesh = scene.meshes[index];
  67770. if (currentMesh._waitingFreezeWorldMatrix) {
  67771. currentMesh.freezeWorldMatrix();
  67772. currentMesh._waitingFreezeWorldMatrix = null;
  67773. }
  67774. else {
  67775. currentMesh.computeWorldMatrix(true);
  67776. }
  67777. }
  67778. }
  67779. // Particles
  67780. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67781. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67782. var parsedParticleSystem = parsedData.particleSystems[index];
  67783. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67784. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67785. }
  67786. }
  67787. }
  67788. return true;
  67789. }
  67790. catch (err) {
  67791. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67792. if (onError) {
  67793. onError(msg, err);
  67794. }
  67795. else {
  67796. BABYLON.Tools.Log(msg);
  67797. throw err;
  67798. }
  67799. }
  67800. finally {
  67801. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67802. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67803. }
  67804. }
  67805. return false;
  67806. },
  67807. load: function (scene, data, rootUrl, onError) {
  67808. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67809. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67810. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67811. // and avoid problems with multiple concurrent .babylon loads.
  67812. var log = "importScene has failed JSON parse";
  67813. try {
  67814. var parsedData = JSON.parse(data);
  67815. log = "";
  67816. // Scene
  67817. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  67818. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  67819. }
  67820. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  67821. scene.autoClear = parsedData.autoClear;
  67822. }
  67823. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  67824. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  67825. }
  67826. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  67827. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  67828. }
  67829. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  67830. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  67831. }
  67832. // Fog
  67833. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  67834. scene.fogMode = parsedData.fogMode;
  67835. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  67836. scene.fogStart = parsedData.fogStart;
  67837. scene.fogEnd = parsedData.fogEnd;
  67838. scene.fogDensity = parsedData.fogDensity;
  67839. log += "\tFog mode for scene: ";
  67840. switch (scene.fogMode) {
  67841. // getters not compiling, so using hardcoded
  67842. case 1:
  67843. log += "exp\n";
  67844. break;
  67845. case 2:
  67846. log += "exp2\n";
  67847. break;
  67848. case 3:
  67849. log += "linear\n";
  67850. break;
  67851. }
  67852. }
  67853. //Physics
  67854. if (parsedData.physicsEnabled) {
  67855. var physicsPlugin;
  67856. if (parsedData.physicsEngine === "cannon") {
  67857. physicsPlugin = new BABYLON.CannonJSPlugin();
  67858. }
  67859. else if (parsedData.physicsEngine === "oimo") {
  67860. physicsPlugin = new BABYLON.OimoJSPlugin();
  67861. }
  67862. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  67863. //else - default engine, which is currently oimo
  67864. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  67865. scene.enablePhysics(physicsGravity, physicsPlugin);
  67866. }
  67867. // Metadata
  67868. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  67869. scene.metadata = parsedData.metadata;
  67870. }
  67871. //collisions, if defined. otherwise, default is true
  67872. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  67873. scene.collisionsEnabled = parsedData.collisionsEnabled;
  67874. }
  67875. scene.workerCollisions = !!parsedData.workerCollisions;
  67876. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  67877. if (!container) {
  67878. return false;
  67879. }
  67880. if (parsedData.autoAnimate) {
  67881. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  67882. }
  67883. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  67884. scene.setActiveCameraByID(parsedData.activeCameraID);
  67885. }
  67886. // Environment texture
  67887. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  67888. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  67889. if (parsedData.createDefaultSkybox === true) {
  67890. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  67891. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  67892. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  67893. }
  67894. }
  67895. // Finish
  67896. return true;
  67897. }
  67898. catch (err) {
  67899. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  67900. if (onError) {
  67901. onError(msg, err);
  67902. }
  67903. else {
  67904. BABYLON.Tools.Log(msg);
  67905. throw err;
  67906. }
  67907. }
  67908. finally {
  67909. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67910. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67911. }
  67912. }
  67913. return false;
  67914. },
  67915. loadAssetContainer: function (scene, data, rootUrl, onError) {
  67916. var container = loadAssetContainer(scene, data, rootUrl, onError);
  67917. return container;
  67918. }
  67919. });
  67920. })(BABYLON || (BABYLON = {}));
  67921. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  67922. var BABYLON;
  67923. (function (BABYLON) {
  67924. var FilesInput = /** @class */ (function () {
  67925. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  67926. this.onProcessFileCallback = function () { return true; };
  67927. this._engine = engine;
  67928. this._currentScene = scene;
  67929. this._sceneLoadedCallback = sceneLoadedCallback;
  67930. this._progressCallback = progressCallback;
  67931. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  67932. this._textureLoadingCallback = textureLoadingCallback;
  67933. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  67934. this._onReloadCallback = onReloadCallback;
  67935. this._errorCallback = errorCallback;
  67936. }
  67937. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  67938. var _this = this;
  67939. if (elementToMonitor) {
  67940. this._elementToMonitor = elementToMonitor;
  67941. this._dragEnterHandler = function (e) { _this.drag(e); };
  67942. this._dragOverHandler = function (e) { _this.drag(e); };
  67943. this._dropHandler = function (e) { _this.drop(e); };
  67944. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  67945. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  67946. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  67947. }
  67948. };
  67949. FilesInput.prototype.dispose = function () {
  67950. if (!this._elementToMonitor) {
  67951. return;
  67952. }
  67953. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  67954. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  67955. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  67956. };
  67957. FilesInput.prototype.renderFunction = function () {
  67958. if (this._additionalRenderLoopLogicCallback) {
  67959. this._additionalRenderLoopLogicCallback();
  67960. }
  67961. if (this._currentScene) {
  67962. if (this._textureLoadingCallback) {
  67963. var remaining = this._currentScene.getWaitingItemsCount();
  67964. if (remaining > 0) {
  67965. this._textureLoadingCallback(remaining);
  67966. }
  67967. }
  67968. this._currentScene.render();
  67969. }
  67970. };
  67971. FilesInput.prototype.drag = function (e) {
  67972. e.stopPropagation();
  67973. e.preventDefault();
  67974. };
  67975. FilesInput.prototype.drop = function (eventDrop) {
  67976. eventDrop.stopPropagation();
  67977. eventDrop.preventDefault();
  67978. this.loadFiles(eventDrop);
  67979. };
  67980. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  67981. var _this = this;
  67982. var reader = folder.createReader();
  67983. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  67984. reader.readEntries(function (entries) {
  67985. remaining.count += entries.length;
  67986. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  67987. var entry = entries_1[_i];
  67988. if (entry.isFile) {
  67989. entry.file(function (file) {
  67990. file.correctName = relativePath + file.name;
  67991. files.push(file);
  67992. if (--remaining.count === 0) {
  67993. callback();
  67994. }
  67995. });
  67996. }
  67997. else if (entry.isDirectory) {
  67998. _this._traverseFolder(entry, files, remaining, callback);
  67999. }
  68000. }
  68001. if (--remaining.count) {
  68002. callback();
  68003. }
  68004. });
  68005. };
  68006. FilesInput.prototype._processFiles = function (files) {
  68007. for (var i = 0; i < files.length; i++) {
  68008. var name = files[i].correctName.toLowerCase();
  68009. var extension = name.split('.').pop();
  68010. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68011. continue;
  68012. }
  68013. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68014. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68015. this._sceneFileToLoad = files[i];
  68016. }
  68017. else {
  68018. FilesInput.FilesToLoad[name] = files[i];
  68019. }
  68020. }
  68021. };
  68022. FilesInput.prototype.loadFiles = function (event) {
  68023. var _this = this;
  68024. if (this._startingProcessingFilesCallback)
  68025. this._startingProcessingFilesCallback();
  68026. // Handling data transfer via drag'n'drop
  68027. if (event && event.dataTransfer && event.dataTransfer.files) {
  68028. this._filesToLoad = event.dataTransfer.files;
  68029. }
  68030. // Handling files from input files
  68031. if (event && event.target && event.target.files) {
  68032. this._filesToLoad = event.target.files;
  68033. }
  68034. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68035. var files_1 = new Array();
  68036. var folders = [];
  68037. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68038. for (var i = 0; i < this._filesToLoad.length; i++) {
  68039. var fileToLoad = this._filesToLoad[i];
  68040. var name_1 = fileToLoad.name.toLowerCase();
  68041. var entry = void 0;
  68042. fileToLoad.correctName = name_1;
  68043. if (items) {
  68044. var item = items[i];
  68045. if (item.getAsEntry) {
  68046. entry = item.getAsEntry();
  68047. }
  68048. else if (item.webkitGetAsEntry) {
  68049. entry = item.webkitGetAsEntry();
  68050. }
  68051. }
  68052. if (!entry) {
  68053. files_1.push(fileToLoad);
  68054. }
  68055. else {
  68056. if (entry.isDirectory) {
  68057. folders.push(entry);
  68058. }
  68059. else {
  68060. files_1.push(fileToLoad);
  68061. }
  68062. }
  68063. }
  68064. if (folders.length === 0) {
  68065. this._processFiles(files_1);
  68066. this._processReload();
  68067. }
  68068. else {
  68069. var remaining = { count: folders.length };
  68070. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68071. var folder = folders_1[_i];
  68072. this._traverseFolder(folder, files_1, remaining, function () {
  68073. _this._processFiles(files_1);
  68074. if (remaining.count === 0) {
  68075. _this._processReload();
  68076. }
  68077. });
  68078. }
  68079. }
  68080. }
  68081. };
  68082. FilesInput.prototype._processReload = function () {
  68083. if (this._onReloadCallback) {
  68084. this._onReloadCallback(this._sceneFileToLoad);
  68085. }
  68086. else {
  68087. this.reload();
  68088. }
  68089. };
  68090. FilesInput.prototype.reload = function () {
  68091. var _this = this;
  68092. // If a scene file has been provided
  68093. if (this._sceneFileToLoad) {
  68094. if (this._currentScene) {
  68095. if (BABYLON.Tools.errorsCount > 0) {
  68096. BABYLON.Tools.ClearLogCache();
  68097. }
  68098. this._engine.stopRenderLoop();
  68099. this._currentScene.dispose();
  68100. }
  68101. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68102. if (_this._progressCallback) {
  68103. _this._progressCallback(progress);
  68104. }
  68105. }).then(function (scene) {
  68106. _this._currentScene = scene;
  68107. if (_this._sceneLoadedCallback) {
  68108. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68109. }
  68110. // Wait for textures and shaders to be ready
  68111. _this._currentScene.executeWhenReady(function () {
  68112. _this._engine.runRenderLoop(function () {
  68113. _this.renderFunction();
  68114. });
  68115. });
  68116. }).catch(function (error) {
  68117. if (_this._errorCallback) {
  68118. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68119. }
  68120. });
  68121. }
  68122. else {
  68123. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68124. }
  68125. };
  68126. FilesInput.FilesToLoad = {};
  68127. return FilesInput;
  68128. }());
  68129. BABYLON.FilesInput = FilesInput;
  68130. })(BABYLON || (BABYLON = {}));
  68131. //# sourceMappingURL=babylon.filesInput.js.map
  68132. var BABYLON;
  68133. (function (BABYLON) {
  68134. /**
  68135. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68136. * The underlying implementation relies on an associative array to ensure the best performances.
  68137. * The value can be anything including 'null' but except 'undefined'
  68138. */
  68139. var StringDictionary = /** @class */ (function () {
  68140. function StringDictionary() {
  68141. this._count = 0;
  68142. this._data = {};
  68143. }
  68144. /**
  68145. * This will clear this dictionary and copy the content from the 'source' one.
  68146. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68147. * @param source the dictionary to take the content from and copy to this dictionary
  68148. */
  68149. StringDictionary.prototype.copyFrom = function (source) {
  68150. var _this = this;
  68151. this.clear();
  68152. source.forEach(function (t, v) { return _this.add(t, v); });
  68153. };
  68154. /**
  68155. * Get a value based from its key
  68156. * @param key the given key to get the matching value from
  68157. * @return the value if found, otherwise undefined is returned
  68158. */
  68159. StringDictionary.prototype.get = function (key) {
  68160. var val = this._data[key];
  68161. if (val !== undefined) {
  68162. return val;
  68163. }
  68164. return undefined;
  68165. };
  68166. /**
  68167. * Get a value from its key or add it if it doesn't exist.
  68168. * This method will ensure you that a given key/data will be present in the dictionary.
  68169. * @param key the given key to get the matching value from
  68170. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68171. * The factory will only be invoked if there's no data for the given key.
  68172. * @return the value corresponding to the key.
  68173. */
  68174. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68175. var val = this.get(key);
  68176. if (val !== undefined) {
  68177. return val;
  68178. }
  68179. val = factory(key);
  68180. if (val) {
  68181. this.add(key, val);
  68182. }
  68183. return val;
  68184. };
  68185. /**
  68186. * Get a value from its key if present in the dictionary otherwise add it
  68187. * @param key the key to get the value from
  68188. * @param val if there's no such key/value pair in the dictionary add it with this value
  68189. * @return the value corresponding to the key
  68190. */
  68191. StringDictionary.prototype.getOrAdd = function (key, val) {
  68192. var curVal = this.get(key);
  68193. if (curVal !== undefined) {
  68194. return curVal;
  68195. }
  68196. this.add(key, val);
  68197. return val;
  68198. };
  68199. /**
  68200. * Check if there's a given key in the dictionary
  68201. * @param key the key to check for
  68202. * @return true if the key is present, false otherwise
  68203. */
  68204. StringDictionary.prototype.contains = function (key) {
  68205. return this._data[key] !== undefined;
  68206. };
  68207. /**
  68208. * Add a new key and its corresponding value
  68209. * @param key the key to add
  68210. * @param value the value corresponding to the key
  68211. * @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
  68212. */
  68213. StringDictionary.prototype.add = function (key, value) {
  68214. if (this._data[key] !== undefined) {
  68215. return false;
  68216. }
  68217. this._data[key] = value;
  68218. ++this._count;
  68219. return true;
  68220. };
  68221. StringDictionary.prototype.set = function (key, value) {
  68222. if (this._data[key] === undefined) {
  68223. return false;
  68224. }
  68225. this._data[key] = value;
  68226. return true;
  68227. };
  68228. /**
  68229. * Get the element of the given key and remove it from the dictionary
  68230. * @param key
  68231. */
  68232. StringDictionary.prototype.getAndRemove = function (key) {
  68233. var val = this.get(key);
  68234. if (val !== undefined) {
  68235. delete this._data[key];
  68236. --this._count;
  68237. return val;
  68238. }
  68239. return null;
  68240. };
  68241. /**
  68242. * Remove a key/value from the dictionary.
  68243. * @param key the key to remove
  68244. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68245. */
  68246. StringDictionary.prototype.remove = function (key) {
  68247. if (this.contains(key)) {
  68248. delete this._data[key];
  68249. --this._count;
  68250. return true;
  68251. }
  68252. return false;
  68253. };
  68254. /**
  68255. * Clear the whole content of the dictionary
  68256. */
  68257. StringDictionary.prototype.clear = function () {
  68258. this._data = {};
  68259. this._count = 0;
  68260. };
  68261. Object.defineProperty(StringDictionary.prototype, "count", {
  68262. get: function () {
  68263. return this._count;
  68264. },
  68265. enumerable: true,
  68266. configurable: true
  68267. });
  68268. /**
  68269. * Execute a callback on each key/val of the dictionary.
  68270. * Note that you can remove any element in this dictionary in the callback implementation
  68271. * @param callback the callback to execute on a given key/value pair
  68272. */
  68273. StringDictionary.prototype.forEach = function (callback) {
  68274. for (var cur in this._data) {
  68275. var val = this._data[cur];
  68276. callback(cur, val);
  68277. }
  68278. };
  68279. /**
  68280. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68281. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68282. * Note that you can remove any element in this dictionary in the callback implementation
  68283. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68284. */
  68285. StringDictionary.prototype.first = function (callback) {
  68286. for (var cur in this._data) {
  68287. var val = this._data[cur];
  68288. var res = callback(cur, val);
  68289. if (res) {
  68290. return res;
  68291. }
  68292. }
  68293. return null;
  68294. };
  68295. return StringDictionary;
  68296. }());
  68297. BABYLON.StringDictionary = StringDictionary;
  68298. })(BABYLON || (BABYLON = {}));
  68299. //# sourceMappingURL=babylon.stringDictionary.js.map
  68300. var BABYLON;
  68301. (function (BABYLON) {
  68302. var Tags = /** @class */ (function () {
  68303. function Tags() {
  68304. }
  68305. Tags.EnableFor = function (obj) {
  68306. obj._tags = obj._tags || {};
  68307. obj.hasTags = function () {
  68308. return Tags.HasTags(obj);
  68309. };
  68310. obj.addTags = function (tagsString) {
  68311. return Tags.AddTagsTo(obj, tagsString);
  68312. };
  68313. obj.removeTags = function (tagsString) {
  68314. return Tags.RemoveTagsFrom(obj, tagsString);
  68315. };
  68316. obj.matchesTagsQuery = function (tagsQuery) {
  68317. return Tags.MatchesQuery(obj, tagsQuery);
  68318. };
  68319. };
  68320. Tags.DisableFor = function (obj) {
  68321. delete obj._tags;
  68322. delete obj.hasTags;
  68323. delete obj.addTags;
  68324. delete obj.removeTags;
  68325. delete obj.matchesTagsQuery;
  68326. };
  68327. Tags.HasTags = function (obj) {
  68328. if (!obj._tags) {
  68329. return false;
  68330. }
  68331. return !BABYLON.Tools.IsEmpty(obj._tags);
  68332. };
  68333. Tags.GetTags = function (obj, asString) {
  68334. if (asString === void 0) { asString = true; }
  68335. if (!obj._tags) {
  68336. return null;
  68337. }
  68338. if (asString) {
  68339. var tagsArray = [];
  68340. for (var tag in obj._tags) {
  68341. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68342. tagsArray.push(tag);
  68343. }
  68344. }
  68345. return tagsArray.join(" ");
  68346. }
  68347. else {
  68348. return obj._tags;
  68349. }
  68350. };
  68351. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68352. // a tag cannot start with '||', '&&', and '!'
  68353. // it cannot contain whitespaces
  68354. Tags.AddTagsTo = function (obj, tagsString) {
  68355. if (!tagsString) {
  68356. return;
  68357. }
  68358. if (typeof tagsString !== "string") {
  68359. return;
  68360. }
  68361. var tags = tagsString.split(" ");
  68362. tags.forEach(function (tag, index, array) {
  68363. Tags._AddTagTo(obj, tag);
  68364. });
  68365. };
  68366. Tags._AddTagTo = function (obj, tag) {
  68367. tag = tag.trim();
  68368. if (tag === "" || tag === "true" || tag === "false") {
  68369. return;
  68370. }
  68371. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68372. return;
  68373. }
  68374. Tags.EnableFor(obj);
  68375. obj._tags[tag] = true;
  68376. };
  68377. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68378. if (!Tags.HasTags(obj)) {
  68379. return;
  68380. }
  68381. var tags = tagsString.split(" ");
  68382. for (var t in tags) {
  68383. Tags._RemoveTagFrom(obj, tags[t]);
  68384. }
  68385. };
  68386. Tags._RemoveTagFrom = function (obj, tag) {
  68387. delete obj._tags[tag];
  68388. };
  68389. Tags.MatchesQuery = function (obj, tagsQuery) {
  68390. if (tagsQuery === undefined) {
  68391. return true;
  68392. }
  68393. if (tagsQuery === "") {
  68394. return Tags.HasTags(obj);
  68395. }
  68396. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68397. };
  68398. return Tags;
  68399. }());
  68400. BABYLON.Tags = Tags;
  68401. })(BABYLON || (BABYLON = {}));
  68402. //# sourceMappingURL=babylon.tags.js.map
  68403. var BABYLON;
  68404. (function (BABYLON) {
  68405. /**
  68406. * Class used to evalaute queries containing `and` and `or` operators
  68407. */
  68408. var AndOrNotEvaluator = /** @class */ (function () {
  68409. function AndOrNotEvaluator() {
  68410. }
  68411. /**
  68412. * Evaluate a query
  68413. * @param query defines the query to evaluate
  68414. * @param evaluateCallback defines the callback used to filter result
  68415. * @returns true if the query matches
  68416. */
  68417. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68418. if (!query.match(/\([^\(\)]*\)/g)) {
  68419. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68420. }
  68421. else {
  68422. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68423. // remove parenthesis
  68424. r = r.slice(1, r.length - 1);
  68425. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68426. });
  68427. }
  68428. if (query === "true") {
  68429. return true;
  68430. }
  68431. if (query === "false") {
  68432. return false;
  68433. }
  68434. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68435. };
  68436. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68437. evaluateCallback = evaluateCallback || (function (r) {
  68438. return r === "true" ? true : false;
  68439. });
  68440. var result;
  68441. var or = parenthesisContent.split("||");
  68442. for (var i in or) {
  68443. if (or.hasOwnProperty(i)) {
  68444. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68445. var and = ori.split("&&");
  68446. if (and.length > 1) {
  68447. for (var j = 0; j < and.length; ++j) {
  68448. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68449. if (andj !== "true" && andj !== "false") {
  68450. if (andj[0] === "!") {
  68451. result = !evaluateCallback(andj.substring(1));
  68452. }
  68453. else {
  68454. result = evaluateCallback(andj);
  68455. }
  68456. }
  68457. else {
  68458. result = andj === "true" ? true : false;
  68459. }
  68460. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68461. ori = "false";
  68462. break;
  68463. }
  68464. }
  68465. }
  68466. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68467. result = true;
  68468. break;
  68469. }
  68470. // result equals false (or undefined)
  68471. if (ori !== "true" && ori !== "false") {
  68472. if (ori[0] === "!") {
  68473. result = !evaluateCallback(ori.substring(1));
  68474. }
  68475. else {
  68476. result = evaluateCallback(ori);
  68477. }
  68478. }
  68479. else {
  68480. result = ori === "true" ? true : false;
  68481. }
  68482. }
  68483. }
  68484. // the whole parenthesis scope is replaced by 'true' or 'false'
  68485. return result ? "true" : "false";
  68486. };
  68487. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68488. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68489. // remove whitespaces
  68490. r = r.replace(/[\s]/g, function () { return ""; });
  68491. return r.length % 2 ? "!" : "";
  68492. });
  68493. booleanString = booleanString.trim();
  68494. if (booleanString === "!true") {
  68495. booleanString = "false";
  68496. }
  68497. else if (booleanString === "!false") {
  68498. booleanString = "true";
  68499. }
  68500. return booleanString;
  68501. };
  68502. return AndOrNotEvaluator;
  68503. }());
  68504. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68505. })(BABYLON || (BABYLON = {}));
  68506. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68507. var BABYLON;
  68508. (function (BABYLON) {
  68509. /**
  68510. * Class used to enable access to IndexedDB
  68511. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68512. */
  68513. var Database = /** @class */ (function () {
  68514. /**
  68515. * Creates a new Database
  68516. * @param urlToScene defines the url to load the scene
  68517. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68518. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68519. */
  68520. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68521. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68522. var _this = this;
  68523. // Handling various flavors of prefixed version of IndexedDB
  68524. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68525. this.callbackManifestChecked = callbackManifestChecked;
  68526. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68527. this.db = null;
  68528. this._enableSceneOffline = false;
  68529. this._enableTexturesOffline = false;
  68530. this.manifestVersionFound = 0;
  68531. this.mustUpdateRessources = false;
  68532. this.hasReachedQuota = false;
  68533. if (!Database.IDBStorageEnabled) {
  68534. this.callbackManifestChecked(true);
  68535. }
  68536. else {
  68537. if (disableManifestCheck) {
  68538. this._enableSceneOffline = true;
  68539. this._enableTexturesOffline = true;
  68540. this.manifestVersionFound = 1;
  68541. BABYLON.Tools.SetImmediate(function () {
  68542. _this.callbackManifestChecked(true);
  68543. });
  68544. }
  68545. else {
  68546. this._checkManifestFile();
  68547. }
  68548. }
  68549. }
  68550. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68551. /**
  68552. * Gets a boolean indicating if scene must be saved in the database
  68553. */
  68554. get: function () {
  68555. return this._enableSceneOffline;
  68556. },
  68557. enumerable: true,
  68558. configurable: true
  68559. });
  68560. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68561. /**
  68562. * Gets a boolean indicating if textures must be saved in the database
  68563. */
  68564. get: function () {
  68565. return this._enableTexturesOffline;
  68566. },
  68567. enumerable: true,
  68568. configurable: true
  68569. });
  68570. Database.prototype._checkManifestFile = function () {
  68571. var _this = this;
  68572. var noManifestFile = function () {
  68573. _this._enableSceneOffline = false;
  68574. _this._enableTexturesOffline = false;
  68575. _this.callbackManifestChecked(false);
  68576. };
  68577. var timeStampUsed = false;
  68578. var manifestURL = this.currentSceneUrl + ".manifest";
  68579. var xhr = new XMLHttpRequest();
  68580. if (navigator.onLine) {
  68581. // Adding a timestamp to by-pass browsers' cache
  68582. timeStampUsed = true;
  68583. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68584. }
  68585. xhr.open("GET", manifestURL, true);
  68586. xhr.addEventListener("load", function () {
  68587. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68588. try {
  68589. var manifestFile = JSON.parse(xhr.response);
  68590. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68591. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68592. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68593. _this.manifestVersionFound = manifestFile.version;
  68594. }
  68595. if (_this.callbackManifestChecked) {
  68596. _this.callbackManifestChecked(true);
  68597. }
  68598. }
  68599. catch (ex) {
  68600. noManifestFile();
  68601. }
  68602. }
  68603. else {
  68604. noManifestFile();
  68605. }
  68606. }, false);
  68607. xhr.addEventListener("error", function (event) {
  68608. if (timeStampUsed) {
  68609. timeStampUsed = false;
  68610. // Let's retry without the timeStamp
  68611. // It could fail when coupled with HTML5 Offline API
  68612. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68613. xhr.open("GET", retryManifestURL, true);
  68614. xhr.send();
  68615. }
  68616. else {
  68617. noManifestFile();
  68618. }
  68619. }, false);
  68620. try {
  68621. xhr.send();
  68622. }
  68623. catch (ex) {
  68624. BABYLON.Tools.Error("Error on XHR send request.");
  68625. this.callbackManifestChecked(false);
  68626. }
  68627. };
  68628. /**
  68629. * Open the database and make it available
  68630. * @param successCallback defines the callback to call on success
  68631. * @param errorCallback defines the callback to call on error
  68632. */
  68633. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68634. var _this = this;
  68635. var handleError = function () {
  68636. _this.isSupported = false;
  68637. if (errorCallback)
  68638. errorCallback();
  68639. };
  68640. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68641. // Your browser doesn't support IndexedDB
  68642. this.isSupported = false;
  68643. if (errorCallback)
  68644. errorCallback();
  68645. }
  68646. else {
  68647. // If the DB hasn't been opened or created yet
  68648. if (!this.db) {
  68649. this.hasReachedQuota = false;
  68650. this.isSupported = true;
  68651. var request = this.idbFactory.open("babylonjs", 1);
  68652. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68653. request.onerror = function (event) {
  68654. handleError();
  68655. };
  68656. // executes when a version change transaction cannot complete due to other active transactions
  68657. request.onblocked = function (event) {
  68658. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68659. handleError();
  68660. };
  68661. // DB has been opened successfully
  68662. request.onsuccess = function (event) {
  68663. _this.db = request.result;
  68664. successCallback();
  68665. };
  68666. // Initialization of the DB. Creating Scenes & Textures stores
  68667. request.onupgradeneeded = function (event) {
  68668. _this.db = (event.target).result;
  68669. if (_this.db) {
  68670. try {
  68671. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68672. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68673. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68674. }
  68675. catch (ex) {
  68676. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68677. handleError();
  68678. }
  68679. }
  68680. };
  68681. }
  68682. // DB has already been created and opened
  68683. else {
  68684. if (successCallback)
  68685. successCallback();
  68686. }
  68687. }
  68688. };
  68689. /**
  68690. * Loads an image from the database
  68691. * @param url defines the url to load from
  68692. * @param image defines the target DOM image
  68693. */
  68694. Database.prototype.loadImageFromDB = function (url, image) {
  68695. var _this = this;
  68696. var completeURL = Database._ReturnFullUrlLocation(url);
  68697. var saveAndLoadImage = function () {
  68698. if (!_this.hasReachedQuota && _this.db !== null) {
  68699. // the texture is not yet in the DB, let's try to save it
  68700. _this._saveImageIntoDBAsync(completeURL, image);
  68701. }
  68702. // If the texture is not in the DB and we've reached the DB quota limit
  68703. // let's load it directly from the web
  68704. else {
  68705. image.src = url;
  68706. }
  68707. };
  68708. if (!this.mustUpdateRessources) {
  68709. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68710. }
  68711. // First time we're download the images or update requested in the manifest file by a version change
  68712. else {
  68713. saveAndLoadImage();
  68714. }
  68715. };
  68716. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68717. if (this.isSupported && this.db !== null) {
  68718. var texture;
  68719. var transaction = this.db.transaction(["textures"]);
  68720. transaction.onabort = function (event) {
  68721. image.src = url;
  68722. };
  68723. transaction.oncomplete = function (event) {
  68724. var blobTextureURL;
  68725. if (texture) {
  68726. var URL = window.URL || window.webkitURL;
  68727. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68728. image.onerror = function () {
  68729. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68730. image.src = url;
  68731. };
  68732. image.src = blobTextureURL;
  68733. }
  68734. else {
  68735. notInDBCallback();
  68736. }
  68737. };
  68738. var getRequest = transaction.objectStore("textures").get(url);
  68739. getRequest.onsuccess = function (event) {
  68740. texture = (event.target).result;
  68741. };
  68742. getRequest.onerror = function (event) {
  68743. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68744. image.src = url;
  68745. };
  68746. }
  68747. else {
  68748. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68749. image.src = url;
  68750. }
  68751. };
  68752. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68753. var _this = this;
  68754. if (this.isSupported) {
  68755. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68756. var generateBlobUrl = function () {
  68757. var blobTextureURL;
  68758. if (blob) {
  68759. var URL = window.URL || window.webkitURL;
  68760. try {
  68761. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68762. }
  68763. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68764. catch (ex) {
  68765. blobTextureURL = URL.createObjectURL(blob);
  68766. }
  68767. }
  68768. if (blobTextureURL) {
  68769. image.src = blobTextureURL;
  68770. }
  68771. };
  68772. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68773. var xhr = new XMLHttpRequest(), blob;
  68774. xhr.open("GET", url, true);
  68775. xhr.responseType = "blob";
  68776. xhr.addEventListener("load", function () {
  68777. if (xhr.status === 200 && _this.db) {
  68778. // Blob as response (XHR2)
  68779. blob = xhr.response;
  68780. var transaction = _this.db.transaction(["textures"], "readwrite");
  68781. // the transaction could abort because of a QuotaExceededError error
  68782. transaction.onabort = function (event) {
  68783. try {
  68784. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68785. var srcElement = (event.srcElement || event.target);
  68786. var error = srcElement.error;
  68787. if (error && error.name === "QuotaExceededError") {
  68788. _this.hasReachedQuota = true;
  68789. }
  68790. }
  68791. catch (ex) { }
  68792. generateBlobUrl();
  68793. };
  68794. transaction.oncomplete = function (event) {
  68795. generateBlobUrl();
  68796. };
  68797. var newTexture = { textureUrl: url, data: blob };
  68798. try {
  68799. // Put the blob into the dabase
  68800. var addRequest = transaction.objectStore("textures").put(newTexture);
  68801. addRequest.onsuccess = function (event) {
  68802. };
  68803. addRequest.onerror = function (event) {
  68804. generateBlobUrl();
  68805. };
  68806. }
  68807. catch (ex) {
  68808. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  68809. if (ex.code === 25) {
  68810. Database.IsUASupportingBlobStorage = false;
  68811. }
  68812. image.src = url;
  68813. }
  68814. }
  68815. else {
  68816. image.src = url;
  68817. }
  68818. }, false);
  68819. xhr.addEventListener("error", function (event) {
  68820. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  68821. image.src = url;
  68822. }, false);
  68823. xhr.send();
  68824. }
  68825. else {
  68826. image.src = url;
  68827. }
  68828. }
  68829. else {
  68830. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68831. image.src = url;
  68832. }
  68833. };
  68834. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  68835. var _this = this;
  68836. var updateVersion = function () {
  68837. // the version is not yet in the DB or we need to update it
  68838. _this._saveVersionIntoDBAsync(url, versionLoaded);
  68839. };
  68840. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  68841. };
  68842. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  68843. var _this = this;
  68844. if (this.isSupported && this.db) {
  68845. var version;
  68846. try {
  68847. var transaction = this.db.transaction(["versions"]);
  68848. transaction.oncomplete = function (event) {
  68849. if (version) {
  68850. // If the version in the JSON file is > than the version in DB
  68851. if (_this.manifestVersionFound > version.data) {
  68852. _this.mustUpdateRessources = true;
  68853. updateInDBCallback();
  68854. }
  68855. else {
  68856. callback(version.data);
  68857. }
  68858. }
  68859. // version was not found in DB
  68860. else {
  68861. _this.mustUpdateRessources = true;
  68862. updateInDBCallback();
  68863. }
  68864. };
  68865. transaction.onabort = function (event) {
  68866. callback(-1);
  68867. };
  68868. var getRequest = transaction.objectStore("versions").get(url);
  68869. getRequest.onsuccess = function (event) {
  68870. version = (event.target).result;
  68871. };
  68872. getRequest.onerror = function (event) {
  68873. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  68874. callback(-1);
  68875. };
  68876. }
  68877. catch (ex) {
  68878. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  68879. callback(-1);
  68880. }
  68881. }
  68882. else {
  68883. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68884. callback(-1);
  68885. }
  68886. };
  68887. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  68888. var _this = this;
  68889. if (this.isSupported && !this.hasReachedQuota && this.db) {
  68890. try {
  68891. // Open a transaction to the database
  68892. var transaction = this.db.transaction(["versions"], "readwrite");
  68893. // the transaction could abort because of a QuotaExceededError error
  68894. transaction.onabort = function (event) {
  68895. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68896. var error = event.srcElement['error'];
  68897. if (error && error.name === "QuotaExceededError") {
  68898. _this.hasReachedQuota = true;
  68899. }
  68900. }
  68901. catch (ex) { }
  68902. callback(-1);
  68903. };
  68904. transaction.oncomplete = function (event) {
  68905. callback(_this.manifestVersionFound);
  68906. };
  68907. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  68908. // Put the scene into the database
  68909. var addRequest = transaction.objectStore("versions").put(newVersion);
  68910. addRequest.onsuccess = function (event) {
  68911. };
  68912. addRequest.onerror = function (event) {
  68913. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  68914. };
  68915. }
  68916. catch (ex) {
  68917. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  68918. callback(-1);
  68919. }
  68920. }
  68921. else {
  68922. callback(-1);
  68923. }
  68924. };
  68925. /**
  68926. * Loads a file from database
  68927. * @param url defines the URL to load from
  68928. * @param sceneLoaded defines a callback to call on success
  68929. * @param progressCallBack defines a callback to call when progress changed
  68930. * @param errorCallback defines a callback to call on error
  68931. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  68932. */
  68933. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  68934. var _this = this;
  68935. var completeUrl = Database._ReturnFullUrlLocation(url);
  68936. var saveAndLoadFile = function () {
  68937. // the scene is not yet in the DB, let's try to save it
  68938. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  68939. };
  68940. this._checkVersionFromDB(completeUrl, function (version) {
  68941. if (version !== -1) {
  68942. if (!_this.mustUpdateRessources) {
  68943. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  68944. }
  68945. else {
  68946. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  68947. }
  68948. }
  68949. else {
  68950. if (errorCallback) {
  68951. errorCallback();
  68952. }
  68953. }
  68954. });
  68955. };
  68956. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  68957. if (this.isSupported && this.db) {
  68958. var targetStore;
  68959. if (url.indexOf(".babylon") !== -1) {
  68960. targetStore = "scenes";
  68961. }
  68962. else {
  68963. targetStore = "textures";
  68964. }
  68965. var file;
  68966. var transaction = this.db.transaction([targetStore]);
  68967. transaction.oncomplete = function (event) {
  68968. if (file) {
  68969. callback(file.data);
  68970. }
  68971. // file was not found in DB
  68972. else {
  68973. notInDBCallback();
  68974. }
  68975. };
  68976. transaction.onabort = function (event) {
  68977. notInDBCallback();
  68978. };
  68979. var getRequest = transaction.objectStore(targetStore).get(url);
  68980. getRequest.onsuccess = function (event) {
  68981. file = (event.target).result;
  68982. };
  68983. getRequest.onerror = function (event) {
  68984. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  68985. notInDBCallback();
  68986. };
  68987. }
  68988. else {
  68989. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68990. callback();
  68991. }
  68992. };
  68993. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  68994. var _this = this;
  68995. if (this.isSupported) {
  68996. var targetStore;
  68997. if (url.indexOf(".babylon") !== -1) {
  68998. targetStore = "scenes";
  68999. }
  69000. else {
  69001. targetStore = "textures";
  69002. }
  69003. // Create XHR
  69004. var xhr = new XMLHttpRequest();
  69005. var fileData;
  69006. xhr.open("GET", url, true);
  69007. if (useArrayBuffer) {
  69008. xhr.responseType = "arraybuffer";
  69009. }
  69010. if (progressCallback) {
  69011. xhr.onprogress = progressCallback;
  69012. }
  69013. xhr.addEventListener("load", function () {
  69014. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69015. // Blob as response (XHR2)
  69016. //fileData = xhr.responseText;
  69017. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69018. if (!_this.hasReachedQuota && _this.db) {
  69019. // Open a transaction to the database
  69020. var transaction = _this.db.transaction([targetStore], "readwrite");
  69021. // the transaction could abort because of a QuotaExceededError error
  69022. transaction.onabort = function (event) {
  69023. try {
  69024. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69025. var error = event.srcElement['error'];
  69026. if (error && error.name === "QuotaExceededError") {
  69027. _this.hasReachedQuota = true;
  69028. }
  69029. }
  69030. catch (ex) { }
  69031. callback(fileData);
  69032. };
  69033. transaction.oncomplete = function (event) {
  69034. callback(fileData);
  69035. };
  69036. var newFile;
  69037. if (targetStore === "scenes") {
  69038. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69039. }
  69040. else {
  69041. newFile = { textureUrl: url, data: fileData };
  69042. }
  69043. try {
  69044. // Put the scene into the database
  69045. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69046. addRequest.onsuccess = function (event) {
  69047. };
  69048. addRequest.onerror = function (event) {
  69049. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69050. };
  69051. }
  69052. catch (ex) {
  69053. callback(fileData);
  69054. }
  69055. }
  69056. else {
  69057. callback(fileData);
  69058. }
  69059. }
  69060. else {
  69061. callback();
  69062. }
  69063. }, false);
  69064. xhr.addEventListener("error", function (event) {
  69065. BABYLON.Tools.Error("error on XHR request.");
  69066. callback();
  69067. }, false);
  69068. xhr.send();
  69069. }
  69070. else {
  69071. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69072. callback();
  69073. }
  69074. };
  69075. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69076. Database.IsUASupportingBlobStorage = true;
  69077. /** Gets a boolean indicating if Database storate is enabled */
  69078. Database.IDBStorageEnabled = true;
  69079. Database._ParseURL = function (url) {
  69080. var a = document.createElement('a');
  69081. a.href = url;
  69082. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69083. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69084. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69085. return absLocation;
  69086. };
  69087. Database._ReturnFullUrlLocation = function (url) {
  69088. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69089. return (Database._ParseURL(window.location.href) + url);
  69090. }
  69091. else {
  69092. return url;
  69093. }
  69094. };
  69095. return Database;
  69096. }());
  69097. BABYLON.Database = Database;
  69098. })(BABYLON || (BABYLON = {}));
  69099. //# sourceMappingURL=babylon.database.js.map
  69100. var BABYLON;
  69101. (function (BABYLON) {
  69102. var FresnelParameters = /** @class */ (function () {
  69103. function FresnelParameters() {
  69104. this._isEnabled = true;
  69105. this.leftColor = BABYLON.Color3.White();
  69106. this.rightColor = BABYLON.Color3.Black();
  69107. this.bias = 0;
  69108. this.power = 1;
  69109. }
  69110. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69111. get: function () {
  69112. return this._isEnabled;
  69113. },
  69114. set: function (value) {
  69115. if (this._isEnabled === value) {
  69116. return;
  69117. }
  69118. this._isEnabled = value;
  69119. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69120. },
  69121. enumerable: true,
  69122. configurable: true
  69123. });
  69124. FresnelParameters.prototype.clone = function () {
  69125. var newFresnelParameters = new FresnelParameters();
  69126. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69127. return newFresnelParameters;
  69128. };
  69129. FresnelParameters.prototype.serialize = function () {
  69130. var serializationObject = {};
  69131. serializationObject.isEnabled = this.isEnabled;
  69132. serializationObject.leftColor = this.leftColor.asArray();
  69133. serializationObject.rightColor = this.rightColor.asArray();
  69134. serializationObject.bias = this.bias;
  69135. serializationObject.power = this.power;
  69136. return serializationObject;
  69137. };
  69138. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69139. var fresnelParameters = new FresnelParameters();
  69140. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69141. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69142. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69143. fresnelParameters.bias = parsedFresnelParameters.bias;
  69144. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69145. return fresnelParameters;
  69146. };
  69147. return FresnelParameters;
  69148. }());
  69149. BABYLON.FresnelParameters = FresnelParameters;
  69150. })(BABYLON || (BABYLON = {}));
  69151. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69152. var BABYLON;
  69153. (function (BABYLON) {
  69154. var MultiMaterial = /** @class */ (function (_super) {
  69155. __extends(MultiMaterial, _super);
  69156. function MultiMaterial(name, scene) {
  69157. var _this = _super.call(this, name, scene, true) || this;
  69158. scene.multiMaterials.push(_this);
  69159. _this.subMaterials = new Array();
  69160. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69161. return _this;
  69162. }
  69163. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69164. get: function () {
  69165. return this._subMaterials;
  69166. },
  69167. set: function (value) {
  69168. this._subMaterials = value;
  69169. this._hookArray(value);
  69170. },
  69171. enumerable: true,
  69172. configurable: true
  69173. });
  69174. MultiMaterial.prototype._hookArray = function (array) {
  69175. var _this = this;
  69176. var oldPush = array.push;
  69177. array.push = function () {
  69178. var items = [];
  69179. for (var _i = 0; _i < arguments.length; _i++) {
  69180. items[_i] = arguments[_i];
  69181. }
  69182. var result = oldPush.apply(array, items);
  69183. _this._markAllSubMeshesAsTexturesDirty();
  69184. return result;
  69185. };
  69186. var oldSplice = array.splice;
  69187. array.splice = function (index, deleteCount) {
  69188. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69189. _this._markAllSubMeshesAsTexturesDirty();
  69190. return deleted;
  69191. };
  69192. };
  69193. // Properties
  69194. MultiMaterial.prototype.getSubMaterial = function (index) {
  69195. if (index < 0 || index >= this.subMaterials.length) {
  69196. return this.getScene().defaultMaterial;
  69197. }
  69198. return this.subMaterials[index];
  69199. };
  69200. MultiMaterial.prototype.getActiveTextures = function () {
  69201. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69202. if (subMaterial) {
  69203. return subMaterial.getActiveTextures();
  69204. }
  69205. else {
  69206. return [];
  69207. }
  69208. }));
  69209. var _a;
  69210. };
  69211. // Methods
  69212. MultiMaterial.prototype.getClassName = function () {
  69213. return "MultiMaterial";
  69214. };
  69215. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69216. for (var index = 0; index < this.subMaterials.length; index++) {
  69217. var subMaterial = this.subMaterials[index];
  69218. if (subMaterial) {
  69219. if (subMaterial.storeEffectOnSubMeshes) {
  69220. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69221. return false;
  69222. }
  69223. continue;
  69224. }
  69225. if (!subMaterial.isReady(mesh)) {
  69226. return false;
  69227. }
  69228. }
  69229. }
  69230. return true;
  69231. };
  69232. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69233. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69234. for (var index = 0; index < this.subMaterials.length; index++) {
  69235. var subMaterial = null;
  69236. var current = this.subMaterials[index];
  69237. if (cloneChildren && current) {
  69238. subMaterial = current.clone(name + "-" + current.name);
  69239. }
  69240. else {
  69241. subMaterial = this.subMaterials[index];
  69242. }
  69243. newMultiMaterial.subMaterials.push(subMaterial);
  69244. }
  69245. return newMultiMaterial;
  69246. };
  69247. MultiMaterial.prototype.serialize = function () {
  69248. var serializationObject = {};
  69249. serializationObject.name = this.name;
  69250. serializationObject.id = this.id;
  69251. if (BABYLON.Tags) {
  69252. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69253. }
  69254. serializationObject.materials = [];
  69255. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69256. var subMat = this.subMaterials[matIndex];
  69257. if (subMat) {
  69258. serializationObject.materials.push(subMat.id);
  69259. }
  69260. else {
  69261. serializationObject.materials.push(null);
  69262. }
  69263. }
  69264. return serializationObject;
  69265. };
  69266. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69267. var scene = this.getScene();
  69268. if (!scene) {
  69269. return;
  69270. }
  69271. var index = scene.multiMaterials.indexOf(this);
  69272. if (index >= 0) {
  69273. scene.multiMaterials.splice(index, 1);
  69274. }
  69275. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69276. };
  69277. return MultiMaterial;
  69278. }(BABYLON.Material));
  69279. BABYLON.MultiMaterial = MultiMaterial;
  69280. })(BABYLON || (BABYLON = {}));
  69281. //# sourceMappingURL=babylon.multiMaterial.js.map
  69282. var BABYLON;
  69283. (function (BABYLON) {
  69284. var FreeCameraTouchInput = /** @class */ (function () {
  69285. function FreeCameraTouchInput() {
  69286. this._offsetX = null;
  69287. this._offsetY = null;
  69288. this._pointerPressed = new Array();
  69289. this.touchAngularSensibility = 200000.0;
  69290. this.touchMoveSensibility = 250.0;
  69291. }
  69292. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69293. var _this = this;
  69294. var previousPosition = null;
  69295. if (this._pointerInput === undefined) {
  69296. this._onLostFocus = function (evt) {
  69297. _this._offsetX = null;
  69298. _this._offsetY = null;
  69299. };
  69300. this._pointerInput = function (p, s) {
  69301. var evt = p.event;
  69302. if (evt.pointerType === "mouse") {
  69303. return;
  69304. }
  69305. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69306. if (!noPreventDefault) {
  69307. evt.preventDefault();
  69308. }
  69309. _this._pointerPressed.push(evt.pointerId);
  69310. if (_this._pointerPressed.length !== 1) {
  69311. return;
  69312. }
  69313. previousPosition = {
  69314. x: evt.clientX,
  69315. y: evt.clientY
  69316. };
  69317. }
  69318. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69319. if (!noPreventDefault) {
  69320. evt.preventDefault();
  69321. }
  69322. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69323. if (index === -1) {
  69324. return;
  69325. }
  69326. _this._pointerPressed.splice(index, 1);
  69327. if (index != 0) {
  69328. return;
  69329. }
  69330. previousPosition = null;
  69331. _this._offsetX = null;
  69332. _this._offsetY = null;
  69333. }
  69334. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69335. if (!noPreventDefault) {
  69336. evt.preventDefault();
  69337. }
  69338. if (!previousPosition) {
  69339. return;
  69340. }
  69341. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69342. if (index != 0) {
  69343. return;
  69344. }
  69345. _this._offsetX = evt.clientX - previousPosition.x;
  69346. _this._offsetY = -(evt.clientY - previousPosition.y);
  69347. }
  69348. };
  69349. }
  69350. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69351. if (this._onLostFocus) {
  69352. element.addEventListener("blur", this._onLostFocus);
  69353. }
  69354. };
  69355. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69356. if (this._pointerInput && element) {
  69357. if (this._observer) {
  69358. this.camera.getScene().onPointerObservable.remove(this._observer);
  69359. this._observer = null;
  69360. }
  69361. if (this._onLostFocus) {
  69362. element.removeEventListener("blur", this._onLostFocus);
  69363. this._onLostFocus = null;
  69364. }
  69365. this._pointerPressed = [];
  69366. this._offsetX = null;
  69367. this._offsetY = null;
  69368. }
  69369. };
  69370. FreeCameraTouchInput.prototype.checkInputs = function () {
  69371. if (this._offsetX && this._offsetY) {
  69372. var camera = this.camera;
  69373. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69374. if (this._pointerPressed.length > 1) {
  69375. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69376. }
  69377. else {
  69378. var speed = camera._computeLocalCameraSpeed();
  69379. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69380. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69381. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69382. }
  69383. }
  69384. };
  69385. FreeCameraTouchInput.prototype.getClassName = function () {
  69386. return "FreeCameraTouchInput";
  69387. };
  69388. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69389. return "touch";
  69390. };
  69391. __decorate([
  69392. BABYLON.serialize()
  69393. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69394. __decorate([
  69395. BABYLON.serialize()
  69396. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69397. return FreeCameraTouchInput;
  69398. }());
  69399. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69400. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69401. })(BABYLON || (BABYLON = {}));
  69402. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69403. var BABYLON;
  69404. (function (BABYLON) {
  69405. // We're mainly based on the logic defined into the FreeCamera code
  69406. var TouchCamera = /** @class */ (function (_super) {
  69407. __extends(TouchCamera, _super);
  69408. //-- end properties for backward compatibility for inputs
  69409. function TouchCamera(name, position, scene) {
  69410. var _this = _super.call(this, name, position, scene) || this;
  69411. _this.inputs.addTouch();
  69412. _this._setupInputs();
  69413. return _this;
  69414. }
  69415. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69416. //-- Begin properties for backward compatibility for inputs
  69417. get: function () {
  69418. var touch = this.inputs.attached["touch"];
  69419. if (touch)
  69420. return touch.touchAngularSensibility;
  69421. return 0;
  69422. },
  69423. set: function (value) {
  69424. var touch = this.inputs.attached["touch"];
  69425. if (touch)
  69426. touch.touchAngularSensibility = value;
  69427. },
  69428. enumerable: true,
  69429. configurable: true
  69430. });
  69431. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69432. get: function () {
  69433. var touch = this.inputs.attached["touch"];
  69434. if (touch)
  69435. return touch.touchMoveSensibility;
  69436. return 0;
  69437. },
  69438. set: function (value) {
  69439. var touch = this.inputs.attached["touch"];
  69440. if (touch)
  69441. touch.touchMoveSensibility = value;
  69442. },
  69443. enumerable: true,
  69444. configurable: true
  69445. });
  69446. TouchCamera.prototype.getClassName = function () {
  69447. return "TouchCamera";
  69448. };
  69449. TouchCamera.prototype._setupInputs = function () {
  69450. var mouse = this.inputs.attached["mouse"];
  69451. if (mouse) {
  69452. mouse.touchEnabled = false;
  69453. }
  69454. };
  69455. return TouchCamera;
  69456. }(BABYLON.FreeCamera));
  69457. BABYLON.TouchCamera = TouchCamera;
  69458. })(BABYLON || (BABYLON = {}));
  69459. //# sourceMappingURL=babylon.touchCamera.js.map
  69460. var BABYLON;
  69461. (function (BABYLON) {
  69462. var ProceduralTexture = /** @class */ (function (_super) {
  69463. __extends(ProceduralTexture, _super);
  69464. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69465. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69466. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69467. if (isCube === void 0) { isCube = false; }
  69468. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69469. _this.isCube = isCube;
  69470. _this.isEnabled = true;
  69471. _this._currentRefreshId = -1;
  69472. _this._refreshRate = 1;
  69473. _this._vertexBuffers = {};
  69474. _this._uniforms = new Array();
  69475. _this._samplers = new Array();
  69476. _this._textures = {};
  69477. _this._floats = {};
  69478. _this._floatsArrays = {};
  69479. _this._colors3 = {};
  69480. _this._colors4 = {};
  69481. _this._vectors2 = {};
  69482. _this._vectors3 = {};
  69483. _this._matrices = {};
  69484. _this._fallbackTextureUsed = false;
  69485. scene.proceduralTextures.push(_this);
  69486. _this._engine = scene.getEngine();
  69487. _this.name = name;
  69488. _this.isRenderTarget = true;
  69489. _this._size = size;
  69490. _this._generateMipMaps = generateMipMaps;
  69491. _this.setFragment(fragment);
  69492. _this._fallbackTexture = fallbackTexture;
  69493. if (isCube) {
  69494. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69495. _this.setFloat("face", 0);
  69496. }
  69497. else {
  69498. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69499. }
  69500. // VBO
  69501. var vertices = [];
  69502. vertices.push(1, 1);
  69503. vertices.push(-1, 1);
  69504. vertices.push(-1, -1);
  69505. vertices.push(1, -1);
  69506. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69507. _this._createIndexBuffer();
  69508. return _this;
  69509. }
  69510. ProceduralTexture.prototype._createIndexBuffer = function () {
  69511. var engine = this._engine;
  69512. // Indices
  69513. var indices = [];
  69514. indices.push(0);
  69515. indices.push(1);
  69516. indices.push(2);
  69517. indices.push(0);
  69518. indices.push(2);
  69519. indices.push(3);
  69520. this._indexBuffer = engine.createIndexBuffer(indices);
  69521. };
  69522. ProceduralTexture.prototype._rebuild = function () {
  69523. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69524. if (vb) {
  69525. vb._rebuild();
  69526. }
  69527. this._createIndexBuffer();
  69528. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69529. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69530. }
  69531. };
  69532. ProceduralTexture.prototype.reset = function () {
  69533. if (this._effect === undefined) {
  69534. return;
  69535. }
  69536. var engine = this._engine;
  69537. engine._releaseEffect(this._effect);
  69538. };
  69539. ProceduralTexture.prototype.isReady = function () {
  69540. var _this = this;
  69541. var engine = this._engine;
  69542. var shaders;
  69543. if (!this._fragment) {
  69544. return false;
  69545. }
  69546. if (this._fallbackTextureUsed) {
  69547. return true;
  69548. }
  69549. if (this._fragment.fragmentElement !== undefined) {
  69550. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69551. }
  69552. else {
  69553. shaders = { vertex: "procedural", fragment: this._fragment };
  69554. }
  69555. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69556. _this.releaseInternalTexture();
  69557. if (_this._fallbackTexture) {
  69558. _this._texture = _this._fallbackTexture._texture;
  69559. if (_this._texture) {
  69560. _this._texture.incrementReferences();
  69561. }
  69562. }
  69563. _this._fallbackTextureUsed = true;
  69564. });
  69565. return this._effect.isReady();
  69566. };
  69567. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69568. this._currentRefreshId = -1;
  69569. };
  69570. ProceduralTexture.prototype.setFragment = function (fragment) {
  69571. this._fragment = fragment;
  69572. };
  69573. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69574. get: function () {
  69575. return this._refreshRate;
  69576. },
  69577. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69578. set: function (value) {
  69579. this._refreshRate = value;
  69580. this.resetRefreshCounter();
  69581. },
  69582. enumerable: true,
  69583. configurable: true
  69584. });
  69585. ProceduralTexture.prototype._shouldRender = function () {
  69586. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69587. return false;
  69588. }
  69589. if (this._fallbackTextureUsed) {
  69590. return false;
  69591. }
  69592. if (this._currentRefreshId === -1) { // At least render once
  69593. this._currentRefreshId = 1;
  69594. return true;
  69595. }
  69596. if (this.refreshRate === this._currentRefreshId) {
  69597. this._currentRefreshId = 1;
  69598. return true;
  69599. }
  69600. this._currentRefreshId++;
  69601. return false;
  69602. };
  69603. ProceduralTexture.prototype.getRenderSize = function () {
  69604. return this._size;
  69605. };
  69606. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69607. if (this._fallbackTextureUsed) {
  69608. return;
  69609. }
  69610. this.releaseInternalTexture();
  69611. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69612. };
  69613. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69614. if (this._uniforms.indexOf(uniformName) === -1) {
  69615. this._uniforms.push(uniformName);
  69616. }
  69617. };
  69618. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69619. if (this._samplers.indexOf(name) === -1) {
  69620. this._samplers.push(name);
  69621. }
  69622. this._textures[name] = texture;
  69623. return this;
  69624. };
  69625. ProceduralTexture.prototype.setFloat = function (name, value) {
  69626. this._checkUniform(name);
  69627. this._floats[name] = value;
  69628. return this;
  69629. };
  69630. ProceduralTexture.prototype.setFloats = function (name, value) {
  69631. this._checkUniform(name);
  69632. this._floatsArrays[name] = value;
  69633. return this;
  69634. };
  69635. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69636. this._checkUniform(name);
  69637. this._colors3[name] = value;
  69638. return this;
  69639. };
  69640. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69641. this._checkUniform(name);
  69642. this._colors4[name] = value;
  69643. return this;
  69644. };
  69645. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69646. this._checkUniform(name);
  69647. this._vectors2[name] = value;
  69648. return this;
  69649. };
  69650. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69651. this._checkUniform(name);
  69652. this._vectors3[name] = value;
  69653. return this;
  69654. };
  69655. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69656. this._checkUniform(name);
  69657. this._matrices[name] = value;
  69658. return this;
  69659. };
  69660. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69661. var scene = this.getScene();
  69662. if (!scene) {
  69663. return;
  69664. }
  69665. var engine = this._engine;
  69666. // Render
  69667. engine.enableEffect(this._effect);
  69668. engine.setState(false);
  69669. // Texture
  69670. for (var name in this._textures) {
  69671. this._effect.setTexture(name, this._textures[name]);
  69672. }
  69673. // Float
  69674. for (name in this._floats) {
  69675. this._effect.setFloat(name, this._floats[name]);
  69676. }
  69677. // Floats
  69678. for (name in this._floatsArrays) {
  69679. this._effect.setArray(name, this._floatsArrays[name]);
  69680. }
  69681. // Color3
  69682. for (name in this._colors3) {
  69683. this._effect.setColor3(name, this._colors3[name]);
  69684. }
  69685. // Color4
  69686. for (name in this._colors4) {
  69687. var color = this._colors4[name];
  69688. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69689. }
  69690. // Vector2
  69691. for (name in this._vectors2) {
  69692. this._effect.setVector2(name, this._vectors2[name]);
  69693. }
  69694. // Vector3
  69695. for (name in this._vectors3) {
  69696. this._effect.setVector3(name, this._vectors3[name]);
  69697. }
  69698. // Matrix
  69699. for (name in this._matrices) {
  69700. this._effect.setMatrix(name, this._matrices[name]);
  69701. }
  69702. if (!this._texture) {
  69703. return;
  69704. }
  69705. if (this.isCube) {
  69706. for (var face = 0; face < 6; face++) {
  69707. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69708. // VBOs
  69709. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69710. this._effect.setFloat("face", face);
  69711. // Clear
  69712. engine.clear(scene.clearColor, true, true, true);
  69713. // Draw order
  69714. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69715. // Mipmaps
  69716. if (face === 5) {
  69717. engine.generateMipMapsForCubemap(this._texture);
  69718. }
  69719. }
  69720. }
  69721. else {
  69722. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69723. // VBOs
  69724. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69725. // Clear
  69726. engine.clear(scene.clearColor, true, true, true);
  69727. // Draw order
  69728. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69729. }
  69730. // Unbind
  69731. engine.unBindFramebuffer(this._texture, this.isCube);
  69732. if (this.onGenerated) {
  69733. this.onGenerated();
  69734. }
  69735. };
  69736. ProceduralTexture.prototype.clone = function () {
  69737. var textureSize = this.getSize();
  69738. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69739. // Base texture
  69740. newTexture.hasAlpha = this.hasAlpha;
  69741. newTexture.level = this.level;
  69742. // RenderTarget Texture
  69743. newTexture.coordinatesMode = this.coordinatesMode;
  69744. return newTexture;
  69745. };
  69746. ProceduralTexture.prototype.dispose = function () {
  69747. var scene = this.getScene();
  69748. if (!scene) {
  69749. return;
  69750. }
  69751. var index = scene.proceduralTextures.indexOf(this);
  69752. if (index >= 0) {
  69753. scene.proceduralTextures.splice(index, 1);
  69754. }
  69755. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69756. if (vertexBuffer) {
  69757. vertexBuffer.dispose();
  69758. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69759. }
  69760. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69761. this._indexBuffer = null;
  69762. }
  69763. _super.prototype.dispose.call(this);
  69764. };
  69765. return ProceduralTexture;
  69766. }(BABYLON.Texture));
  69767. BABYLON.ProceduralTexture = ProceduralTexture;
  69768. })(BABYLON || (BABYLON = {}));
  69769. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69770. var BABYLON;
  69771. (function (BABYLON) {
  69772. var CustomProceduralTexture = /** @class */ (function (_super) {
  69773. __extends(CustomProceduralTexture, _super);
  69774. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69775. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69776. _this._animate = true;
  69777. _this._time = 0;
  69778. _this._texturePath = texturePath;
  69779. //Try to load json
  69780. _this.loadJson(texturePath);
  69781. _this.refreshRate = 1;
  69782. return _this;
  69783. }
  69784. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  69785. var _this = this;
  69786. var noConfigFile = function () {
  69787. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  69788. try {
  69789. _this.setFragment(_this._texturePath);
  69790. }
  69791. catch (ex) {
  69792. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  69793. }
  69794. };
  69795. var configFileUrl = jsonUrl + "/config.json";
  69796. var xhr = new XMLHttpRequest();
  69797. xhr.open("GET", configFileUrl, true);
  69798. xhr.addEventListener("load", function () {
  69799. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69800. try {
  69801. _this._config = JSON.parse(xhr.response);
  69802. _this.updateShaderUniforms();
  69803. _this.updateTextures();
  69804. _this.setFragment(_this._texturePath + "/custom");
  69805. _this._animate = _this._config.animate;
  69806. _this.refreshRate = _this._config.refreshrate;
  69807. }
  69808. catch (ex) {
  69809. noConfigFile();
  69810. }
  69811. }
  69812. else {
  69813. noConfigFile();
  69814. }
  69815. }, false);
  69816. xhr.addEventListener("error", function () {
  69817. noConfigFile();
  69818. }, false);
  69819. try {
  69820. xhr.send();
  69821. }
  69822. catch (ex) {
  69823. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  69824. }
  69825. };
  69826. CustomProceduralTexture.prototype.isReady = function () {
  69827. if (!_super.prototype.isReady.call(this)) {
  69828. return false;
  69829. }
  69830. for (var name in this._textures) {
  69831. var texture = this._textures[name];
  69832. if (!texture.isReady()) {
  69833. return false;
  69834. }
  69835. }
  69836. return true;
  69837. };
  69838. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69839. var scene = this.getScene();
  69840. if (this._animate && scene) {
  69841. this._time += scene.getAnimationRatio() * 0.03;
  69842. this.updateShaderUniforms();
  69843. }
  69844. _super.prototype.render.call(this, useCameraPostProcess);
  69845. };
  69846. CustomProceduralTexture.prototype.updateTextures = function () {
  69847. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  69848. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  69849. }
  69850. };
  69851. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  69852. if (this._config) {
  69853. for (var j = 0; j < this._config.uniforms.length; j++) {
  69854. var uniform = this._config.uniforms[j];
  69855. switch (uniform.type) {
  69856. case "float":
  69857. this.setFloat(uniform.name, uniform.value);
  69858. break;
  69859. case "color3":
  69860. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  69861. break;
  69862. case "color4":
  69863. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  69864. break;
  69865. case "vector2":
  69866. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  69867. break;
  69868. case "vector3":
  69869. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  69870. break;
  69871. }
  69872. }
  69873. }
  69874. this.setFloat("time", this._time);
  69875. };
  69876. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  69877. get: function () {
  69878. return this._animate;
  69879. },
  69880. set: function (value) {
  69881. this._animate = value;
  69882. },
  69883. enumerable: true,
  69884. configurable: true
  69885. });
  69886. return CustomProceduralTexture;
  69887. }(BABYLON.ProceduralTexture));
  69888. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  69889. })(BABYLON || (BABYLON = {}));
  69890. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  69891. var BABYLON;
  69892. (function (BABYLON) {
  69893. var FreeCameraGamepadInput = /** @class */ (function () {
  69894. function FreeCameraGamepadInput() {
  69895. this.gamepadAngularSensibility = 200;
  69896. this.gamepadMoveSensibility = 40;
  69897. // private members
  69898. this._cameraTransform = BABYLON.Matrix.Identity();
  69899. this._deltaTransform = BABYLON.Vector3.Zero();
  69900. this._vector3 = BABYLON.Vector3.Zero();
  69901. this._vector2 = BABYLON.Vector2.Zero();
  69902. }
  69903. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69904. var _this = this;
  69905. var manager = this.camera.getScene().gamepadManager;
  69906. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69907. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69908. // prioritize XBOX gamepads.
  69909. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69910. _this.gamepad = gamepad;
  69911. }
  69912. }
  69913. });
  69914. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69915. if (_this.gamepad === gamepad) {
  69916. _this.gamepad = null;
  69917. }
  69918. });
  69919. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  69920. };
  69921. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  69922. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  69923. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  69924. this.gamepad = null;
  69925. };
  69926. FreeCameraGamepadInput.prototype.checkInputs = function () {
  69927. if (this.gamepad && this.gamepad.leftStick) {
  69928. var camera = this.camera;
  69929. var LSValues = this.gamepad.leftStick;
  69930. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  69931. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  69932. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  69933. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  69934. var RSValues = this.gamepad.rightStick;
  69935. if (RSValues) {
  69936. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  69937. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  69938. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  69939. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  69940. }
  69941. else {
  69942. RSValues = { x: 0, y: 0 };
  69943. }
  69944. if (!camera.rotationQuaternion) {
  69945. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  69946. }
  69947. else {
  69948. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  69949. }
  69950. var speed = camera._computeLocalCameraSpeed() * 50.0;
  69951. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  69952. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  69953. camera.cameraDirection.addInPlace(this._deltaTransform);
  69954. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  69955. camera.cameraRotation.addInPlace(this._vector2);
  69956. }
  69957. };
  69958. FreeCameraGamepadInput.prototype.getClassName = function () {
  69959. return "FreeCameraGamepadInput";
  69960. };
  69961. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  69962. return "gamepad";
  69963. };
  69964. __decorate([
  69965. BABYLON.serialize()
  69966. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  69967. __decorate([
  69968. BABYLON.serialize()
  69969. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  69970. return FreeCameraGamepadInput;
  69971. }());
  69972. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  69973. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  69974. })(BABYLON || (BABYLON = {}));
  69975. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  69976. var BABYLON;
  69977. (function (BABYLON) {
  69978. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  69979. function ArcRotateCameraGamepadInput() {
  69980. this.gamepadRotationSensibility = 80;
  69981. this.gamepadMoveSensibility = 40;
  69982. }
  69983. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  69984. var _this = this;
  69985. var manager = this.camera.getScene().gamepadManager;
  69986. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  69987. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  69988. // prioritize XBOX gamepads.
  69989. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  69990. _this.gamepad = gamepad;
  69991. }
  69992. }
  69993. });
  69994. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  69995. if (_this.gamepad === gamepad) {
  69996. _this.gamepad = null;
  69997. }
  69998. });
  69999. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70000. };
  70001. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70002. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70003. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70004. this.gamepad = null;
  70005. };
  70006. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70007. if (this.gamepad) {
  70008. var camera = this.camera;
  70009. var RSValues = this.gamepad.rightStick;
  70010. if (RSValues) {
  70011. if (RSValues.x != 0) {
  70012. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70013. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70014. camera.inertialAlphaOffset += normalizedRX;
  70015. }
  70016. }
  70017. if (RSValues.y != 0) {
  70018. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70019. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70020. camera.inertialBetaOffset += normalizedRY;
  70021. }
  70022. }
  70023. }
  70024. var LSValues = this.gamepad.leftStick;
  70025. if (LSValues && LSValues.y != 0) {
  70026. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70027. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70028. this.camera.inertialRadiusOffset -= normalizedLY;
  70029. }
  70030. }
  70031. }
  70032. };
  70033. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70034. return "ArcRotateCameraGamepadInput";
  70035. };
  70036. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70037. return "gamepad";
  70038. };
  70039. __decorate([
  70040. BABYLON.serialize()
  70041. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70042. __decorate([
  70043. BABYLON.serialize()
  70044. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70045. return ArcRotateCameraGamepadInput;
  70046. }());
  70047. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70048. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70049. })(BABYLON || (BABYLON = {}));
  70050. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70051. var BABYLON;
  70052. (function (BABYLON) {
  70053. var GamepadManager = /** @class */ (function () {
  70054. function GamepadManager(_scene) {
  70055. var _this = this;
  70056. this._scene = _scene;
  70057. this._babylonGamepads = [];
  70058. this._oneGamepadConnected = false;
  70059. this._isMonitoring = false;
  70060. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70061. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70062. this._gamepadEventSupported = false;
  70063. }
  70064. else {
  70065. this._gamepadEventSupported = 'GamepadEvent' in window;
  70066. this._gamepadSupport = (navigator.getGamepads ||
  70067. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70068. }
  70069. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70070. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70071. for (var i in _this._babylonGamepads) {
  70072. var gamepad = _this._babylonGamepads[i];
  70073. if (gamepad && gamepad._isConnected) {
  70074. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70075. }
  70076. }
  70077. });
  70078. this._onGamepadConnectedEvent = function (evt) {
  70079. var gamepad = evt.gamepad;
  70080. if (gamepad.index in _this._babylonGamepads) {
  70081. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70082. return;
  70083. }
  70084. }
  70085. var newGamepad;
  70086. if (_this._babylonGamepads[gamepad.index]) {
  70087. newGamepad = _this._babylonGamepads[gamepad.index];
  70088. newGamepad.browserGamepad = gamepad;
  70089. newGamepad._isConnected = true;
  70090. }
  70091. else {
  70092. newGamepad = _this._addNewGamepad(gamepad);
  70093. }
  70094. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70095. _this._startMonitoringGamepads();
  70096. };
  70097. this._onGamepadDisconnectedEvent = function (evt) {
  70098. var gamepad = evt.gamepad;
  70099. // Remove the gamepad from the list of gamepads to monitor.
  70100. for (var i in _this._babylonGamepads) {
  70101. if (_this._babylonGamepads[i].index === gamepad.index) {
  70102. var disconnectedGamepad = _this._babylonGamepads[i];
  70103. disconnectedGamepad._isConnected = false;
  70104. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70105. break;
  70106. }
  70107. }
  70108. };
  70109. if (this._gamepadSupport) {
  70110. //first add already-connected gamepads
  70111. this._updateGamepadObjects();
  70112. if (this._babylonGamepads.length) {
  70113. this._startMonitoringGamepads();
  70114. }
  70115. // Checking if the gamepad connected event is supported (like in Firefox)
  70116. if (this._gamepadEventSupported) {
  70117. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70118. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70119. }
  70120. else {
  70121. this._startMonitoringGamepads();
  70122. }
  70123. }
  70124. }
  70125. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70126. get: function () {
  70127. return this._babylonGamepads;
  70128. },
  70129. enumerable: true,
  70130. configurable: true
  70131. });
  70132. GamepadManager.prototype.getGamepadByType = function (type) {
  70133. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70134. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70135. var gamepad = _a[_i];
  70136. if (gamepad && gamepad.type === type) {
  70137. return gamepad;
  70138. }
  70139. }
  70140. return null;
  70141. };
  70142. GamepadManager.prototype.dispose = function () {
  70143. if (this._gamepadEventSupported) {
  70144. if (this._onGamepadConnectedEvent) {
  70145. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70146. }
  70147. if (this._onGamepadDisconnectedEvent) {
  70148. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70149. }
  70150. this._onGamepadConnectedEvent = null;
  70151. this._onGamepadDisconnectedEvent = null;
  70152. }
  70153. this._babylonGamepads.forEach(function (gamepad) {
  70154. gamepad.dispose();
  70155. });
  70156. this.onGamepadConnectedObservable.clear();
  70157. this.onGamepadDisconnectedObservable.clear();
  70158. this._oneGamepadConnected = false;
  70159. this._stopMonitoringGamepads();
  70160. this._babylonGamepads = [];
  70161. };
  70162. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70163. if (!this._oneGamepadConnected) {
  70164. this._oneGamepadConnected = true;
  70165. }
  70166. var newGamepad;
  70167. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70168. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70169. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70170. }
  70171. // if pose is supported, use the (WebVR) pose enabled controller
  70172. else if (gamepad.pose) {
  70173. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70174. }
  70175. else {
  70176. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70177. }
  70178. this._babylonGamepads[newGamepad.index] = newGamepad;
  70179. return newGamepad;
  70180. };
  70181. GamepadManager.prototype._startMonitoringGamepads = function () {
  70182. if (!this._isMonitoring) {
  70183. this._isMonitoring = true;
  70184. //back-comp
  70185. if (!this._scene) {
  70186. this._checkGamepadsStatus();
  70187. }
  70188. }
  70189. };
  70190. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70191. this._isMonitoring = false;
  70192. };
  70193. GamepadManager.prototype._checkGamepadsStatus = function () {
  70194. var _this = this;
  70195. // Hack to be compatible Chrome
  70196. this._updateGamepadObjects();
  70197. for (var i in this._babylonGamepads) {
  70198. var gamepad = this._babylonGamepads[i];
  70199. if (!gamepad || !gamepad.isConnected) {
  70200. continue;
  70201. }
  70202. gamepad.update();
  70203. }
  70204. if (this._isMonitoring && !this._scene) {
  70205. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70206. }
  70207. };
  70208. // This function is called only on Chrome, which does not properly support
  70209. // connection/disconnection events and forces you to recopy again the gamepad object
  70210. GamepadManager.prototype._updateGamepadObjects = function () {
  70211. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70212. for (var i = 0; i < gamepads.length; i++) {
  70213. var gamepad = gamepads[i];
  70214. if (gamepad) {
  70215. if (!this._babylonGamepads[gamepad.index]) {
  70216. var newGamepad = this._addNewGamepad(gamepad);
  70217. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70218. }
  70219. else {
  70220. // Forced to copy again this object for Chrome for unknown reason
  70221. this._babylonGamepads[i].browserGamepad = gamepad;
  70222. if (!this._babylonGamepads[i].isConnected) {
  70223. this._babylonGamepads[i]._isConnected = true;
  70224. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70225. }
  70226. }
  70227. }
  70228. }
  70229. };
  70230. return GamepadManager;
  70231. }());
  70232. BABYLON.GamepadManager = GamepadManager;
  70233. })(BABYLON || (BABYLON = {}));
  70234. //# sourceMappingURL=babylon.gamepadManager.js.map
  70235. var BABYLON;
  70236. (function (BABYLON) {
  70237. var StickValues = /** @class */ (function () {
  70238. function StickValues(x, y) {
  70239. this.x = x;
  70240. this.y = y;
  70241. }
  70242. return StickValues;
  70243. }());
  70244. BABYLON.StickValues = StickValues;
  70245. var Gamepad = /** @class */ (function () {
  70246. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70247. if (leftStickX === void 0) { leftStickX = 0; }
  70248. if (leftStickY === void 0) { leftStickY = 1; }
  70249. if (rightStickX === void 0) { rightStickX = 2; }
  70250. if (rightStickY === void 0) { rightStickY = 3; }
  70251. this.id = id;
  70252. this.index = index;
  70253. this.browserGamepad = browserGamepad;
  70254. this._isConnected = true;
  70255. this._invertLeftStickY = false;
  70256. this.type = Gamepad.GAMEPAD;
  70257. this._leftStickAxisX = leftStickX;
  70258. this._leftStickAxisY = leftStickY;
  70259. this._rightStickAxisX = rightStickX;
  70260. this._rightStickAxisY = rightStickY;
  70261. if (this.browserGamepad.axes.length >= 2) {
  70262. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70263. }
  70264. if (this.browserGamepad.axes.length >= 4) {
  70265. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70266. }
  70267. }
  70268. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70269. get: function () {
  70270. return this._isConnected;
  70271. },
  70272. enumerable: true,
  70273. configurable: true
  70274. });
  70275. Gamepad.prototype.onleftstickchanged = function (callback) {
  70276. this._onleftstickchanged = callback;
  70277. };
  70278. Gamepad.prototype.onrightstickchanged = function (callback) {
  70279. this._onrightstickchanged = callback;
  70280. };
  70281. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70282. get: function () {
  70283. return this._leftStick;
  70284. },
  70285. set: function (newValues) {
  70286. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70287. this._onleftstickchanged(newValues);
  70288. }
  70289. this._leftStick = newValues;
  70290. },
  70291. enumerable: true,
  70292. configurable: true
  70293. });
  70294. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70295. get: function () {
  70296. return this._rightStick;
  70297. },
  70298. set: function (newValues) {
  70299. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70300. this._onrightstickchanged(newValues);
  70301. }
  70302. this._rightStick = newValues;
  70303. },
  70304. enumerable: true,
  70305. configurable: true
  70306. });
  70307. Gamepad.prototype.update = function () {
  70308. if (this._leftStick) {
  70309. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70310. if (this._invertLeftStickY) {
  70311. this.leftStick.y *= -1;
  70312. }
  70313. }
  70314. if (this._rightStick) {
  70315. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70316. }
  70317. };
  70318. Gamepad.prototype.dispose = function () {
  70319. };
  70320. Gamepad.GAMEPAD = 0;
  70321. Gamepad.GENERIC = 1;
  70322. Gamepad.XBOX = 2;
  70323. Gamepad.POSE_ENABLED = 3;
  70324. return Gamepad;
  70325. }());
  70326. BABYLON.Gamepad = Gamepad;
  70327. var GenericPad = /** @class */ (function (_super) {
  70328. __extends(GenericPad, _super);
  70329. function GenericPad(id, index, browserGamepad) {
  70330. var _this = _super.call(this, id, index, browserGamepad) || this;
  70331. _this.onButtonDownObservable = new BABYLON.Observable();
  70332. _this.onButtonUpObservable = new BABYLON.Observable();
  70333. _this.type = Gamepad.GENERIC;
  70334. _this._buttons = new Array(browserGamepad.buttons.length);
  70335. return _this;
  70336. }
  70337. GenericPad.prototype.onbuttondown = function (callback) {
  70338. this._onbuttondown = callback;
  70339. };
  70340. GenericPad.prototype.onbuttonup = function (callback) {
  70341. this._onbuttonup = callback;
  70342. };
  70343. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70344. if (newValue !== currentValue) {
  70345. if (newValue === 1) {
  70346. if (this._onbuttondown) {
  70347. this._onbuttondown(buttonIndex);
  70348. }
  70349. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70350. }
  70351. if (newValue === 0) {
  70352. if (this._onbuttonup) {
  70353. this._onbuttonup(buttonIndex);
  70354. }
  70355. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70356. }
  70357. }
  70358. return newValue;
  70359. };
  70360. GenericPad.prototype.update = function () {
  70361. _super.prototype.update.call(this);
  70362. for (var index = 0; index < this._buttons.length; index++) {
  70363. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70364. }
  70365. };
  70366. GenericPad.prototype.dispose = function () {
  70367. _super.prototype.dispose.call(this);
  70368. this.onButtonDownObservable.clear();
  70369. this.onButtonUpObservable.clear();
  70370. };
  70371. return GenericPad;
  70372. }(Gamepad));
  70373. BABYLON.GenericPad = GenericPad;
  70374. })(BABYLON || (BABYLON = {}));
  70375. //# sourceMappingURL=babylon.gamepad.js.map
  70376. var BABYLON;
  70377. (function (BABYLON) {
  70378. /**
  70379. * Defines supported buttons for XBox360 compatible gamepads
  70380. */
  70381. var Xbox360Button;
  70382. (function (Xbox360Button) {
  70383. /** A */
  70384. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70385. /** B */
  70386. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70387. /** X */
  70388. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70389. /** Y */
  70390. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70391. /** Start */
  70392. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70393. /** Back */
  70394. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70395. /** Left button */
  70396. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70397. /** Right button */
  70398. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70399. /** Left stick */
  70400. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70401. /** Right stick */
  70402. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70403. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70404. /** Defines values for XBox360 DPad */
  70405. var Xbox360Dpad;
  70406. (function (Xbox360Dpad) {
  70407. /** Up */
  70408. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70409. /** Down */
  70410. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70411. /** Left */
  70412. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70413. /** Right */
  70414. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70415. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70416. /**
  70417. * Defines a XBox360 gamepad
  70418. */
  70419. var Xbox360Pad = /** @class */ (function (_super) {
  70420. __extends(Xbox360Pad, _super);
  70421. /**
  70422. * Creates a new XBox360 gamepad object
  70423. * @param id defines the id of this gamepad
  70424. * @param index defines its index
  70425. * @param gamepad defines the internal HTML gamepad object
  70426. * @param xboxOne defines if it is a XBox One gamepad
  70427. */
  70428. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70429. if (xboxOne === void 0) { xboxOne = false; }
  70430. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70431. _this._leftTrigger = 0;
  70432. _this._rightTrigger = 0;
  70433. /** Observable raised when a button is pressed */
  70434. _this.onButtonDownObservable = new BABYLON.Observable();
  70435. /** Observable raised when a button is released */
  70436. _this.onButtonUpObservable = new BABYLON.Observable();
  70437. /** Observable raised when a pad is pressed */
  70438. _this.onPadDownObservable = new BABYLON.Observable();
  70439. /** Observable raised when a pad is released */
  70440. _this.onPadUpObservable = new BABYLON.Observable();
  70441. _this._buttonA = 0;
  70442. _this._buttonB = 0;
  70443. _this._buttonX = 0;
  70444. _this._buttonY = 0;
  70445. _this._buttonBack = 0;
  70446. _this._buttonStart = 0;
  70447. _this._buttonLB = 0;
  70448. _this._buttonRB = 0;
  70449. _this._buttonLeftStick = 0;
  70450. _this._buttonRightStick = 0;
  70451. _this._dPadUp = 0;
  70452. _this._dPadDown = 0;
  70453. _this._dPadLeft = 0;
  70454. _this._dPadRight = 0;
  70455. _this._isXboxOnePad = false;
  70456. _this.type = BABYLON.Gamepad.XBOX;
  70457. _this._isXboxOnePad = xboxOne;
  70458. return _this;
  70459. }
  70460. /**
  70461. * Defines the callback to call when left trigger is pressed
  70462. * @param callback defines the callback to use
  70463. */
  70464. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70465. this._onlefttriggerchanged = callback;
  70466. };
  70467. /**
  70468. * Defines the callback to call when right trigger is pressed
  70469. * @param callback defines the callback to use
  70470. */
  70471. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70472. this._onrighttriggerchanged = callback;
  70473. };
  70474. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70475. /**
  70476. * Gets or sets left trigger value
  70477. */
  70478. get: function () {
  70479. return this._leftTrigger;
  70480. },
  70481. set: function (newValue) {
  70482. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70483. this._onlefttriggerchanged(newValue);
  70484. }
  70485. this._leftTrigger = newValue;
  70486. },
  70487. enumerable: true,
  70488. configurable: true
  70489. });
  70490. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70491. /**
  70492. * Gets or sets right trigger value
  70493. */
  70494. get: function () {
  70495. return this._rightTrigger;
  70496. },
  70497. set: function (newValue) {
  70498. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70499. this._onrighttriggerchanged(newValue);
  70500. }
  70501. this._rightTrigger = newValue;
  70502. },
  70503. enumerable: true,
  70504. configurable: true
  70505. });
  70506. /**
  70507. * Defines the callback to call when a button is pressed
  70508. * @param callback defines the callback to use
  70509. */
  70510. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70511. this._onbuttondown = callback;
  70512. };
  70513. /**
  70514. * Defines the callback to call when a button is released
  70515. * @param callback defines the callback to use
  70516. */
  70517. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70518. this._onbuttonup = callback;
  70519. };
  70520. /**
  70521. * Defines the callback to call when a pad is pressed
  70522. * @param callback defines the callback to use
  70523. */
  70524. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70525. this._ondpaddown = callback;
  70526. };
  70527. /**
  70528. * Defines the callback to call when a pad is released
  70529. * @param callback defines the callback to use
  70530. */
  70531. Xbox360Pad.prototype.ondpadup = function (callback) {
  70532. this._ondpadup = callback;
  70533. };
  70534. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70535. if (newValue !== currentValue) {
  70536. if (newValue === 1) {
  70537. if (this._onbuttondown) {
  70538. this._onbuttondown(buttonType);
  70539. }
  70540. this.onButtonDownObservable.notifyObservers(buttonType);
  70541. }
  70542. if (newValue === 0) {
  70543. if (this._onbuttonup) {
  70544. this._onbuttonup(buttonType);
  70545. }
  70546. this.onButtonUpObservable.notifyObservers(buttonType);
  70547. }
  70548. }
  70549. return newValue;
  70550. };
  70551. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70552. if (newValue !== currentValue) {
  70553. if (newValue === 1) {
  70554. if (this._ondpaddown) {
  70555. this._ondpaddown(buttonType);
  70556. }
  70557. this.onPadDownObservable.notifyObservers(buttonType);
  70558. }
  70559. if (newValue === 0) {
  70560. if (this._ondpadup) {
  70561. this._ondpadup(buttonType);
  70562. }
  70563. this.onPadUpObservable.notifyObservers(buttonType);
  70564. }
  70565. }
  70566. return newValue;
  70567. };
  70568. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70569. /** Gets or sets value of A button */
  70570. get: function () {
  70571. return this._buttonA;
  70572. },
  70573. set: function (value) {
  70574. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70575. },
  70576. enumerable: true,
  70577. configurable: true
  70578. });
  70579. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70580. /** Gets or sets value of B button */
  70581. get: function () {
  70582. return this._buttonB;
  70583. },
  70584. set: function (value) {
  70585. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70586. },
  70587. enumerable: true,
  70588. configurable: true
  70589. });
  70590. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70591. /** Gets or sets value of X button */
  70592. get: function () {
  70593. return this._buttonX;
  70594. },
  70595. set: function (value) {
  70596. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70597. },
  70598. enumerable: true,
  70599. configurable: true
  70600. });
  70601. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70602. /** Gets or sets value of Y button */
  70603. get: function () {
  70604. return this._buttonY;
  70605. },
  70606. set: function (value) {
  70607. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70608. },
  70609. enumerable: true,
  70610. configurable: true
  70611. });
  70612. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70613. /** Gets or sets value of Start button */
  70614. get: function () {
  70615. return this._buttonStart;
  70616. },
  70617. set: function (value) {
  70618. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70619. },
  70620. enumerable: true,
  70621. configurable: true
  70622. });
  70623. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70624. /** Gets or sets value of Back button */
  70625. get: function () {
  70626. return this._buttonBack;
  70627. },
  70628. set: function (value) {
  70629. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70630. },
  70631. enumerable: true,
  70632. configurable: true
  70633. });
  70634. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70635. /** Gets or sets value of Left button */
  70636. get: function () {
  70637. return this._buttonLB;
  70638. },
  70639. set: function (value) {
  70640. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70641. },
  70642. enumerable: true,
  70643. configurable: true
  70644. });
  70645. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70646. /** Gets or sets value of Right button */
  70647. get: function () {
  70648. return this._buttonRB;
  70649. },
  70650. set: function (value) {
  70651. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70652. },
  70653. enumerable: true,
  70654. configurable: true
  70655. });
  70656. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70657. /** Gets or sets value of left stick */
  70658. get: function () {
  70659. return this._buttonLeftStick;
  70660. },
  70661. set: function (value) {
  70662. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70663. },
  70664. enumerable: true,
  70665. configurable: true
  70666. });
  70667. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70668. /** Gets or sets value of right stick */
  70669. get: function () {
  70670. return this._buttonRightStick;
  70671. },
  70672. set: function (value) {
  70673. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70674. },
  70675. enumerable: true,
  70676. configurable: true
  70677. });
  70678. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70679. /** Gets or sets value of DPad up */
  70680. get: function () {
  70681. return this._dPadUp;
  70682. },
  70683. set: function (value) {
  70684. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70685. },
  70686. enumerable: true,
  70687. configurable: true
  70688. });
  70689. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70690. /** Gets or sets value of DPad down */
  70691. get: function () {
  70692. return this._dPadDown;
  70693. },
  70694. set: function (value) {
  70695. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70696. },
  70697. enumerable: true,
  70698. configurable: true
  70699. });
  70700. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70701. /** Gets or sets value of DPad left */
  70702. get: function () {
  70703. return this._dPadLeft;
  70704. },
  70705. set: function (value) {
  70706. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70707. },
  70708. enumerable: true,
  70709. configurable: true
  70710. });
  70711. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70712. /** Gets or sets value of DPad right */
  70713. get: function () {
  70714. return this._dPadRight;
  70715. },
  70716. set: function (value) {
  70717. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70718. },
  70719. enumerable: true,
  70720. configurable: true
  70721. });
  70722. /**
  70723. * Force the gamepad to synchronize with device values
  70724. */
  70725. Xbox360Pad.prototype.update = function () {
  70726. _super.prototype.update.call(this);
  70727. if (this._isXboxOnePad) {
  70728. this.buttonA = this.browserGamepad.buttons[0].value;
  70729. this.buttonB = this.browserGamepad.buttons[1].value;
  70730. this.buttonX = this.browserGamepad.buttons[2].value;
  70731. this.buttonY = this.browserGamepad.buttons[3].value;
  70732. this.buttonLB = this.browserGamepad.buttons[4].value;
  70733. this.buttonRB = this.browserGamepad.buttons[5].value;
  70734. this.leftTrigger = this.browserGamepad.axes[2];
  70735. this.rightTrigger = this.browserGamepad.axes[5];
  70736. this.buttonBack = this.browserGamepad.buttons[9].value;
  70737. this.buttonStart = this.browserGamepad.buttons[8].value;
  70738. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70739. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70740. this.dPadUp = this.browserGamepad.buttons[11].value;
  70741. this.dPadDown = this.browserGamepad.buttons[12].value;
  70742. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70743. this.dPadRight = this.browserGamepad.buttons[14].value;
  70744. }
  70745. else {
  70746. this.buttonA = this.browserGamepad.buttons[0].value;
  70747. this.buttonB = this.browserGamepad.buttons[1].value;
  70748. this.buttonX = this.browserGamepad.buttons[2].value;
  70749. this.buttonY = this.browserGamepad.buttons[3].value;
  70750. this.buttonLB = this.browserGamepad.buttons[4].value;
  70751. this.buttonRB = this.browserGamepad.buttons[5].value;
  70752. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70753. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70754. this.buttonBack = this.browserGamepad.buttons[8].value;
  70755. this.buttonStart = this.browserGamepad.buttons[9].value;
  70756. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70757. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70758. this.dPadUp = this.browserGamepad.buttons[12].value;
  70759. this.dPadDown = this.browserGamepad.buttons[13].value;
  70760. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70761. this.dPadRight = this.browserGamepad.buttons[15].value;
  70762. }
  70763. };
  70764. Xbox360Pad.prototype.dispose = function () {
  70765. _super.prototype.dispose.call(this);
  70766. this.onButtonDownObservable.clear();
  70767. this.onButtonUpObservable.clear();
  70768. this.onPadDownObservable.clear();
  70769. this.onPadUpObservable.clear();
  70770. };
  70771. return Xbox360Pad;
  70772. }(BABYLON.Gamepad));
  70773. BABYLON.Xbox360Pad = Xbox360Pad;
  70774. })(BABYLON || (BABYLON = {}));
  70775. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70776. var BABYLON;
  70777. (function (BABYLON) {
  70778. /**
  70779. * Defines the types of pose enabled controllers that are supported
  70780. */
  70781. var PoseEnabledControllerType;
  70782. (function (PoseEnabledControllerType) {
  70783. /**
  70784. * HTC Vive
  70785. */
  70786. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  70787. /**
  70788. * Oculus Rift
  70789. */
  70790. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  70791. /**
  70792. * Windows mixed reality
  70793. */
  70794. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  70795. /**
  70796. * Samsung gear VR
  70797. */
  70798. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  70799. /**
  70800. * Google Daydream
  70801. */
  70802. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  70803. /**
  70804. * Generic
  70805. */
  70806. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  70807. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  70808. /**
  70809. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70810. */
  70811. var PoseEnabledControllerHelper = /** @class */ (function () {
  70812. function PoseEnabledControllerHelper() {
  70813. }
  70814. /**
  70815. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70816. * @param vrGamepad the gamepad to initialized
  70817. * @returns a vr controller of the type the gamepad identified as
  70818. */
  70819. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  70820. // Oculus Touch
  70821. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  70822. return new BABYLON.OculusTouchController(vrGamepad);
  70823. }
  70824. // Windows Mixed Reality controllers
  70825. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  70826. return new BABYLON.WindowsMotionController(vrGamepad);
  70827. }
  70828. // HTC Vive
  70829. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  70830. return new BABYLON.ViveController(vrGamepad);
  70831. }
  70832. // Samsung/Oculus Gear VR
  70833. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  70834. return new BABYLON.GearVRController(vrGamepad);
  70835. }
  70836. // Google Daydream
  70837. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  70838. return new BABYLON.DaydreamController(vrGamepad);
  70839. }
  70840. // Generic
  70841. else {
  70842. return new BABYLON.GenericController(vrGamepad);
  70843. }
  70844. };
  70845. return PoseEnabledControllerHelper;
  70846. }());
  70847. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  70848. /**
  70849. * Defines the PoseEnabledController object that contains state of a vr capable controller
  70850. */
  70851. var PoseEnabledController = /** @class */ (function (_super) {
  70852. __extends(PoseEnabledController, _super);
  70853. /**
  70854. * Creates a new PoseEnabledController from a gamepad
  70855. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  70856. */
  70857. function PoseEnabledController(browserGamepad) {
  70858. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  70859. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  70860. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  70861. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  70862. /**
  70863. * The device position in babylon space
  70864. */
  70865. _this.devicePosition = BABYLON.Vector3.Zero();
  70866. /**
  70867. * The device rotation in babylon space
  70868. */
  70869. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  70870. /**
  70871. * The scale factor of the device in babylon space
  70872. */
  70873. _this.deviceScaleFactor = 1;
  70874. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  70875. /**
  70876. * Internal, matrix used to convert room space to babylon space
  70877. */
  70878. _this._deviceToWorld = BABYLON.Matrix.Identity();
  70879. /**
  70880. * Node to be used when casting a ray from the controller
  70881. */
  70882. _this._pointingPoseNode = null;
  70883. _this._workingMatrix = BABYLON.Matrix.Identity();
  70884. /**
  70885. * @hidden
  70886. */
  70887. _this._meshAttachedObservable = new BABYLON.Observable();
  70888. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  70889. _this.controllerType = PoseEnabledControllerType.GENERIC;
  70890. _this.position = BABYLON.Vector3.Zero();
  70891. _this.rotationQuaternion = new BABYLON.Quaternion();
  70892. _this._calculatedPosition = BABYLON.Vector3.Zero();
  70893. _this._calculatedRotation = new BABYLON.Quaternion();
  70894. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  70895. return _this;
  70896. }
  70897. /**
  70898. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  70899. */
  70900. PoseEnabledController.prototype.update = function () {
  70901. _super.prototype.update.call(this);
  70902. var pose = this.browserGamepad.pose;
  70903. this.updateFromDevice(pose);
  70904. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  70905. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  70906. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  70907. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  70908. if (this._mesh) {
  70909. this._mesh.position.copyFrom(this.devicePosition);
  70910. if (this._mesh.rotationQuaternion) {
  70911. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  70912. }
  70913. }
  70914. };
  70915. /**
  70916. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  70917. * @param poseData raw pose fromthe device
  70918. */
  70919. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  70920. if (poseData) {
  70921. this.rawPose = poseData;
  70922. if (poseData.position) {
  70923. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  70924. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  70925. this._deviceRoomPosition.z *= -1;
  70926. }
  70927. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  70928. this._calculatedPosition.addInPlace(this.position);
  70929. }
  70930. var pose = this.rawPose;
  70931. if (poseData.orientation && pose.orientation) {
  70932. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  70933. if (this._mesh) {
  70934. if (this._mesh.getScene().useRightHandedSystem) {
  70935. this._deviceRoomRotationQuaternion.z *= -1;
  70936. this._deviceRoomRotationQuaternion.w *= -1;
  70937. }
  70938. else {
  70939. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  70940. }
  70941. }
  70942. // if the camera is set, rotate to the camera's rotation
  70943. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  70944. }
  70945. }
  70946. };
  70947. /**
  70948. * Attaches a mesh to the controller
  70949. * @param mesh the mesh to be attached
  70950. */
  70951. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  70952. if (this._mesh) {
  70953. this._mesh.parent = null;
  70954. }
  70955. this._mesh = mesh;
  70956. if (this._poseControlledCamera) {
  70957. this._mesh.parent = this._poseControlledCamera;
  70958. }
  70959. if (!this._mesh.rotationQuaternion) {
  70960. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  70961. }
  70962. this._meshAttachedObservable.notifyObservers(mesh);
  70963. };
  70964. /**
  70965. * Attaches the controllers mesh to a camera
  70966. * @param camera the camera the mesh should be attached to
  70967. */
  70968. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  70969. this._poseControlledCamera = camera;
  70970. if (this._mesh) {
  70971. this._mesh.parent = this._poseControlledCamera;
  70972. }
  70973. };
  70974. /**
  70975. * Disposes of the controller
  70976. */
  70977. PoseEnabledController.prototype.dispose = function () {
  70978. if (this._mesh) {
  70979. this._mesh.dispose();
  70980. }
  70981. this._mesh = null;
  70982. _super.prototype.dispose.call(this);
  70983. };
  70984. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  70985. /**
  70986. * The mesh that is attached to the controller
  70987. */
  70988. get: function () {
  70989. return this._mesh;
  70990. },
  70991. enumerable: true,
  70992. configurable: true
  70993. });
  70994. /**
  70995. * Gets the ray of the controller in the direction the controller is pointing
  70996. * @param length the length the resulting ray should be
  70997. * @returns a ray in the direction the controller is pointing
  70998. */
  70999. PoseEnabledController.prototype.getForwardRay = function (length) {
  71000. if (length === void 0) { length = 100; }
  71001. if (!this.mesh) {
  71002. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71003. }
  71004. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71005. var origin = m.getTranslation();
  71006. var forward = new BABYLON.Vector3(0, 0, -1);
  71007. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71008. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71009. return new BABYLON.Ray(origin, direction, length);
  71010. };
  71011. /**
  71012. * Name of the child mesh that can be used to cast a ray from the controller
  71013. */
  71014. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71015. return PoseEnabledController;
  71016. }(BABYLON.Gamepad));
  71017. BABYLON.PoseEnabledController = PoseEnabledController;
  71018. })(BABYLON || (BABYLON = {}));
  71019. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71020. var BABYLON;
  71021. (function (BABYLON) {
  71022. /**
  71023. * Defines the WebVRController object that represents controllers tracked in 3D space
  71024. */
  71025. var WebVRController = /** @class */ (function (_super) {
  71026. __extends(WebVRController, _super);
  71027. /**
  71028. * Creates a new WebVRController from a gamepad
  71029. * @param vrGamepad the gamepad that the WebVRController should be created from
  71030. */
  71031. function WebVRController(vrGamepad) {
  71032. var _this = _super.call(this, vrGamepad) || this;
  71033. // Observables
  71034. /**
  71035. * Fired when the trigger state has changed
  71036. */
  71037. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71038. /**
  71039. * Fired when the main button state has changed
  71040. */
  71041. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71042. /**
  71043. * Fired when the secondary button state has changed
  71044. */
  71045. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71046. /**
  71047. * Fired when the pad state has changed
  71048. */
  71049. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71050. /**
  71051. * Fired when controllers stick values have changed
  71052. */
  71053. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71054. /**
  71055. * X and Y axis corrisponding to the controllers joystick
  71056. */
  71057. _this.pad = { x: 0, y: 0 };
  71058. // avoid GC, store state in a tmp object
  71059. _this._changes = {
  71060. pressChanged: false,
  71061. touchChanged: false,
  71062. valueChanged: false,
  71063. changed: false
  71064. };
  71065. _this._buttons = new Array(vrGamepad.buttons.length);
  71066. _this.hand = vrGamepad.hand;
  71067. return _this;
  71068. }
  71069. /**
  71070. * Fired when a controller button's state has changed
  71071. * @param callback the callback containing the button that was modified
  71072. */
  71073. WebVRController.prototype.onButtonStateChange = function (callback) {
  71074. this._onButtonStateChange = callback;
  71075. };
  71076. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71077. /**
  71078. * The default controller model for the controller
  71079. */
  71080. get: function () {
  71081. return this._defaultModel;
  71082. },
  71083. enumerable: true,
  71084. configurable: true
  71085. });
  71086. /**
  71087. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71088. */
  71089. WebVRController.prototype.update = function () {
  71090. _super.prototype.update.call(this);
  71091. for (var index = 0; index < this._buttons.length; index++) {
  71092. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71093. }
  71094. ;
  71095. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71096. this.pad.x = this.leftStick.x;
  71097. this.pad.y = this.leftStick.y;
  71098. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71099. }
  71100. };
  71101. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71102. if (!newState) {
  71103. newState = {
  71104. pressed: false,
  71105. touched: false,
  71106. value: 0
  71107. };
  71108. }
  71109. if (!currentState) {
  71110. this._buttons[buttonIndex] = {
  71111. pressed: newState.pressed,
  71112. touched: newState.touched,
  71113. value: newState.value
  71114. };
  71115. return;
  71116. }
  71117. this._checkChanges(newState, currentState);
  71118. if (this._changes.changed) {
  71119. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71120. this._handleButtonChange(buttonIndex, newState, this._changes);
  71121. }
  71122. this._buttons[buttonIndex].pressed = newState.pressed;
  71123. this._buttons[buttonIndex].touched = newState.touched;
  71124. // oculus triggers are never 0, thou not touched.
  71125. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71126. };
  71127. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71128. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71129. this._changes.touchChanged = newState.touched !== currentState.touched;
  71130. this._changes.valueChanged = newState.value !== currentState.value;
  71131. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71132. return this._changes;
  71133. };
  71134. /**
  71135. * Disposes of th webVRCOntroller
  71136. */
  71137. WebVRController.prototype.dispose = function () {
  71138. _super.prototype.dispose.call(this);
  71139. this.onTriggerStateChangedObservable.clear();
  71140. this.onMainButtonStateChangedObservable.clear();
  71141. this.onSecondaryButtonStateChangedObservable.clear();
  71142. this.onPadStateChangedObservable.clear();
  71143. this.onPadValuesChangedObservable.clear();
  71144. };
  71145. return WebVRController;
  71146. }(BABYLON.PoseEnabledController));
  71147. BABYLON.WebVRController = WebVRController;
  71148. })(BABYLON || (BABYLON = {}));
  71149. //# sourceMappingURL=babylon.webVRController.js.map
  71150. var BABYLON;
  71151. (function (BABYLON) {
  71152. /**
  71153. * Oculus Touch Controller
  71154. */
  71155. var OculusTouchController = /** @class */ (function (_super) {
  71156. __extends(OculusTouchController, _super);
  71157. /**
  71158. * Creates a new OculusTouchController from a gamepad
  71159. * @param vrGamepad the gamepad that the controller should be created from
  71160. */
  71161. function OculusTouchController(vrGamepad) {
  71162. var _this = _super.call(this, vrGamepad) || this;
  71163. /**
  71164. * Fired when the secondary trigger on this controller is modified
  71165. */
  71166. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71167. /**
  71168. * Fired when the thumb rest on this controller is modified
  71169. */
  71170. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71171. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71172. return _this;
  71173. }
  71174. /**
  71175. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71176. * @param scene scene in which to add meshes
  71177. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71178. */
  71179. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71180. var _this = this;
  71181. var meshName;
  71182. // Hand
  71183. if (this.hand === 'left') {
  71184. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71185. }
  71186. else { // Right is the default if no hand is specified
  71187. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71188. }
  71189. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71190. /*
  71191. Parent Mesh name: oculus_touch_left
  71192. - body
  71193. - trigger
  71194. - thumbstick
  71195. - grip
  71196. - button_y
  71197. - button_x
  71198. - button_enter
  71199. */
  71200. _this._defaultModel = newMeshes[1];
  71201. _this.attachToMesh(_this._defaultModel);
  71202. if (meshLoaded) {
  71203. meshLoaded(_this._defaultModel);
  71204. }
  71205. });
  71206. };
  71207. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71208. /**
  71209. * Fired when the A button on this controller is modified
  71210. */
  71211. get: function () {
  71212. if (this.hand === 'right') {
  71213. return this.onMainButtonStateChangedObservable;
  71214. }
  71215. else {
  71216. throw new Error('No A button on left hand');
  71217. }
  71218. },
  71219. enumerable: true,
  71220. configurable: true
  71221. });
  71222. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71223. /**
  71224. * Fired when the B button on this controller is modified
  71225. */
  71226. get: function () {
  71227. if (this.hand === 'right') {
  71228. return this.onSecondaryButtonStateChangedObservable;
  71229. }
  71230. else {
  71231. throw new Error('No B button on left hand');
  71232. }
  71233. },
  71234. enumerable: true,
  71235. configurable: true
  71236. });
  71237. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71238. /**
  71239. * Fired when the X button on this controller is modified
  71240. */
  71241. get: function () {
  71242. if (this.hand === 'left') {
  71243. return this.onMainButtonStateChangedObservable;
  71244. }
  71245. else {
  71246. throw new Error('No X button on right hand');
  71247. }
  71248. },
  71249. enumerable: true,
  71250. configurable: true
  71251. });
  71252. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71253. /**
  71254. * Fired when the Y button on this controller is modified
  71255. */
  71256. get: function () {
  71257. if (this.hand === 'left') {
  71258. return this.onSecondaryButtonStateChangedObservable;
  71259. }
  71260. else {
  71261. throw new Error('No Y button on right hand');
  71262. }
  71263. },
  71264. enumerable: true,
  71265. configurable: true
  71266. });
  71267. /**
  71268. * Called once for each button that changed state since the last frame
  71269. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71270. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71271. * 2) secondary trigger (same)
  71272. * 3) A (right) X (left), touch, pressed = value
  71273. * 4) B / Y
  71274. * 5) thumb rest
  71275. * @param buttonIdx Which button index changed
  71276. * @param state New state of the button
  71277. * @param changes Which properties on the state changed since last frame
  71278. */
  71279. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71280. var notifyObject = state; //{ state: state, changes: changes };
  71281. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71282. switch (buttonIdx) {
  71283. case 0:
  71284. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71285. return;
  71286. case 1: // index trigger
  71287. if (this._defaultModel) {
  71288. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71289. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71290. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71291. }
  71292. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71293. return;
  71294. case 2: // secondary trigger
  71295. if (this._defaultModel) {
  71296. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71297. }
  71298. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71299. return;
  71300. case 3:
  71301. if (this._defaultModel) {
  71302. if (notifyObject.pressed) {
  71303. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71304. }
  71305. else {
  71306. (this._defaultModel.getChildren()[1]).position.y = 0;
  71307. }
  71308. }
  71309. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71310. return;
  71311. case 4:
  71312. if (this._defaultModel) {
  71313. if (notifyObject.pressed) {
  71314. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71315. }
  71316. else {
  71317. (this._defaultModel.getChildren()[2]).position.y = 0;
  71318. }
  71319. }
  71320. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71321. return;
  71322. case 5:
  71323. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71324. return;
  71325. }
  71326. };
  71327. /**
  71328. * Base Url for the controller model.
  71329. */
  71330. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71331. /**
  71332. * File name for the left controller model.
  71333. */
  71334. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71335. /**
  71336. * File name for the right controller model.
  71337. */
  71338. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71339. return OculusTouchController;
  71340. }(BABYLON.WebVRController));
  71341. BABYLON.OculusTouchController = OculusTouchController;
  71342. })(BABYLON || (BABYLON = {}));
  71343. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71344. var BABYLON;
  71345. (function (BABYLON) {
  71346. /**
  71347. * Vive Controller
  71348. */
  71349. var ViveController = /** @class */ (function (_super) {
  71350. __extends(ViveController, _super);
  71351. /**
  71352. * Creates a new ViveController from a gamepad
  71353. * @param vrGamepad the gamepad that the controller should be created from
  71354. */
  71355. function ViveController(vrGamepad) {
  71356. var _this = _super.call(this, vrGamepad) || this;
  71357. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71358. _this._invertLeftStickY = true;
  71359. return _this;
  71360. }
  71361. /**
  71362. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71363. * @param scene scene in which to add meshes
  71364. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71365. */
  71366. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71367. var _this = this;
  71368. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71369. /*
  71370. Parent Mesh name: ViveWand
  71371. - body
  71372. - r_gripper
  71373. - l_gripper
  71374. - menu_button
  71375. - system_button
  71376. - trackpad
  71377. - trigger
  71378. - LED
  71379. */
  71380. _this._defaultModel = newMeshes[1];
  71381. _this.attachToMesh(_this._defaultModel);
  71382. if (meshLoaded) {
  71383. meshLoaded(_this._defaultModel);
  71384. }
  71385. });
  71386. };
  71387. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71388. /**
  71389. * Fired when the left button on this controller is modified
  71390. */
  71391. get: function () {
  71392. return this.onMainButtonStateChangedObservable;
  71393. },
  71394. enumerable: true,
  71395. configurable: true
  71396. });
  71397. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71398. /**
  71399. * Fired when the right button on this controller is modified
  71400. */
  71401. get: function () {
  71402. return this.onMainButtonStateChangedObservable;
  71403. },
  71404. enumerable: true,
  71405. configurable: true
  71406. });
  71407. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71408. /**
  71409. * Fired when the menu button on this controller is modified
  71410. */
  71411. get: function () {
  71412. return this.onSecondaryButtonStateChangedObservable;
  71413. },
  71414. enumerable: true,
  71415. configurable: true
  71416. });
  71417. /**
  71418. * Called once for each button that changed state since the last frame
  71419. * Vive mapping:
  71420. * 0: touchpad
  71421. * 1: trigger
  71422. * 2: left AND right buttons
  71423. * 3: menu button
  71424. * @param buttonIdx Which button index changed
  71425. * @param state New state of the button
  71426. * @param changes Which properties on the state changed since last frame
  71427. */
  71428. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71429. var notifyObject = state; //{ state: state, changes: changes };
  71430. switch (buttonIdx) {
  71431. case 0:
  71432. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71433. return;
  71434. case 1: // index trigger
  71435. if (this._defaultModel) {
  71436. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71437. }
  71438. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71439. return;
  71440. case 2: // left AND right button
  71441. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71442. return;
  71443. case 3:
  71444. if (this._defaultModel) {
  71445. if (notifyObject.pressed) {
  71446. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71447. }
  71448. else {
  71449. (this._defaultModel.getChildren()[2]).position.y = 0;
  71450. }
  71451. }
  71452. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71453. return;
  71454. }
  71455. };
  71456. /**
  71457. * Base Url for the controller model.
  71458. */
  71459. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71460. /**
  71461. * File name for the controller model.
  71462. */
  71463. ViveController.MODEL_FILENAME = 'wand.babylon';
  71464. return ViveController;
  71465. }(BABYLON.WebVRController));
  71466. BABYLON.ViveController = ViveController;
  71467. })(BABYLON || (BABYLON = {}));
  71468. //# sourceMappingURL=babylon.viveController.js.map
  71469. var BABYLON;
  71470. (function (BABYLON) {
  71471. /**
  71472. * Generic Controller
  71473. */
  71474. var GenericController = /** @class */ (function (_super) {
  71475. __extends(GenericController, _super);
  71476. /**
  71477. * Creates a new GenericController from a gamepad
  71478. * @param vrGamepad the gamepad that the controller should be created from
  71479. */
  71480. function GenericController(vrGamepad) {
  71481. return _super.call(this, vrGamepad) || this;
  71482. }
  71483. /**
  71484. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71485. * @param scene scene in which to add meshes
  71486. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71487. */
  71488. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71489. var _this = this;
  71490. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71491. _this._defaultModel = newMeshes[1];
  71492. _this.attachToMesh(_this._defaultModel);
  71493. if (meshLoaded) {
  71494. meshLoaded(_this._defaultModel);
  71495. }
  71496. });
  71497. };
  71498. /**
  71499. * Called once for each button that changed state since the last frame
  71500. * @param buttonIdx Which button index changed
  71501. * @param state New state of the button
  71502. * @param changes Which properties on the state changed since last frame
  71503. */
  71504. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71505. console.log("Button id: " + buttonIdx + "state: ");
  71506. console.dir(state);
  71507. };
  71508. /**
  71509. * Base Url for the controller model.
  71510. */
  71511. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71512. /**
  71513. * File name for the controller model.
  71514. */
  71515. GenericController.MODEL_FILENAME = 'generic.babylon';
  71516. return GenericController;
  71517. }(BABYLON.WebVRController));
  71518. BABYLON.GenericController = GenericController;
  71519. })(BABYLON || (BABYLON = {}));
  71520. //# sourceMappingURL=babylon.genericController.js.map
  71521. var BABYLON;
  71522. (function (BABYLON) {
  71523. /**
  71524. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71525. */
  71526. var LoadedMeshInfo = /** @class */ (function () {
  71527. function LoadedMeshInfo() {
  71528. /**
  71529. * Map of the button meshes contained in the controller
  71530. */
  71531. this.buttonMeshes = {};
  71532. /**
  71533. * Map of the axis meshes contained in the controller
  71534. */
  71535. this.axisMeshes = {};
  71536. }
  71537. return LoadedMeshInfo;
  71538. }());
  71539. /**
  71540. * Defines the WindowsMotionController object that the state of the windows motion controller
  71541. */
  71542. var WindowsMotionController = /** @class */ (function (_super) {
  71543. __extends(WindowsMotionController, _super);
  71544. /**
  71545. * Creates a new WindowsMotionController from a gamepad
  71546. * @param vrGamepad the gamepad that the controller should be created from
  71547. */
  71548. function WindowsMotionController(vrGamepad) {
  71549. var _this = _super.call(this, vrGamepad) || this;
  71550. _this._mapping = {
  71551. // Semantic button names
  71552. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71553. // A mapping of the button name to glTF model node name
  71554. // that should be transformed by button value.
  71555. buttonMeshNames: {
  71556. 'trigger': 'SELECT',
  71557. 'menu': 'MENU',
  71558. 'grip': 'GRASP',
  71559. 'thumbstick': 'THUMBSTICK_PRESS',
  71560. 'trackpad': 'TOUCHPAD_PRESS'
  71561. },
  71562. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71563. buttonObservableNames: {
  71564. 'trigger': 'onTriggerStateChangedObservable',
  71565. 'menu': 'onSecondaryButtonStateChangedObservable',
  71566. 'grip': 'onMainButtonStateChangedObservable',
  71567. 'thumbstick': 'onPadStateChangedObservable',
  71568. 'trackpad': 'onTrackpadChangedObservable'
  71569. },
  71570. // A mapping of the axis name to glTF model node name
  71571. // that should be transformed by axis value.
  71572. // This array mirrors the browserGamepad.axes array, such that
  71573. // the mesh corresponding to axis 0 is in this array index 0.
  71574. axisMeshNames: [
  71575. 'THUMBSTICK_X',
  71576. 'THUMBSTICK_Y',
  71577. 'TOUCHPAD_TOUCH_X',
  71578. 'TOUCHPAD_TOUCH_Y'
  71579. ],
  71580. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71581. };
  71582. /**
  71583. * Fired when the trackpad on this controller is clicked
  71584. */
  71585. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71586. /**
  71587. * Fired when the trackpad on this controller is modified
  71588. */
  71589. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71590. /**
  71591. * The current x and y values of this controller's trackpad
  71592. */
  71593. _this.trackpad = { x: 0, y: 0 };
  71594. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71595. _this._loadedMeshInfo = null;
  71596. return _this;
  71597. }
  71598. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71599. /**
  71600. * Fired when the trigger on this controller is modified
  71601. */
  71602. get: function () {
  71603. return this.onTriggerStateChangedObservable;
  71604. },
  71605. enumerable: true,
  71606. configurable: true
  71607. });
  71608. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71609. /**
  71610. * Fired when the menu button on this controller is modified
  71611. */
  71612. get: function () {
  71613. return this.onSecondaryButtonStateChangedObservable;
  71614. },
  71615. enumerable: true,
  71616. configurable: true
  71617. });
  71618. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71619. /**
  71620. * Fired when the grip button on this controller is modified
  71621. */
  71622. get: function () {
  71623. return this.onMainButtonStateChangedObservable;
  71624. },
  71625. enumerable: true,
  71626. configurable: true
  71627. });
  71628. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71629. /**
  71630. * Fired when the thumbstick button on this controller is modified
  71631. */
  71632. get: function () {
  71633. return this.onPadStateChangedObservable;
  71634. },
  71635. enumerable: true,
  71636. configurable: true
  71637. });
  71638. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71639. /**
  71640. * Fired when the touchpad button on this controller is modified
  71641. */
  71642. get: function () {
  71643. return this.onTrackpadChangedObservable;
  71644. },
  71645. enumerable: true,
  71646. configurable: true
  71647. });
  71648. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71649. /**
  71650. * Fired when the touchpad values on this controller are modified
  71651. */
  71652. get: function () {
  71653. return this.onTrackpadValuesChangedObservable;
  71654. },
  71655. enumerable: true,
  71656. configurable: true
  71657. });
  71658. /**
  71659. * Called once per frame by the engine.
  71660. */
  71661. WindowsMotionController.prototype.update = function () {
  71662. _super.prototype.update.call(this);
  71663. if (this.browserGamepad.axes) {
  71664. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  71665. this.trackpad.x = this.browserGamepad["axes"][2];
  71666. this.trackpad.y = this.browserGamepad["axes"][3];
  71667. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71668. }
  71669. // Only need to animate axes if there is a loaded mesh
  71670. if (this._loadedMeshInfo) {
  71671. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71672. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71673. }
  71674. }
  71675. }
  71676. };
  71677. /**
  71678. * Called once for each button that changed state since the last frame
  71679. * @param buttonIdx Which button index changed
  71680. * @param state New state of the button
  71681. * @param changes Which properties on the state changed since last frame
  71682. */
  71683. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71684. var buttonName = this._mapping.buttons[buttonIdx];
  71685. if (!buttonName) {
  71686. return;
  71687. }
  71688. // Only emit events for buttons that we know how to map from index to name
  71689. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71690. if (observable) {
  71691. observable.notifyObservers(state);
  71692. }
  71693. this._lerpButtonTransform(buttonName, state.value);
  71694. };
  71695. /**
  71696. * Moves the buttons on the controller mesh based on their current state
  71697. * @param buttonName the name of the button to move
  71698. * @param buttonValue the value of the button which determines the buttons new position
  71699. */
  71700. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71701. // If there is no loaded mesh, there is nothing to transform.
  71702. if (!this._loadedMeshInfo) {
  71703. return;
  71704. }
  71705. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71706. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71707. return;
  71708. }
  71709. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71710. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71711. };
  71712. /**
  71713. * Moves the axis on the controller mesh based on its current state
  71714. * @param axis the index of the axis
  71715. * @param axisValue the value of the axis which determines the meshes new position
  71716. * @hidden
  71717. */
  71718. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71719. if (!this._loadedMeshInfo) {
  71720. return;
  71721. }
  71722. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71723. if (!meshInfo) {
  71724. return;
  71725. }
  71726. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71727. return;
  71728. }
  71729. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71730. var lerpValue = axisValue * 0.5 + 0.5;
  71731. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71732. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71733. };
  71734. /**
  71735. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71736. * @param scene scene in which to add meshes
  71737. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71738. */
  71739. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71740. var _this = this;
  71741. if (forceDefault === void 0) { forceDefault = false; }
  71742. var path;
  71743. var filename;
  71744. // Checking if GLB loader is present
  71745. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71746. // Determine the device specific folder based on the ID suffix
  71747. var device = 'default';
  71748. if (this.id && !forceDefault) {
  71749. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71750. device = ((match && match[0]) || device);
  71751. }
  71752. // Hand
  71753. if (this.hand === 'left') {
  71754. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71755. }
  71756. else { // Right is the default if no hand is specified
  71757. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71758. }
  71759. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71760. }
  71761. else {
  71762. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71763. path = BABYLON.GenericController.MODEL_BASE_URL;
  71764. filename = BABYLON.GenericController.MODEL_FILENAME;
  71765. }
  71766. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71767. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71768. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71769. if (!_this._loadedMeshInfo) {
  71770. return;
  71771. }
  71772. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71773. _this.attachToMesh(_this._defaultModel);
  71774. if (meshLoaded) {
  71775. meshLoaded(_this._defaultModel);
  71776. }
  71777. }, null, function (scene, message) {
  71778. BABYLON.Tools.Log(message);
  71779. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71780. if (!forceDefault) {
  71781. _this.initControllerMesh(scene, meshLoaded, true);
  71782. }
  71783. });
  71784. };
  71785. /**
  71786. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  71787. * can be transformed by button presses and axes values, based on this._mapping.
  71788. *
  71789. * @param scene scene in which the meshes exist
  71790. * @param meshes list of meshes that make up the controller model to process
  71791. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  71792. */
  71793. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  71794. var loadedMeshInfo = null;
  71795. // Create a new mesh to contain the glTF hierarchy
  71796. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  71797. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  71798. var childMesh = null;
  71799. for (var i = 0; i < meshes.length; i++) {
  71800. var mesh = meshes[i];
  71801. if (!mesh.parent) {
  71802. // Exclude controller meshes from picking results
  71803. mesh.isPickable = false;
  71804. // Handle root node, attach to the new parentMesh
  71805. childMesh = mesh;
  71806. break;
  71807. }
  71808. }
  71809. if (childMesh) {
  71810. childMesh.setParent(parentMesh);
  71811. // Create our mesh info. Note that this method will always return non-null.
  71812. loadedMeshInfo = this.createMeshInfo(parentMesh);
  71813. }
  71814. else {
  71815. BABYLON.Tools.Warn('Could not find root node in model file.');
  71816. }
  71817. return loadedMeshInfo;
  71818. };
  71819. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  71820. var loadedMeshInfo = new LoadedMeshInfo();
  71821. var i;
  71822. loadedMeshInfo.rootNode = rootNode;
  71823. // Reset the caches
  71824. loadedMeshInfo.buttonMeshes = {};
  71825. loadedMeshInfo.axisMeshes = {};
  71826. // Button Meshes
  71827. for (i = 0; i < this._mapping.buttons.length; i++) {
  71828. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  71829. if (!buttonMeshName) {
  71830. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  71831. continue;
  71832. }
  71833. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  71834. if (!buttonMesh) {
  71835. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  71836. continue;
  71837. }
  71838. var buttonMeshInfo = {
  71839. index: i,
  71840. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  71841. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  71842. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  71843. };
  71844. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  71845. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  71846. }
  71847. else {
  71848. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  71849. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  71850. '(VALUE: ' + !!buttonMeshInfo.value +
  71851. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  71852. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  71853. ')');
  71854. }
  71855. }
  71856. // Axis Meshes
  71857. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  71858. var axisMeshName = this._mapping.axisMeshNames[i];
  71859. if (!axisMeshName) {
  71860. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  71861. continue;
  71862. }
  71863. var axisMesh = getChildByName(rootNode, axisMeshName);
  71864. if (!axisMesh) {
  71865. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  71866. continue;
  71867. }
  71868. var axisMeshInfo = {
  71869. index: i,
  71870. value: getImmediateChildByName(axisMesh, 'VALUE'),
  71871. min: getImmediateChildByName(axisMesh, 'MIN'),
  71872. max: getImmediateChildByName(axisMesh, 'MAX')
  71873. };
  71874. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  71875. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  71876. }
  71877. else {
  71878. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  71879. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  71880. '(VALUE: ' + !!axisMeshInfo.value +
  71881. ', MIN: ' + !!axisMeshInfo.min +
  71882. ', MAX:' + !!axisMeshInfo.max +
  71883. ')');
  71884. }
  71885. }
  71886. // Pointing Ray
  71887. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  71888. if (!loadedMeshInfo.pointingPoseNode) {
  71889. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  71890. }
  71891. return loadedMeshInfo;
  71892. // Look through all children recursively. This will return null if no mesh exists with the given name.
  71893. function getChildByName(node, name) {
  71894. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  71895. }
  71896. // Look through only immediate children. This will return null if no mesh exists with the given name.
  71897. function getImmediateChildByName(node, name) {
  71898. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  71899. }
  71900. };
  71901. /**
  71902. * Gets the ray of the controller in the direction the controller is pointing
  71903. * @param length the length the resulting ray should be
  71904. * @returns a ray in the direction the controller is pointing
  71905. */
  71906. WindowsMotionController.prototype.getForwardRay = function (length) {
  71907. if (length === void 0) { length = 100; }
  71908. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  71909. return _super.prototype.getForwardRay.call(this, length);
  71910. }
  71911. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  71912. var origin = m.getTranslation();
  71913. var forward = new BABYLON.Vector3(0, 0, -1);
  71914. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71915. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71916. return new BABYLON.Ray(origin, direction, length);
  71917. };
  71918. /**
  71919. * Disposes of the controller
  71920. */
  71921. WindowsMotionController.prototype.dispose = function () {
  71922. _super.prototype.dispose.call(this);
  71923. this.onTrackpadChangedObservable.clear();
  71924. };
  71925. /**
  71926. * The base url used to load the left and right controller models
  71927. */
  71928. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  71929. /**
  71930. * The name of the left controller model file
  71931. */
  71932. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  71933. /**
  71934. * The name of the right controller model file
  71935. */
  71936. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  71937. /**
  71938. * The controller name prefix for this controller type
  71939. */
  71940. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  71941. /**
  71942. * The controller id pattern for this controller type
  71943. */
  71944. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  71945. return WindowsMotionController;
  71946. }(BABYLON.WebVRController));
  71947. BABYLON.WindowsMotionController = WindowsMotionController;
  71948. })(BABYLON || (BABYLON = {}));
  71949. //# sourceMappingURL=babylon.windowsMotionController.js.map
  71950. var BABYLON;
  71951. (function (BABYLON) {
  71952. /**
  71953. * Gear VR Controller
  71954. */
  71955. var GearVRController = /** @class */ (function (_super) {
  71956. __extends(GearVRController, _super);
  71957. /**
  71958. * Creates a new GearVRController from a gamepad
  71959. * @param vrGamepad the gamepad that the controller should be created from
  71960. */
  71961. function GearVRController(vrGamepad) {
  71962. var _this = _super.call(this, vrGamepad) || this;
  71963. _this._buttonIndexToObservableNameMap = [
  71964. 'onTrackpadChangedObservable',
  71965. 'onTriggerStateChangedObservable' // Trigger
  71966. ];
  71967. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  71968. return _this;
  71969. }
  71970. /**
  71971. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71972. * @param scene scene in which to add meshes
  71973. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71974. */
  71975. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71976. var _this = this;
  71977. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  71978. _this._defaultModel = newMeshes[1];
  71979. _this.attachToMesh(_this._defaultModel);
  71980. if (meshLoaded) {
  71981. meshLoaded(_this._defaultModel);
  71982. }
  71983. });
  71984. };
  71985. /**
  71986. * Called once for each button that changed state since the last frame
  71987. * @param buttonIdx Which button index changed
  71988. * @param state New state of the button
  71989. * @param changes Which properties on the state changed since last frame
  71990. */
  71991. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71992. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  71993. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  71994. // Only emit events for buttons that we know how to map from index to observable
  71995. var observable = this[observableName];
  71996. if (observable) {
  71997. observable.notifyObservers(state);
  71998. }
  71999. }
  72000. };
  72001. /**
  72002. * Base Url for the controller model.
  72003. */
  72004. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72005. /**
  72006. * File name for the controller model.
  72007. */
  72008. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72009. /**
  72010. * Gamepad Id prefix used to identify this controller.
  72011. */
  72012. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72013. return GearVRController;
  72014. }(BABYLON.WebVRController));
  72015. BABYLON.GearVRController = GearVRController;
  72016. })(BABYLON || (BABYLON = {}));
  72017. //# sourceMappingURL=babylon.gearVRController.js.map
  72018. var BABYLON;
  72019. (function (BABYLON) {
  72020. /**
  72021. * Google Daydream controller
  72022. */
  72023. var DaydreamController = /** @class */ (function (_super) {
  72024. __extends(DaydreamController, _super);
  72025. /**
  72026. * Creates a new DaydreamController from a gamepad
  72027. * @param vrGamepad the gamepad that the controller should be created from
  72028. */
  72029. function DaydreamController(vrGamepad) {
  72030. var _this = _super.call(this, vrGamepad) || this;
  72031. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72032. return _this;
  72033. }
  72034. /**
  72035. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72036. * @param scene scene in which to add meshes
  72037. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72038. */
  72039. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72040. var _this = this;
  72041. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72042. _this._defaultModel = newMeshes[1];
  72043. _this.attachToMesh(_this._defaultModel);
  72044. if (meshLoaded) {
  72045. meshLoaded(_this._defaultModel);
  72046. }
  72047. });
  72048. };
  72049. /**
  72050. * Called once for each button that changed state since the last frame
  72051. * @param buttonIdx Which button index changed
  72052. * @param state New state of the button
  72053. * @param changes Which properties on the state changed since last frame
  72054. */
  72055. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72056. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72057. if (buttonIdx === 0) {
  72058. var observable = this.onTriggerStateChangedObservable;
  72059. if (observable) {
  72060. observable.notifyObservers(state);
  72061. }
  72062. }
  72063. else {
  72064. // If the app or home buttons are ever made available
  72065. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72066. }
  72067. };
  72068. /**
  72069. * Base Url for the controller model.
  72070. */
  72071. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72072. /**
  72073. * File name for the controller model.
  72074. */
  72075. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72076. /**
  72077. * Gamepad Id prefix used to identify Daydream Controller.
  72078. */
  72079. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72080. return DaydreamController;
  72081. }(BABYLON.WebVRController));
  72082. BABYLON.DaydreamController = DaydreamController;
  72083. })(BABYLON || (BABYLON = {}));
  72084. //# sourceMappingURL=babylon.daydreamController.js.map
  72085. var BABYLON;
  72086. (function (BABYLON) {
  72087. var FollowCamera = /** @class */ (function (_super) {
  72088. __extends(FollowCamera, _super);
  72089. function FollowCamera(name, position, scene, lockedTarget) {
  72090. if (lockedTarget === void 0) { lockedTarget = null; }
  72091. var _this = _super.call(this, name, position, scene) || this;
  72092. _this.radius = 12;
  72093. _this.rotationOffset = 0;
  72094. _this.heightOffset = 4;
  72095. _this.cameraAcceleration = 0.05;
  72096. _this.maxCameraSpeed = 20;
  72097. _this.lockedTarget = lockedTarget;
  72098. return _this;
  72099. }
  72100. FollowCamera.prototype.getRadians = function (degrees) {
  72101. return degrees * Math.PI / 180;
  72102. };
  72103. FollowCamera.prototype.follow = function (cameraTarget) {
  72104. if (!cameraTarget)
  72105. return;
  72106. var yRotation;
  72107. if (cameraTarget.rotationQuaternion) {
  72108. var rotMatrix = new BABYLON.Matrix();
  72109. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72110. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72111. }
  72112. else {
  72113. yRotation = cameraTarget.rotation.y;
  72114. }
  72115. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72116. var targetPosition = cameraTarget.getAbsolutePosition();
  72117. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72118. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72119. var dx = targetX - this.position.x;
  72120. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72121. var dz = (targetZ) - this.position.z;
  72122. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72123. var vy = dy * this.cameraAcceleration;
  72124. var vz = dz * this.cameraAcceleration * 2;
  72125. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72126. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72127. }
  72128. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72129. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72130. }
  72131. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72132. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72133. }
  72134. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72135. this.setTarget(targetPosition);
  72136. };
  72137. FollowCamera.prototype._checkInputs = function () {
  72138. _super.prototype._checkInputs.call(this);
  72139. if (this.lockedTarget) {
  72140. this.follow(this.lockedTarget);
  72141. }
  72142. };
  72143. FollowCamera.prototype.getClassName = function () {
  72144. return "FollowCamera";
  72145. };
  72146. __decorate([
  72147. BABYLON.serialize()
  72148. ], FollowCamera.prototype, "radius", void 0);
  72149. __decorate([
  72150. BABYLON.serialize()
  72151. ], FollowCamera.prototype, "rotationOffset", void 0);
  72152. __decorate([
  72153. BABYLON.serialize()
  72154. ], FollowCamera.prototype, "heightOffset", void 0);
  72155. __decorate([
  72156. BABYLON.serialize()
  72157. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72158. __decorate([
  72159. BABYLON.serialize()
  72160. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72161. __decorate([
  72162. BABYLON.serializeAsMeshReference("lockedTargetId")
  72163. ], FollowCamera.prototype, "lockedTarget", void 0);
  72164. return FollowCamera;
  72165. }(BABYLON.TargetCamera));
  72166. BABYLON.FollowCamera = FollowCamera;
  72167. var ArcFollowCamera = /** @class */ (function (_super) {
  72168. __extends(ArcFollowCamera, _super);
  72169. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72170. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72171. _this.alpha = alpha;
  72172. _this.beta = beta;
  72173. _this.radius = radius;
  72174. _this.target = target;
  72175. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72176. _this.follow();
  72177. return _this;
  72178. }
  72179. ArcFollowCamera.prototype.follow = function () {
  72180. if (!this.target) {
  72181. return;
  72182. }
  72183. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72184. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72185. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72186. var targetPosition = this.target.getAbsolutePosition();
  72187. this.position = targetPosition.add(this._cartesianCoordinates);
  72188. this.setTarget(targetPosition);
  72189. };
  72190. ArcFollowCamera.prototype._checkInputs = function () {
  72191. _super.prototype._checkInputs.call(this);
  72192. this.follow();
  72193. };
  72194. ArcFollowCamera.prototype.getClassName = function () {
  72195. return "ArcFollowCamera";
  72196. };
  72197. return ArcFollowCamera;
  72198. }(BABYLON.TargetCamera));
  72199. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72200. })(BABYLON || (BABYLON = {}));
  72201. //# sourceMappingURL=babylon.followCamera.js.map
  72202. var BABYLON;
  72203. (function (BABYLON) {
  72204. // We're mainly based on the logic defined into the FreeCamera code
  72205. var UniversalCamera = /** @class */ (function (_super) {
  72206. __extends(UniversalCamera, _super);
  72207. //-- end properties for backward compatibility for inputs
  72208. function UniversalCamera(name, position, scene) {
  72209. var _this = _super.call(this, name, position, scene) || this;
  72210. _this.inputs.addGamepad();
  72211. return _this;
  72212. }
  72213. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72214. //-- Begin properties for backward compatibility for inputs
  72215. get: function () {
  72216. var gamepad = this.inputs.attached["gamepad"];
  72217. if (gamepad)
  72218. return gamepad.gamepadAngularSensibility;
  72219. return 0;
  72220. },
  72221. set: function (value) {
  72222. var gamepad = this.inputs.attached["gamepad"];
  72223. if (gamepad)
  72224. gamepad.gamepadAngularSensibility = value;
  72225. },
  72226. enumerable: true,
  72227. configurable: true
  72228. });
  72229. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72230. get: function () {
  72231. var gamepad = this.inputs.attached["gamepad"];
  72232. if (gamepad)
  72233. return gamepad.gamepadMoveSensibility;
  72234. return 0;
  72235. },
  72236. set: function (value) {
  72237. var gamepad = this.inputs.attached["gamepad"];
  72238. if (gamepad)
  72239. gamepad.gamepadMoveSensibility = value;
  72240. },
  72241. enumerable: true,
  72242. configurable: true
  72243. });
  72244. UniversalCamera.prototype.getClassName = function () {
  72245. return "UniversalCamera";
  72246. };
  72247. return UniversalCamera;
  72248. }(BABYLON.TouchCamera));
  72249. BABYLON.UniversalCamera = UniversalCamera;
  72250. })(BABYLON || (BABYLON = {}));
  72251. //# sourceMappingURL=babylon.universalCamera.js.map
  72252. var BABYLON;
  72253. (function (BABYLON) {
  72254. // We're mainly based on the logic defined into the FreeCamera code
  72255. var GamepadCamera = /** @class */ (function (_super) {
  72256. __extends(GamepadCamera, _super);
  72257. //-- end properties for backward compatibility for inputs
  72258. function GamepadCamera(name, position, scene) {
  72259. return _super.call(this, name, position, scene) || this;
  72260. }
  72261. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72262. //-- Begin properties for backward compatibility for inputs
  72263. get: function () {
  72264. var gamepad = this.inputs.attached["gamepad"];
  72265. if (gamepad)
  72266. return gamepad.gamepadAngularSensibility;
  72267. return 0;
  72268. },
  72269. set: function (value) {
  72270. var gamepad = this.inputs.attached["gamepad"];
  72271. if (gamepad)
  72272. gamepad.gamepadAngularSensibility = value;
  72273. },
  72274. enumerable: true,
  72275. configurable: true
  72276. });
  72277. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72278. get: function () {
  72279. var gamepad = this.inputs.attached["gamepad"];
  72280. if (gamepad)
  72281. return gamepad.gamepadMoveSensibility;
  72282. return 0;
  72283. },
  72284. set: function (value) {
  72285. var gamepad = this.inputs.attached["gamepad"];
  72286. if (gamepad)
  72287. gamepad.gamepadMoveSensibility = value;
  72288. },
  72289. enumerable: true,
  72290. configurable: true
  72291. });
  72292. GamepadCamera.prototype.getClassName = function () {
  72293. return "GamepadCamera";
  72294. };
  72295. return GamepadCamera;
  72296. }(BABYLON.UniversalCamera));
  72297. BABYLON.GamepadCamera = GamepadCamera;
  72298. })(BABYLON || (BABYLON = {}));
  72299. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72300. var BABYLON;
  72301. (function (BABYLON) {
  72302. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72303. function PostProcessRenderPipelineManager() {
  72304. this._renderPipelines = {};
  72305. }
  72306. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72307. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72308. };
  72309. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72310. if (unique === void 0) { unique = false; }
  72311. var renderPipeline = this._renderPipelines[renderPipelineName];
  72312. if (!renderPipeline) {
  72313. return;
  72314. }
  72315. renderPipeline._attachCameras(cameras, unique);
  72316. };
  72317. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72318. var renderPipeline = this._renderPipelines[renderPipelineName];
  72319. if (!renderPipeline) {
  72320. return;
  72321. }
  72322. renderPipeline._detachCameras(cameras);
  72323. };
  72324. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72325. var renderPipeline = this._renderPipelines[renderPipelineName];
  72326. if (!renderPipeline) {
  72327. return;
  72328. }
  72329. renderPipeline._enableEffect(renderEffectName, cameras);
  72330. };
  72331. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72332. var renderPipeline = this._renderPipelines[renderPipelineName];
  72333. if (!renderPipeline) {
  72334. return;
  72335. }
  72336. renderPipeline._disableEffect(renderEffectName, cameras);
  72337. };
  72338. PostProcessRenderPipelineManager.prototype.update = function () {
  72339. for (var renderPipelineName in this._renderPipelines) {
  72340. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72341. var pipeline = this._renderPipelines[renderPipelineName];
  72342. if (!pipeline.isSupported) {
  72343. pipeline.dispose();
  72344. delete this._renderPipelines[renderPipelineName];
  72345. }
  72346. else {
  72347. pipeline._update();
  72348. }
  72349. }
  72350. }
  72351. };
  72352. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72353. for (var renderPipelineName in this._renderPipelines) {
  72354. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72355. var pipeline = this._renderPipelines[renderPipelineName];
  72356. pipeline._rebuild();
  72357. }
  72358. }
  72359. };
  72360. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72361. for (var renderPipelineName in this._renderPipelines) {
  72362. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72363. var pipeline = this._renderPipelines[renderPipelineName];
  72364. pipeline.dispose();
  72365. }
  72366. }
  72367. };
  72368. return PostProcessRenderPipelineManager;
  72369. }());
  72370. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72371. })(BABYLON || (BABYLON = {}));
  72372. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72373. var BABYLON;
  72374. (function (BABYLON) {
  72375. /**
  72376. * This represents a set of one or more post processes in Babylon.
  72377. * A post process can be used to apply a shader to a texture after it is rendered.
  72378. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72379. */
  72380. var PostProcessRenderEffect = /** @class */ (function () {
  72381. /**
  72382. * Instantiates a post process render effect.
  72383. * A post process can be used to apply a shader to a texture after it is rendered.
  72384. * @param engine The engine the effect is tied to
  72385. * @param name The name of the effect
  72386. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72387. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72388. */
  72389. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72390. this._name = name;
  72391. this._singleInstance = singleInstance || true;
  72392. this._getPostProcesses = getPostProcesses;
  72393. this._cameras = {};
  72394. this._indicesForCamera = {};
  72395. this._postProcesses = {};
  72396. }
  72397. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72398. /**
  72399. * Checks if all the post processes in the effect are supported.
  72400. */
  72401. get: function () {
  72402. for (var index in this._postProcesses) {
  72403. if (this._postProcesses.hasOwnProperty(index)) {
  72404. var pps = this._postProcesses[index];
  72405. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72406. if (!pps[ppIndex].isSupported) {
  72407. return false;
  72408. }
  72409. }
  72410. }
  72411. }
  72412. return true;
  72413. },
  72414. enumerable: true,
  72415. configurable: true
  72416. });
  72417. /**
  72418. * Updates the current state of the effect
  72419. */
  72420. PostProcessRenderEffect.prototype._update = function () {
  72421. };
  72422. /**
  72423. * Attaches the effect on cameras
  72424. * @param cameras The camera to attach to.
  72425. */
  72426. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72427. var _this = this;
  72428. var cameraKey;
  72429. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72430. if (!cams) {
  72431. return;
  72432. }
  72433. for (var i = 0; i < cams.length; i++) {
  72434. var camera = cams[i];
  72435. var cameraName = camera.name;
  72436. if (this._singleInstance) {
  72437. cameraKey = 0;
  72438. }
  72439. else {
  72440. cameraKey = cameraName;
  72441. }
  72442. if (!this._postProcesses[cameraKey]) {
  72443. var postProcess = this._getPostProcesses();
  72444. if (postProcess) {
  72445. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72446. }
  72447. }
  72448. if (!this._indicesForCamera[cameraName]) {
  72449. this._indicesForCamera[cameraName] = [];
  72450. }
  72451. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72452. var index = camera.attachPostProcess(postProcess);
  72453. _this._indicesForCamera[cameraName].push(index);
  72454. });
  72455. if (!this._cameras[cameraName]) {
  72456. this._cameras[cameraName] = camera;
  72457. }
  72458. }
  72459. };
  72460. /**
  72461. * Detatches the effect on cameras
  72462. * @param cameras The camera to detatch from.
  72463. */
  72464. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72465. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72466. if (!cams) {
  72467. return;
  72468. }
  72469. for (var i = 0; i < cams.length; i++) {
  72470. var camera = cams[i];
  72471. var cameraName = camera.name;
  72472. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72473. camera.detachPostProcess(postProcess);
  72474. });
  72475. if (this._cameras[cameraName]) {
  72476. //this._indicesForCamera.splice(index, 1);
  72477. this._cameras[cameraName] = null;
  72478. }
  72479. }
  72480. };
  72481. /**
  72482. * Enables the effect on given cameras
  72483. * @param cameras The camera to enable.
  72484. */
  72485. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72486. var _this = this;
  72487. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72488. if (!cams) {
  72489. return;
  72490. }
  72491. for (var i = 0; i < cams.length; i++) {
  72492. var camera = cams[i];
  72493. var cameraName = camera.name;
  72494. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72495. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72496. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72497. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72498. });
  72499. }
  72500. }
  72501. }
  72502. };
  72503. /**
  72504. * Disables the effect on the given cameras
  72505. * @param cameras The camera to disable.
  72506. */
  72507. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72508. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72509. if (!cams) {
  72510. return;
  72511. }
  72512. for (var i = 0; i < cams.length; i++) {
  72513. var camera = cams[i];
  72514. var cameraName = camera.name;
  72515. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72516. camera.detachPostProcess(postProcess);
  72517. });
  72518. }
  72519. };
  72520. /**
  72521. * Gets a list of the post processes contained in the effect.
  72522. * @param camera The camera to get the post processes on.
  72523. * @returns The list of the post processes in the effect.
  72524. */
  72525. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72526. if (this._singleInstance) {
  72527. return this._postProcesses[0];
  72528. }
  72529. else {
  72530. if (!camera) {
  72531. return null;
  72532. }
  72533. return this._postProcesses[camera.name];
  72534. }
  72535. };
  72536. return PostProcessRenderEffect;
  72537. }());
  72538. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72539. })(BABYLON || (BABYLON = {}));
  72540. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72541. var BABYLON;
  72542. (function (BABYLON) {
  72543. var PostProcessRenderPipeline = /** @class */ (function () {
  72544. function PostProcessRenderPipeline(engine, name) {
  72545. this.engine = engine;
  72546. this._name = name;
  72547. this._renderEffects = {};
  72548. this._renderEffectsForIsolatedPass = new Array();
  72549. this._cameras = [];
  72550. }
  72551. PostProcessRenderPipeline.prototype.getClassName = function () {
  72552. return "PostProcessRenderPipeline";
  72553. };
  72554. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72555. get: function () {
  72556. for (var renderEffectName in this._renderEffects) {
  72557. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72558. if (!this._renderEffects[renderEffectName].isSupported) {
  72559. return false;
  72560. }
  72561. }
  72562. }
  72563. return true;
  72564. },
  72565. enumerable: true,
  72566. configurable: true
  72567. });
  72568. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72569. this._renderEffects[renderEffect._name] = renderEffect;
  72570. };
  72571. // private
  72572. PostProcessRenderPipeline.prototype._rebuild = function () {
  72573. };
  72574. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72575. var renderEffects = this._renderEffects[renderEffectName];
  72576. if (!renderEffects) {
  72577. return;
  72578. }
  72579. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72580. };
  72581. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72582. var renderEffects = this._renderEffects[renderEffectName];
  72583. if (!renderEffects) {
  72584. return;
  72585. }
  72586. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72587. };
  72588. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72589. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72590. if (!cams) {
  72591. return;
  72592. }
  72593. var indicesToDelete = [];
  72594. var i;
  72595. for (i = 0; i < cams.length; i++) {
  72596. var camera = cams[i];
  72597. var cameraName = camera.name;
  72598. if (this._cameras.indexOf(camera) === -1) {
  72599. this._cameras[cameraName] = camera;
  72600. }
  72601. else if (unique) {
  72602. indicesToDelete.push(i);
  72603. }
  72604. }
  72605. for (i = 0; i < indicesToDelete.length; i++) {
  72606. cameras.splice(indicesToDelete[i], 1);
  72607. }
  72608. for (var renderEffectName in this._renderEffects) {
  72609. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72610. this._renderEffects[renderEffectName]._attachCameras(cams);
  72611. }
  72612. }
  72613. };
  72614. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72615. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72616. if (!cams) {
  72617. return;
  72618. }
  72619. for (var renderEffectName in this._renderEffects) {
  72620. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72621. this._renderEffects[renderEffectName]._detachCameras(cams);
  72622. }
  72623. }
  72624. for (var i = 0; i < cams.length; i++) {
  72625. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72626. }
  72627. };
  72628. PostProcessRenderPipeline.prototype._update = function () {
  72629. for (var renderEffectName in this._renderEffects) {
  72630. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72631. this._renderEffects[renderEffectName]._update();
  72632. }
  72633. }
  72634. for (var i = 0; i < this._cameras.length; i++) {
  72635. var cameraName = this._cameras[i].name;
  72636. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72637. this._renderEffectsForIsolatedPass[cameraName]._update();
  72638. }
  72639. }
  72640. };
  72641. PostProcessRenderPipeline.prototype._reset = function () {
  72642. this._renderEffects = {};
  72643. this._renderEffectsForIsolatedPass = new Array();
  72644. };
  72645. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72646. // 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)
  72647. var effectKeys = Object.keys(this._renderEffects);
  72648. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72649. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72650. if (postProcesses) {
  72651. postProcesses[0].samples = sampleCount;
  72652. return true;
  72653. }
  72654. }
  72655. return false;
  72656. };
  72657. PostProcessRenderPipeline.prototype.dispose = function () {
  72658. // Must be implemented by children
  72659. };
  72660. __decorate([
  72661. BABYLON.serialize()
  72662. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72663. return PostProcessRenderPipeline;
  72664. }());
  72665. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72666. })(BABYLON || (BABYLON = {}));
  72667. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72668. var BABYLON;
  72669. (function (BABYLON) {
  72670. /**
  72671. * This represents a depth renderer in Babylon.
  72672. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72673. */
  72674. var DepthRenderer = /** @class */ (function () {
  72675. /**
  72676. * Instantiates a depth renderer
  72677. * @param scene The scene the renderer belongs to
  72678. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72679. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72680. */
  72681. function DepthRenderer(scene, type, camera) {
  72682. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72683. if (camera === void 0) { camera = null; }
  72684. var _this = this;
  72685. this._scene = scene;
  72686. this._camera = camera;
  72687. var engine = scene.getEngine();
  72688. // Render target
  72689. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72690. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72691. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72692. this._depthMap.refreshRate = 1;
  72693. this._depthMap.renderParticles = false;
  72694. this._depthMap.renderList = null;
  72695. // Camera to get depth map from to support multiple concurrent cameras
  72696. this._depthMap.activeCamera = this._camera;
  72697. this._depthMap.ignoreCameraViewport = true;
  72698. this._depthMap.useCameraPostProcesses = false;
  72699. // set default depth value to 1.0 (far away)
  72700. this._depthMap.onClearObservable.add(function (engine) {
  72701. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72702. });
  72703. // Custom render function
  72704. var renderSubMesh = function (subMesh) {
  72705. var mesh = subMesh.getRenderingMesh();
  72706. var scene = _this._scene;
  72707. var engine = scene.getEngine();
  72708. var material = subMesh.getMaterial();
  72709. if (!material) {
  72710. return;
  72711. }
  72712. // Culling and reverse (right handed system)
  72713. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72714. // Managing instances
  72715. var batch = mesh._getInstancesRenderList(subMesh._id);
  72716. if (batch.mustReturn) {
  72717. return;
  72718. }
  72719. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72720. var camera = _this._camera || scene.activeCamera;
  72721. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72722. engine.enableEffect(_this._effect);
  72723. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72724. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72725. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72726. // Alpha test
  72727. if (material && material.needAlphaTesting()) {
  72728. var alphaTexture = material.getAlphaTestTexture();
  72729. if (alphaTexture) {
  72730. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72731. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72732. }
  72733. }
  72734. // Bones
  72735. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72736. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72737. }
  72738. // Draw
  72739. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72740. }
  72741. };
  72742. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72743. var index;
  72744. if (depthOnlySubMeshes.length) {
  72745. engine.setColorWrite(false);
  72746. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72747. renderSubMesh(depthOnlySubMeshes.data[index]);
  72748. }
  72749. engine.setColorWrite(true);
  72750. }
  72751. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72752. renderSubMesh(opaqueSubMeshes.data[index]);
  72753. }
  72754. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72755. renderSubMesh(alphaTestSubMeshes.data[index]);
  72756. }
  72757. };
  72758. }
  72759. /**
  72760. * Creates the depth rendering effect and checks if the effect is ready.
  72761. * @param subMesh The submesh to be used to render the depth map of
  72762. * @param useInstances If multiple world instances should be used
  72763. * @returns if the depth renderer is ready to render the depth map
  72764. */
  72765. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72766. var material = subMesh.getMaterial();
  72767. if (material.disableDepthWrite) {
  72768. return false;
  72769. }
  72770. var defines = [];
  72771. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72772. var mesh = subMesh.getMesh();
  72773. // Alpha test
  72774. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72775. defines.push("#define ALPHATEST");
  72776. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72777. attribs.push(BABYLON.VertexBuffer.UVKind);
  72778. defines.push("#define UV1");
  72779. }
  72780. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72781. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72782. defines.push("#define UV2");
  72783. }
  72784. }
  72785. // Bones
  72786. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72787. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72788. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72789. if (mesh.numBoneInfluencers > 4) {
  72790. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72791. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72792. }
  72793. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72794. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72795. }
  72796. else {
  72797. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72798. }
  72799. // Instances
  72800. if (useInstances) {
  72801. defines.push("#define INSTANCES");
  72802. attribs.push("world0");
  72803. attribs.push("world1");
  72804. attribs.push("world2");
  72805. attribs.push("world3");
  72806. }
  72807. // Get correct effect
  72808. var join = defines.join("\n");
  72809. if (this._cachedDefines !== join) {
  72810. this._cachedDefines = join;
  72811. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  72812. }
  72813. return this._effect.isReady();
  72814. };
  72815. /**
  72816. * Gets the texture which the depth map will be written to.
  72817. * @returns The depth map texture
  72818. */
  72819. DepthRenderer.prototype.getDepthMap = function () {
  72820. return this._depthMap;
  72821. };
  72822. /**
  72823. * Disposes of the depth renderer.
  72824. */
  72825. DepthRenderer.prototype.dispose = function () {
  72826. this._depthMap.dispose();
  72827. };
  72828. return DepthRenderer;
  72829. }());
  72830. BABYLON.DepthRenderer = DepthRenderer;
  72831. })(BABYLON || (BABYLON = {}));
  72832. //# sourceMappingURL=babylon.depthRenderer.js.map
  72833. var BABYLON;
  72834. (function (BABYLON) {
  72835. var SSAORenderingPipeline = /** @class */ (function (_super) {
  72836. __extends(SSAORenderingPipeline, _super);
  72837. /**
  72838. * @constructor
  72839. * @param {string} name - The rendering pipeline name
  72840. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72841. * @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 }
  72842. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72843. */
  72844. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  72845. var _this = _super.call(this, scene.getEngine(), name) || this;
  72846. // Members
  72847. /**
  72848. * The PassPostProcess id in the pipeline that contains the original scene color
  72849. */
  72850. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72851. /**
  72852. * The SSAO PostProcess id in the pipeline
  72853. */
  72854. _this.SSAORenderEffect = "SSAORenderEffect";
  72855. /**
  72856. * The horizontal blur PostProcess id in the pipeline
  72857. */
  72858. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  72859. /**
  72860. * The vertical blur PostProcess id in the pipeline
  72861. */
  72862. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  72863. /**
  72864. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  72865. */
  72866. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  72867. /**
  72868. * The output strength of the SSAO post-process. Default value is 1.0.
  72869. */
  72870. _this.totalStrength = 1.0;
  72871. /**
  72872. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  72873. */
  72874. _this.radius = 0.0001;
  72875. /**
  72876. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  72877. * Must not be equal to fallOff and superior to fallOff.
  72878. * Default value is 0.975
  72879. */
  72880. _this.area = 0.0075;
  72881. /**
  72882. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  72883. * Must not be equal to area and inferior to area.
  72884. * Default value is 0.0
  72885. */
  72886. _this.fallOff = 0.000001;
  72887. /**
  72888. * The base color of the SSAO post-process
  72889. * The final result is "base + ssao" between [0, 1]
  72890. */
  72891. _this.base = 0.5;
  72892. _this._firstUpdate = true;
  72893. _this._scene = scene;
  72894. // Set up assets
  72895. _this._createRandomTexture();
  72896. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  72897. var ssaoRatio = ratio.ssaoRatio || ratio;
  72898. var combineRatio = ratio.combineRatio || ratio;
  72899. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  72900. _this._createSSAOPostProcess(ssaoRatio);
  72901. _this._createBlurPostProcess(ssaoRatio);
  72902. _this._createSSAOCombinePostProcess(combineRatio);
  72903. // Set up pipeline
  72904. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  72905. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  72906. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  72907. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  72908. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  72909. // Finish
  72910. scene.postProcessRenderPipelineManager.addPipeline(_this);
  72911. if (cameras)
  72912. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  72913. return _this;
  72914. }
  72915. // Public Methods
  72916. /**
  72917. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  72918. */
  72919. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  72920. if (disableDepthRender === void 0) { disableDepthRender = false; }
  72921. for (var i = 0; i < this._scene.cameras.length; i++) {
  72922. var camera = this._scene.cameras[i];
  72923. this._originalColorPostProcess.dispose(camera);
  72924. this._ssaoPostProcess.dispose(camera);
  72925. this._blurHPostProcess.dispose(camera);
  72926. this._blurVPostProcess.dispose(camera);
  72927. this._ssaoCombinePostProcess.dispose(camera);
  72928. }
  72929. this._randomTexture.dispose();
  72930. if (disableDepthRender)
  72931. this._scene.disableDepthRenderer();
  72932. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  72933. _super.prototype.dispose.call(this);
  72934. };
  72935. // Private Methods
  72936. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  72937. var _this = this;
  72938. var size = 16;
  72939. 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);
  72940. 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);
  72941. this._blurHPostProcess.onActivateObservable.add(function () {
  72942. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  72943. _this._blurHPostProcess.kernel = size * dw;
  72944. });
  72945. this._blurVPostProcess.onActivateObservable.add(function () {
  72946. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  72947. _this._blurVPostProcess.kernel = size * dw;
  72948. });
  72949. };
  72950. SSAORenderingPipeline.prototype._rebuild = function () {
  72951. this._firstUpdate = true;
  72952. _super.prototype._rebuild.call(this);
  72953. };
  72954. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  72955. var _this = this;
  72956. var numSamples = 16;
  72957. var sampleSphere = [
  72958. 0.5381, 0.1856, -0.4319,
  72959. 0.1379, 0.2486, 0.4430,
  72960. 0.3371, 0.5679, -0.0057,
  72961. -0.6999, -0.0451, -0.0019,
  72962. 0.0689, -0.1598, -0.8547,
  72963. 0.0560, 0.0069, -0.1843,
  72964. -0.0146, 0.1402, 0.0762,
  72965. 0.0100, -0.1924, -0.0344,
  72966. -0.3577, -0.5301, -0.4358,
  72967. -0.3169, 0.1063, 0.0158,
  72968. 0.0103, -0.5869, 0.0046,
  72969. -0.0897, -0.4940, 0.3287,
  72970. 0.7119, -0.0154, -0.0918,
  72971. -0.0533, 0.0596, -0.5411,
  72972. 0.0352, -0.0631, 0.5460,
  72973. -0.4776, 0.2847, -0.0271
  72974. ];
  72975. var samplesFactor = 1.0 / numSamples;
  72976. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  72977. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  72978. "area", "fallOff", "base", "range", "viewport"
  72979. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  72980. this._ssaoPostProcess.onApply = function (effect) {
  72981. if (_this._firstUpdate) {
  72982. effect.setArray3("sampleSphere", sampleSphere);
  72983. effect.setFloat("samplesFactor", samplesFactor);
  72984. effect.setFloat("randTextureTiles", 4.0);
  72985. }
  72986. effect.setFloat("totalStrength", _this.totalStrength);
  72987. effect.setFloat("radius", _this.radius);
  72988. effect.setFloat("area", _this.area);
  72989. effect.setFloat("fallOff", _this.fallOff);
  72990. effect.setFloat("base", _this.base);
  72991. effect.setTexture("textureSampler", _this._depthTexture);
  72992. effect.setTexture("randomSampler", _this._randomTexture);
  72993. };
  72994. };
  72995. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  72996. var _this = this;
  72997. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  72998. this._ssaoCombinePostProcess.onApply = function (effect) {
  72999. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73000. };
  73001. };
  73002. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73003. var size = 512;
  73004. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73005. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73006. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73007. var context = this._randomTexture.getContext();
  73008. var rand = function (min, max) {
  73009. return Math.random() * (max - min) + min;
  73010. };
  73011. var randVector = BABYLON.Vector3.Zero();
  73012. for (var x = 0; x < size; x++) {
  73013. for (var y = 0; y < size; y++) {
  73014. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73015. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73016. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73017. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73018. context.fillRect(x, y, 1, 1);
  73019. }
  73020. }
  73021. this._randomTexture.update(false);
  73022. };
  73023. __decorate([
  73024. BABYLON.serialize()
  73025. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73026. __decorate([
  73027. BABYLON.serialize()
  73028. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73029. __decorate([
  73030. BABYLON.serialize()
  73031. ], SSAORenderingPipeline.prototype, "area", void 0);
  73032. __decorate([
  73033. BABYLON.serialize()
  73034. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73035. __decorate([
  73036. BABYLON.serialize()
  73037. ], SSAORenderingPipeline.prototype, "base", void 0);
  73038. return SSAORenderingPipeline;
  73039. }(BABYLON.PostProcessRenderPipeline));
  73040. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73041. })(BABYLON || (BABYLON = {}));
  73042. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73043. var BABYLON;
  73044. (function (BABYLON) {
  73045. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73046. __extends(SSAO2RenderingPipeline, _super);
  73047. /**
  73048. * @constructor
  73049. * @param {string} name - The rendering pipeline name
  73050. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73051. * @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 }
  73052. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73053. */
  73054. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73055. var _this = _super.call(this, scene.getEngine(), name) || this;
  73056. // Members
  73057. /**
  73058. * The PassPostProcess id in the pipeline that contains the original scene color
  73059. */
  73060. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73061. /**
  73062. * The SSAO PostProcess id in the pipeline
  73063. */
  73064. _this.SSAORenderEffect = "SSAORenderEffect";
  73065. /**
  73066. * The horizontal blur PostProcess id in the pipeline
  73067. */
  73068. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73069. /**
  73070. * The vertical blur PostProcess id in the pipeline
  73071. */
  73072. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73073. /**
  73074. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73075. */
  73076. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73077. /**
  73078. * The output strength of the SSAO post-process. Default value is 1.0.
  73079. */
  73080. _this.totalStrength = 1.0;
  73081. /**
  73082. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73083. */
  73084. _this.maxZ = 100.0;
  73085. /**
  73086. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73087. */
  73088. _this.minZAspect = 0.2;
  73089. /**
  73090. * Number of samples used for the SSAO calculations. Default value is 8
  73091. */
  73092. _this._samples = 8;
  73093. /**
  73094. * Are we using bilateral blur ?
  73095. */
  73096. _this._expensiveBlur = true;
  73097. /**
  73098. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73099. */
  73100. _this.radius = 2.0;
  73101. /**
  73102. * The base color of the SSAO post-process
  73103. * The final result is "base + ssao" between [0, 1]
  73104. */
  73105. _this.base = 0.1;
  73106. _this._firstUpdate = true;
  73107. _this._scene = scene;
  73108. _this._ratio = ratio;
  73109. if (!_this.isSupported) {
  73110. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73111. return _this;
  73112. }
  73113. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73114. var blurRatio = _this._ratio.blurRatio || ratio;
  73115. // Set up assets
  73116. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73117. _this._createRandomTexture();
  73118. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73119. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73120. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73121. _this._createSSAOPostProcess(1.0);
  73122. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73123. _this._createSSAOCombinePostProcess(blurRatio);
  73124. // Set up pipeline
  73125. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73126. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73127. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73128. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73129. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73130. // Finish
  73131. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73132. if (cameras)
  73133. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73134. return _this;
  73135. }
  73136. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73137. get: function () {
  73138. return this._samples;
  73139. },
  73140. set: function (n) {
  73141. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73142. this._samples = n;
  73143. this._sampleSphere = this._generateHemisphere();
  73144. this._firstUpdate = true;
  73145. },
  73146. enumerable: true,
  73147. configurable: true
  73148. });
  73149. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73150. get: function () {
  73151. return this._expensiveBlur;
  73152. },
  73153. set: function (b) {
  73154. 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"]);
  73155. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73156. this._expensiveBlur = b;
  73157. this._firstUpdate = true;
  73158. },
  73159. enumerable: true,
  73160. configurable: true
  73161. });
  73162. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73163. /**
  73164. * Support test.
  73165. */
  73166. get: function () {
  73167. var engine = BABYLON.Engine.LastCreatedEngine;
  73168. if (!engine) {
  73169. return false;
  73170. }
  73171. return engine.getCaps().drawBuffersExtension;
  73172. },
  73173. enumerable: true,
  73174. configurable: true
  73175. });
  73176. // Public Methods
  73177. /**
  73178. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73179. */
  73180. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73181. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73182. for (var i = 0; i < this._scene.cameras.length; i++) {
  73183. var camera = this._scene.cameras[i];
  73184. this._originalColorPostProcess.dispose(camera);
  73185. this._ssaoPostProcess.dispose(camera);
  73186. this._blurHPostProcess.dispose(camera);
  73187. this._blurVPostProcess.dispose(camera);
  73188. this._ssaoCombinePostProcess.dispose(camera);
  73189. }
  73190. this._randomTexture.dispose();
  73191. if (disableGeometryBufferRenderer)
  73192. this._scene.disableGeometryBufferRenderer();
  73193. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73194. _super.prototype.dispose.call(this);
  73195. };
  73196. // Private Methods
  73197. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73198. var _this = this;
  73199. this._samplerOffsets = [];
  73200. var expensive = this.expensiveBlur;
  73201. for (var i = -8; i < 8; i++) {
  73202. this._samplerOffsets.push(i * 2 + 0.5);
  73203. }
  73204. 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");
  73205. this._blurHPostProcess.onApply = function (effect) {
  73206. if (!_this._scene.activeCamera) {
  73207. return;
  73208. }
  73209. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73210. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73211. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73212. effect.setFloat("radius", _this.radius);
  73213. effect.setTexture("depthSampler", _this._depthTexture);
  73214. if (_this._firstUpdate) {
  73215. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73216. }
  73217. };
  73218. 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");
  73219. this._blurVPostProcess.onApply = function (effect) {
  73220. if (!_this._scene.activeCamera) {
  73221. return;
  73222. }
  73223. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73224. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73225. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73226. effect.setFloat("radius", _this.radius);
  73227. effect.setTexture("depthSampler", _this._depthTexture);
  73228. if (_this._firstUpdate) {
  73229. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73230. _this._firstUpdate = false;
  73231. }
  73232. };
  73233. };
  73234. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73235. this._firstUpdate = true;
  73236. _super.prototype._rebuild.call(this);
  73237. };
  73238. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73239. var numSamples = this.samples;
  73240. var result = [];
  73241. var vector, scale;
  73242. var rand = function (min, max) {
  73243. return Math.random() * (max - min) + min;
  73244. };
  73245. var i = 0;
  73246. while (i < numSamples) {
  73247. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73248. vector.normalize();
  73249. scale = i / numSamples;
  73250. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73251. vector.scaleInPlace(scale);
  73252. result.push(vector.x, vector.y, vector.z);
  73253. i++;
  73254. }
  73255. return result;
  73256. };
  73257. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73258. var _this = this;
  73259. var numSamples = this.samples;
  73260. this._sampleSphere = this._generateHemisphere();
  73261. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73262. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73263. "base", "range", "projection", "near", "far", "texelSize",
  73264. "xViewport", "yViewport", "maxZ", "minZAspect"
  73265. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73266. this._ssaoPostProcess.onApply = function (effect) {
  73267. if (_this._firstUpdate) {
  73268. effect.setArray3("sampleSphere", _this._sampleSphere);
  73269. effect.setFloat("randTextureTiles", 4.0);
  73270. }
  73271. if (!_this._scene.activeCamera) {
  73272. return;
  73273. }
  73274. effect.setFloat("samplesFactor", 1 / _this.samples);
  73275. effect.setFloat("totalStrength", _this.totalStrength);
  73276. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73277. effect.setFloat("radius", _this.radius);
  73278. effect.setFloat("maxZ", _this.maxZ);
  73279. effect.setFloat("minZAspect", _this.minZAspect);
  73280. effect.setFloat("base", _this.base);
  73281. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73282. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73283. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73284. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73285. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73286. effect.setTexture("textureSampler", _this._depthTexture);
  73287. effect.setTexture("normalSampler", _this._normalTexture);
  73288. effect.setTexture("randomSampler", _this._randomTexture);
  73289. };
  73290. };
  73291. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73292. var _this = this;
  73293. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73294. this._ssaoCombinePostProcess.onApply = function (effect) {
  73295. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73296. };
  73297. };
  73298. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73299. var size = 512;
  73300. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73301. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73302. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73303. var context = this._randomTexture.getContext();
  73304. var rand = function (min, max) {
  73305. return Math.random() * (max - min) + min;
  73306. };
  73307. var randVector = BABYLON.Vector3.Zero();
  73308. for (var x = 0; x < size; x++) {
  73309. for (var y = 0; y < size; y++) {
  73310. randVector.x = rand(0.0, 1.0);
  73311. randVector.y = rand(0.0, 1.0);
  73312. randVector.z = 0.0;
  73313. randVector.normalize();
  73314. randVector.scaleInPlace(255);
  73315. randVector.x = Math.floor(randVector.x);
  73316. randVector.y = Math.floor(randVector.y);
  73317. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73318. context.fillRect(x, y, 1, 1);
  73319. }
  73320. }
  73321. this._randomTexture.update(false);
  73322. };
  73323. /**
  73324. * Serialize the rendering pipeline (Used when exporting)
  73325. * @returns the serialized object
  73326. */
  73327. SSAO2RenderingPipeline.prototype.serialize = function () {
  73328. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73329. serializationObject.customType = "SSAO2RenderingPipeline";
  73330. return serializationObject;
  73331. };
  73332. /**
  73333. * Parse the serialized pipeline
  73334. * @param source Source pipeline.
  73335. * @param scene The scene to load the pipeline to.
  73336. * @param rootUrl The URL of the serialized pipeline.
  73337. * @returns An instantiated pipeline from the serialized object.
  73338. */
  73339. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73340. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73341. };
  73342. __decorate([
  73343. BABYLON.serialize()
  73344. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73345. __decorate([
  73346. BABYLON.serialize()
  73347. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73348. __decorate([
  73349. BABYLON.serialize()
  73350. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73351. __decorate([
  73352. BABYLON.serialize("samples")
  73353. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73354. __decorate([
  73355. BABYLON.serialize()
  73356. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73357. __decorate([
  73358. BABYLON.serialize("expensiveBlur")
  73359. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73360. __decorate([
  73361. BABYLON.serialize()
  73362. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73363. __decorate([
  73364. BABYLON.serialize()
  73365. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73366. return SSAO2RenderingPipeline;
  73367. }(BABYLON.PostProcessRenderPipeline));
  73368. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73369. })(BABYLON || (BABYLON = {}));
  73370. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73371. // BABYLON.JS Chromatic Aberration GLSL Shader
  73372. // Author: Olivier Guyot
  73373. // Separates very slightly R, G and B colors on the edges of the screen
  73374. // Inspired by Francois Tarlier & Martins Upitis
  73375. var BABYLON;
  73376. (function (BABYLON) {
  73377. var LensRenderingPipeline = /** @class */ (function (_super) {
  73378. __extends(LensRenderingPipeline, _super);
  73379. /**
  73380. * @constructor
  73381. *
  73382. * Effect parameters are as follow:
  73383. * {
  73384. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73385. * edge_blur: number; // from 0 to x (1 for realism)
  73386. * distortion: number; // from 0 to x (1 for realism)
  73387. * grain_amount: number; // from 0 to 1
  73388. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73389. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73390. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73391. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73392. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73393. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73394. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73395. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73396. * }
  73397. * Note: if an effect parameter is unset, effect is disabled
  73398. *
  73399. * @param {string} name - The rendering pipeline name
  73400. * @param {object} parameters - An object containing all parameters (see above)
  73401. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73402. * @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)
  73403. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73404. */
  73405. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73406. if (ratio === void 0) { ratio = 1.0; }
  73407. var _this = _super.call(this, scene.getEngine(), name) || this;
  73408. // Lens effects can be of the following:
  73409. // - chromatic aberration (slight shift of RGB colors)
  73410. // - blur on the edge of the lens
  73411. // - lens distortion
  73412. // - depth-of-field blur & highlights enhancing
  73413. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73414. // - grain effect (noise or custom texture)
  73415. // Two additional texture samplers are needed:
  73416. // - depth map (for depth-of-field)
  73417. // - grain texture
  73418. /**
  73419. * The chromatic aberration PostProcess id in the pipeline
  73420. */
  73421. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73422. /**
  73423. * The highlights enhancing PostProcess id in the pipeline
  73424. */
  73425. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73426. /**
  73427. * The depth-of-field PostProcess id in the pipeline
  73428. */
  73429. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73430. _this._scene = scene;
  73431. // Fetch texture samplers
  73432. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73433. if (parameters.grain_texture) {
  73434. _this._grainTexture = parameters.grain_texture;
  73435. }
  73436. else {
  73437. _this._createGrainTexture();
  73438. }
  73439. // save parameters
  73440. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73441. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73442. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73443. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73444. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73445. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73446. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73447. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73448. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73449. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73450. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73451. // Create effects
  73452. _this._createChromaticAberrationPostProcess(ratio);
  73453. _this._createHighlightsPostProcess(ratio);
  73454. _this._createDepthOfFieldPostProcess(ratio / 4);
  73455. // Set up pipeline
  73456. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73457. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73458. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73459. if (_this._highlightsGain === -1) {
  73460. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73461. }
  73462. // Finish
  73463. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73464. if (cameras) {
  73465. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73466. }
  73467. return _this;
  73468. }
  73469. // public methods (self explanatory)
  73470. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73471. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73472. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73473. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73474. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73475. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73476. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73477. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73478. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73479. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73480. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73481. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73482. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73483. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73484. };
  73485. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73486. this._highlightsPostProcess.updateEffect();
  73487. };
  73488. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73489. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73490. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73491. this._highlightsGain = amount;
  73492. };
  73493. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73494. if (this._highlightsGain === -1) {
  73495. this._highlightsGain = 1.0;
  73496. }
  73497. this._highlightsThreshold = amount;
  73498. };
  73499. LensRenderingPipeline.prototype.disableHighlights = function () {
  73500. this._highlightsGain = -1;
  73501. };
  73502. /**
  73503. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73504. */
  73505. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73506. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73507. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73508. this._chromaticAberrationPostProcess = null;
  73509. this._highlightsPostProcess = null;
  73510. this._depthOfFieldPostProcess = null;
  73511. this._grainTexture.dispose();
  73512. if (disableDepthRender)
  73513. this._scene.disableDepthRenderer();
  73514. };
  73515. // colors shifting and distortion
  73516. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73517. var _this = this;
  73518. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73519. [], // samplers
  73520. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73521. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73522. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73523. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73524. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73525. effect.setFloat('radialIntensity', 1);
  73526. effect.setFloat2('direction', 17, 17);
  73527. effect.setFloat2('centerPosition', 0.5, 0.5);
  73528. };
  73529. };
  73530. // highlights enhancing
  73531. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73532. var _this = this;
  73533. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73534. [], // samplers
  73535. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73536. this._highlightsPostProcess.onApply = function (effect) {
  73537. effect.setFloat('gain', _this._highlightsGain);
  73538. effect.setFloat('threshold', _this._highlightsThreshold);
  73539. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73540. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73541. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73542. };
  73543. };
  73544. // colors shifting and distortion
  73545. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73546. var _this = this;
  73547. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73548. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73549. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73550. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73551. this._depthOfFieldPostProcess.onApply = function (effect) {
  73552. effect.setTexture("depthSampler", _this._depthTexture);
  73553. effect.setTexture("grainSampler", _this._grainTexture);
  73554. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73555. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73556. effect.setFloat('grain_amount', _this._grainAmount);
  73557. effect.setBool('blur_noise', _this._blurNoise);
  73558. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73559. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73560. effect.setFloat('distortion', _this._distortion);
  73561. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73562. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73563. effect.setFloat('aperture', _this._dofAperture);
  73564. effect.setFloat('darken', _this._dofDarken);
  73565. effect.setFloat('edge_blur', _this._edgeBlur);
  73566. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73567. if (_this._scene.activeCamera) {
  73568. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73569. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73570. }
  73571. };
  73572. };
  73573. // creates a black and white random noise texture, 512x512
  73574. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73575. var size = 512;
  73576. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73577. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73578. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73579. var context = this._grainTexture.getContext();
  73580. var rand = function (min, max) {
  73581. return Math.random() * (max - min) + min;
  73582. };
  73583. var value;
  73584. for (var x = 0; x < size; x++) {
  73585. for (var y = 0; y < size; y++) {
  73586. value = Math.floor(rand(0.42, 0.58) * 255);
  73587. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73588. context.fillRect(x, y, 1, 1);
  73589. }
  73590. }
  73591. this._grainTexture.update(false);
  73592. };
  73593. return LensRenderingPipeline;
  73594. }(BABYLON.PostProcessRenderPipeline));
  73595. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73596. })(BABYLON || (BABYLON = {}));
  73597. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73598. var BABYLON;
  73599. (function (BABYLON) {
  73600. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73601. __extends(StandardRenderingPipeline, _super);
  73602. /**
  73603. * @constructor
  73604. * @param {string} name - The rendering pipeline name
  73605. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73606. * @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)
  73607. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73608. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73609. */
  73610. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73611. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73612. var _this = _super.call(this, scene.getEngine(), name) || this;
  73613. _this.downSampleX4PostProcess = null;
  73614. _this.brightPassPostProcess = null;
  73615. _this.blurHPostProcesses = [];
  73616. _this.blurVPostProcesses = [];
  73617. _this.textureAdderPostProcess = null;
  73618. _this.volumetricLightPostProcess = null;
  73619. _this.volumetricLightSmoothXPostProcess = null;
  73620. _this.volumetricLightSmoothYPostProcess = null;
  73621. _this.volumetricLightMergePostProces = null;
  73622. _this.volumetricLightFinalPostProcess = null;
  73623. _this.luminancePostProcess = null;
  73624. _this.luminanceDownSamplePostProcesses = [];
  73625. _this.hdrPostProcess = null;
  73626. _this.textureAdderFinalPostProcess = null;
  73627. _this.lensFlareFinalPostProcess = null;
  73628. _this.hdrFinalPostProcess = null;
  73629. _this.lensFlarePostProcess = null;
  73630. _this.lensFlareComposePostProcess = null;
  73631. _this.motionBlurPostProcess = null;
  73632. _this.depthOfFieldPostProcess = null;
  73633. // Values
  73634. _this.brightThreshold = 1.0;
  73635. _this.blurWidth = 512.0;
  73636. _this.horizontalBlur = false;
  73637. _this.exposure = 1.0;
  73638. _this.lensTexture = null;
  73639. _this.volumetricLightCoefficient = 0.2;
  73640. _this.volumetricLightPower = 4.0;
  73641. _this.volumetricLightBlurScale = 64.0;
  73642. _this.sourceLight = null;
  73643. _this.hdrMinimumLuminance = 1.0;
  73644. _this.hdrDecreaseRate = 0.5;
  73645. _this.hdrIncreaseRate = 0.5;
  73646. _this.lensColorTexture = null;
  73647. _this.lensFlareStrength = 20.0;
  73648. _this.lensFlareGhostDispersal = 1.4;
  73649. _this.lensFlareHaloWidth = 0.7;
  73650. _this.lensFlareDistortionStrength = 16.0;
  73651. _this.lensStarTexture = null;
  73652. _this.lensFlareDirtTexture = null;
  73653. _this.depthOfFieldDistance = 10.0;
  73654. _this.depthOfFieldBlurWidth = 64.0;
  73655. _this.motionStrength = 1.0;
  73656. // IAnimatable
  73657. _this.animations = [];
  73658. _this._currentDepthOfFieldSource = null;
  73659. _this._hdrCurrentLuminance = 1.0;
  73660. // Getters and setters
  73661. _this._bloomEnabled = true;
  73662. _this._depthOfFieldEnabled = false;
  73663. _this._vlsEnabled = false;
  73664. _this._lensFlareEnabled = false;
  73665. _this._hdrEnabled = false;
  73666. _this._motionBlurEnabled = false;
  73667. _this._motionBlurSamples = 64.0;
  73668. _this._volumetricLightStepsCount = 50.0;
  73669. _this._cameras = cameras || [];
  73670. // Initialize
  73671. _this._scene = scene;
  73672. _this._basePostProcess = originalPostProcess;
  73673. _this._ratio = ratio;
  73674. // Misc
  73675. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73676. // Finish
  73677. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73678. _this._buildPipeline();
  73679. return _this;
  73680. }
  73681. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73682. get: function () {
  73683. return this._bloomEnabled;
  73684. },
  73685. set: function (enabled) {
  73686. if (this._bloomEnabled === enabled) {
  73687. return;
  73688. }
  73689. this._bloomEnabled = enabled;
  73690. this._buildPipeline();
  73691. },
  73692. enumerable: true,
  73693. configurable: true
  73694. });
  73695. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73696. get: function () {
  73697. return this._depthOfFieldEnabled;
  73698. },
  73699. set: function (enabled) {
  73700. if (this._depthOfFieldEnabled === enabled) {
  73701. return;
  73702. }
  73703. this._depthOfFieldEnabled = enabled;
  73704. this._buildPipeline();
  73705. },
  73706. enumerable: true,
  73707. configurable: true
  73708. });
  73709. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73710. get: function () {
  73711. return this._lensFlareEnabled;
  73712. },
  73713. set: function (enabled) {
  73714. if (this._lensFlareEnabled === enabled) {
  73715. return;
  73716. }
  73717. this._lensFlareEnabled = enabled;
  73718. this._buildPipeline();
  73719. },
  73720. enumerable: true,
  73721. configurable: true
  73722. });
  73723. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73724. get: function () {
  73725. return this._hdrEnabled;
  73726. },
  73727. set: function (enabled) {
  73728. if (this._hdrEnabled === enabled) {
  73729. return;
  73730. }
  73731. this._hdrEnabled = enabled;
  73732. this._buildPipeline();
  73733. },
  73734. enumerable: true,
  73735. configurable: true
  73736. });
  73737. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73738. get: function () {
  73739. return this._vlsEnabled;
  73740. },
  73741. set: function (enabled) {
  73742. if (this._vlsEnabled === enabled) {
  73743. return;
  73744. }
  73745. if (enabled) {
  73746. var geometry = this._scene.enableGeometryBufferRenderer();
  73747. if (!geometry) {
  73748. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73749. return;
  73750. }
  73751. }
  73752. this._vlsEnabled = enabled;
  73753. this._buildPipeline();
  73754. },
  73755. enumerable: true,
  73756. configurable: true
  73757. });
  73758. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73759. get: function () {
  73760. return this._motionBlurEnabled;
  73761. },
  73762. set: function (enabled) {
  73763. if (this._motionBlurEnabled === enabled) {
  73764. return;
  73765. }
  73766. this._motionBlurEnabled = enabled;
  73767. this._buildPipeline();
  73768. },
  73769. enumerable: true,
  73770. configurable: true
  73771. });
  73772. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73773. get: function () {
  73774. return this._volumetricLightStepsCount;
  73775. },
  73776. set: function (count) {
  73777. if (this.volumetricLightPostProcess) {
  73778. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73779. }
  73780. this._volumetricLightStepsCount = count;
  73781. },
  73782. enumerable: true,
  73783. configurable: true
  73784. });
  73785. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  73786. get: function () {
  73787. return this._motionBlurSamples;
  73788. },
  73789. set: function (samples) {
  73790. if (this.motionBlurPostProcess) {
  73791. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  73792. }
  73793. this._motionBlurSamples = samples;
  73794. },
  73795. enumerable: true,
  73796. configurable: true
  73797. });
  73798. StandardRenderingPipeline.prototype._buildPipeline = function () {
  73799. var _this = this;
  73800. var ratio = this._ratio;
  73801. var scene = this._scene;
  73802. this._disposePostProcesses();
  73803. this._reset();
  73804. // Create pass post-process
  73805. if (!this._basePostProcess) {
  73806. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  73807. this.originalPostProcess.onApply = function (effect) {
  73808. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  73809. };
  73810. }
  73811. else {
  73812. this.originalPostProcess = this._basePostProcess;
  73813. }
  73814. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  73815. this._currentDepthOfFieldSource = this.originalPostProcess;
  73816. if (this._bloomEnabled) {
  73817. // Create down sample X4 post-process
  73818. this._createDownSampleX4PostProcess(scene, ratio / 2);
  73819. // Create bright pass post-process
  73820. this._createBrightPassPostProcess(scene, ratio / 2);
  73821. // Create gaussian blur post-processes (down sampling blurs)
  73822. this._createBlurPostProcesses(scene, ratio / 4, 1);
  73823. // Create texture adder post-process
  73824. this._createTextureAdderPostProcess(scene, ratio);
  73825. // Create depth-of-field source post-process
  73826. 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);
  73827. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  73828. }
  73829. if (this._vlsEnabled) {
  73830. // Create volumetric light
  73831. this._createVolumetricLightPostProcess(scene, ratio);
  73832. // Create volumetric light final post-process
  73833. 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);
  73834. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  73835. }
  73836. if (this._lensFlareEnabled) {
  73837. // Create lens flare post-process
  73838. this._createLensFlarePostProcess(scene, ratio);
  73839. // Create depth-of-field source post-process post lens-flare and disable it now
  73840. 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);
  73841. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  73842. }
  73843. if (this._hdrEnabled) {
  73844. // Create luminance
  73845. this._createLuminancePostProcesses(scene, this._floatTextureType);
  73846. // Create HDR
  73847. this._createHdrPostProcess(scene, ratio);
  73848. // Create depth-of-field source post-process post hdr and disable it now
  73849. 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);
  73850. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  73851. }
  73852. if (this._depthOfFieldEnabled) {
  73853. // Create gaussian blur used by depth-of-field
  73854. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  73855. // Create depth-of-field post-process
  73856. this._createDepthOfFieldPostProcess(scene, ratio);
  73857. }
  73858. if (this._motionBlurEnabled) {
  73859. // Create motion blur post-process
  73860. this._createMotionBlurPostProcess(scene, ratio);
  73861. }
  73862. if (this._cameras !== null) {
  73863. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  73864. }
  73865. };
  73866. // Down Sample X4 Post-Processs
  73867. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  73868. var _this = this;
  73869. var downSampleX4Offsets = new Array(32);
  73870. 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);
  73871. this.downSampleX4PostProcess.onApply = function (effect) {
  73872. var id = 0;
  73873. var width = _this.downSampleX4PostProcess.width;
  73874. var height = _this.downSampleX4PostProcess.height;
  73875. for (var i = -2; i < 2; i++) {
  73876. for (var j = -2; j < 2; j++) {
  73877. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  73878. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  73879. id += 2;
  73880. }
  73881. }
  73882. effect.setArray2("dsOffsets", downSampleX4Offsets);
  73883. };
  73884. // Add to pipeline
  73885. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  73886. };
  73887. // Brightpass Post-Process
  73888. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  73889. var _this = this;
  73890. var brightOffsets = new Array(8);
  73891. 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);
  73892. this.brightPassPostProcess.onApply = function (effect) {
  73893. var sU = (1.0 / _this.brightPassPostProcess.width);
  73894. var sV = (1.0 / _this.brightPassPostProcess.height);
  73895. brightOffsets[0] = -0.5 * sU;
  73896. brightOffsets[1] = 0.5 * sV;
  73897. brightOffsets[2] = 0.5 * sU;
  73898. brightOffsets[3] = 0.5 * sV;
  73899. brightOffsets[4] = -0.5 * sU;
  73900. brightOffsets[5] = -0.5 * sV;
  73901. brightOffsets[6] = 0.5 * sU;
  73902. brightOffsets[7] = -0.5 * sV;
  73903. effect.setArray2("dsOffsets", brightOffsets);
  73904. effect.setFloat("brightThreshold", _this.brightThreshold);
  73905. };
  73906. // Add to pipeline
  73907. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  73908. };
  73909. // Create blur H&V post-processes
  73910. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  73911. var _this = this;
  73912. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  73913. var engine = scene.getEngine();
  73914. 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);
  73915. 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);
  73916. blurX.onActivateObservable.add(function () {
  73917. var dw = blurX.width / engine.getRenderWidth();
  73918. blurX.kernel = _this[blurWidthKey] * dw;
  73919. });
  73920. blurY.onActivateObservable.add(function () {
  73921. var dw = blurY.height / engine.getRenderHeight();
  73922. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  73923. });
  73924. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  73925. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  73926. this.blurHPostProcesses.push(blurX);
  73927. this.blurVPostProcesses.push(blurY);
  73928. };
  73929. // Create texture adder post-process
  73930. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  73931. var _this = this;
  73932. 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);
  73933. this.textureAdderPostProcess.onApply = function (effect) {
  73934. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  73935. effect.setTexture("lensSampler", _this.lensTexture);
  73936. effect.setFloat("exposure", _this.exposure);
  73937. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  73938. };
  73939. // Add to pipeline
  73940. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  73941. };
  73942. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  73943. var _this = this;
  73944. var geometryRenderer = scene.enableGeometryBufferRenderer();
  73945. geometryRenderer.enablePosition = true;
  73946. var geometry = geometryRenderer.getGBuffer();
  73947. // Base post-process
  73948. 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));
  73949. var depthValues = BABYLON.Vector2.Zero();
  73950. this.volumetricLightPostProcess.onApply = function (effect) {
  73951. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  73952. var generator = _this.sourceLight.getShadowGenerator();
  73953. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  73954. effect.setTexture("positionSampler", geometry.textures[2]);
  73955. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  73956. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  73957. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  73958. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  73959. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  73960. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  73961. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  73962. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  73963. effect.setVector2("depthValues", depthValues);
  73964. }
  73965. };
  73966. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  73967. // Smooth
  73968. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  73969. // Merge
  73970. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  73971. this.volumetricLightMergePostProces.onApply = function (effect) {
  73972. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  73973. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  73974. };
  73975. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  73976. };
  73977. // Create luminance
  73978. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  73979. var _this = this;
  73980. // Create luminance
  73981. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  73982. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  73983. var offsets = [];
  73984. this.luminancePostProcess.onApply = function (effect) {
  73985. var sU = (1.0 / _this.luminancePostProcess.width);
  73986. var sV = (1.0 / _this.luminancePostProcess.height);
  73987. offsets[0] = -0.5 * sU;
  73988. offsets[1] = 0.5 * sV;
  73989. offsets[2] = 0.5 * sU;
  73990. offsets[3] = 0.5 * sV;
  73991. offsets[4] = -0.5 * sU;
  73992. offsets[5] = -0.5 * sV;
  73993. offsets[6] = 0.5 * sU;
  73994. offsets[7] = -0.5 * sV;
  73995. effect.setArray2("lumOffsets", offsets);
  73996. };
  73997. // Add to pipeline
  73998. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  73999. // Create down sample luminance
  74000. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74001. var size = Math.pow(3, i);
  74002. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74003. if (i === 0) {
  74004. defines += "#define FINAL_DOWN_SAMPLER";
  74005. }
  74006. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74007. this.luminanceDownSamplePostProcesses.push(postProcess);
  74008. }
  74009. // Create callbacks and add effects
  74010. var lastLuminance = this.luminancePostProcess;
  74011. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74012. var downSampleOffsets = new Array(18);
  74013. pp.onApply = function (effect) {
  74014. if (!lastLuminance) {
  74015. return;
  74016. }
  74017. var id = 0;
  74018. for (var x = -1; x < 2; x++) {
  74019. for (var y = -1; y < 2; y++) {
  74020. downSampleOffsets[id] = x / lastLuminance.width;
  74021. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74022. id += 2;
  74023. }
  74024. }
  74025. effect.setArray2("dsOffsets", downSampleOffsets);
  74026. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74027. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74028. lastLuminance = _this.luminancePostProcess;
  74029. }
  74030. else {
  74031. lastLuminance = pp;
  74032. }
  74033. };
  74034. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74035. pp.onAfterRender = function (effect) {
  74036. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74037. 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);
  74038. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74039. };
  74040. }
  74041. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74042. });
  74043. };
  74044. // Create HDR post-process
  74045. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74046. var _this = this;
  74047. 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);
  74048. var outputLiminance = 1;
  74049. var time = 0;
  74050. var lastTime = 0;
  74051. this.hdrPostProcess.onApply = function (effect) {
  74052. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74053. time += scene.getEngine().getDeltaTime();
  74054. if (outputLiminance < 0) {
  74055. outputLiminance = _this._hdrCurrentLuminance;
  74056. }
  74057. else {
  74058. var dt = (lastTime - time) / 1000.0;
  74059. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74060. outputLiminance += _this.hdrDecreaseRate * dt;
  74061. }
  74062. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74063. outputLiminance -= _this.hdrIncreaseRate * dt;
  74064. }
  74065. else {
  74066. outputLiminance = _this._hdrCurrentLuminance;
  74067. }
  74068. }
  74069. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74070. effect.setFloat("averageLuminance", outputLiminance);
  74071. lastTime = time;
  74072. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74073. };
  74074. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74075. };
  74076. // Create lens flare post-process
  74077. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74078. var _this = this;
  74079. 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);
  74080. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74081. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74082. 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);
  74083. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74084. var resolution = new BABYLON.Vector2(0, 0);
  74085. // Lens flare
  74086. this.lensFlarePostProcess.onApply = function (effect) {
  74087. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74088. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74089. effect.setFloat("strength", _this.lensFlareStrength);
  74090. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74091. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74092. // Shift
  74093. resolution.x = _this.lensFlarePostProcess.width;
  74094. resolution.y = _this.lensFlarePostProcess.height;
  74095. effect.setVector2("resolution", resolution);
  74096. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74097. };
  74098. // Compose
  74099. 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);
  74100. 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);
  74101. this.lensFlareComposePostProcess.onApply = function (effect) {
  74102. if (!_this._scene.activeCamera) {
  74103. return;
  74104. }
  74105. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74106. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74107. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74108. // Lens start rotation matrix
  74109. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74110. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74111. 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));
  74112. camRot *= 4.0;
  74113. 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);
  74114. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74115. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74116. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74117. };
  74118. };
  74119. // Create depth-of-field post-process
  74120. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74121. var _this = this;
  74122. 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);
  74123. this.depthOfFieldPostProcess.onApply = function (effect) {
  74124. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74125. effect.setTexture("depthSampler", _this._getDepthTexture());
  74126. effect.setFloat("distance", _this.depthOfFieldDistance);
  74127. };
  74128. // Add to pipeline
  74129. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74130. };
  74131. // Create motion blur post-process
  74132. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74133. var _this = this;
  74134. 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);
  74135. var motionScale = 0;
  74136. var prevViewProjection = BABYLON.Matrix.Identity();
  74137. var invViewProjection = BABYLON.Matrix.Identity();
  74138. var viewProjection = BABYLON.Matrix.Identity();
  74139. var screenSize = BABYLON.Vector2.Zero();
  74140. this.motionBlurPostProcess.onApply = function (effect) {
  74141. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74142. viewProjection.invertToRef(invViewProjection);
  74143. effect.setMatrix("inverseViewProjection", invViewProjection);
  74144. effect.setMatrix("prevViewProjection", prevViewProjection);
  74145. prevViewProjection = viewProjection;
  74146. screenSize.x = _this.motionBlurPostProcess.width;
  74147. screenSize.y = _this.motionBlurPostProcess.height;
  74148. effect.setVector2("screenSize", screenSize);
  74149. motionScale = scene.getEngine().getFps() / 60.0;
  74150. effect.setFloat("motionScale", motionScale);
  74151. effect.setFloat("motionStrength", _this.motionStrength);
  74152. effect.setTexture("depthSampler", _this._getDepthTexture());
  74153. };
  74154. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74155. };
  74156. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74157. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74158. var renderer = this._scene.enableGeometryBufferRenderer();
  74159. return renderer.getGBuffer().textures[0];
  74160. }
  74161. return this._scene.enableDepthRenderer().getDepthMap();
  74162. };
  74163. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74164. for (var i = 0; i < this._cameras.length; i++) {
  74165. var camera = this._cameras[i];
  74166. if (this.originalPostProcess) {
  74167. this.originalPostProcess.dispose(camera);
  74168. }
  74169. if (this.downSampleX4PostProcess) {
  74170. this.downSampleX4PostProcess.dispose(camera);
  74171. }
  74172. if (this.brightPassPostProcess) {
  74173. this.brightPassPostProcess.dispose(camera);
  74174. }
  74175. if (this.textureAdderPostProcess) {
  74176. this.textureAdderPostProcess.dispose(camera);
  74177. }
  74178. if (this.textureAdderFinalPostProcess) {
  74179. this.textureAdderFinalPostProcess.dispose(camera);
  74180. }
  74181. if (this.volumetricLightPostProcess) {
  74182. this.volumetricLightPostProcess.dispose(camera);
  74183. }
  74184. if (this.volumetricLightSmoothXPostProcess) {
  74185. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74186. }
  74187. if (this.volumetricLightSmoothYPostProcess) {
  74188. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74189. }
  74190. if (this.volumetricLightMergePostProces) {
  74191. this.volumetricLightMergePostProces.dispose(camera);
  74192. }
  74193. if (this.volumetricLightFinalPostProcess) {
  74194. this.volumetricLightFinalPostProcess.dispose(camera);
  74195. }
  74196. if (this.lensFlarePostProcess) {
  74197. this.lensFlarePostProcess.dispose(camera);
  74198. }
  74199. if (this.lensFlareComposePostProcess) {
  74200. this.lensFlareComposePostProcess.dispose(camera);
  74201. }
  74202. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74203. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74204. }
  74205. if (this.luminancePostProcess) {
  74206. this.luminancePostProcess.dispose(camera);
  74207. }
  74208. if (this.hdrPostProcess) {
  74209. this.hdrPostProcess.dispose(camera);
  74210. }
  74211. if (this.hdrFinalPostProcess) {
  74212. this.hdrFinalPostProcess.dispose(camera);
  74213. }
  74214. if (this.depthOfFieldPostProcess) {
  74215. this.depthOfFieldPostProcess.dispose(camera);
  74216. }
  74217. if (this.motionBlurPostProcess) {
  74218. this.motionBlurPostProcess.dispose(camera);
  74219. }
  74220. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74221. this.blurHPostProcesses[j].dispose(camera);
  74222. }
  74223. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74224. this.blurVPostProcesses[j].dispose(camera);
  74225. }
  74226. }
  74227. this.originalPostProcess = null;
  74228. this.downSampleX4PostProcess = null;
  74229. this.brightPassPostProcess = null;
  74230. this.textureAdderPostProcess = null;
  74231. this.textureAdderFinalPostProcess = null;
  74232. this.volumetricLightPostProcess = null;
  74233. this.volumetricLightSmoothXPostProcess = null;
  74234. this.volumetricLightSmoothYPostProcess = null;
  74235. this.volumetricLightMergePostProces = null;
  74236. this.volumetricLightFinalPostProcess = null;
  74237. this.lensFlarePostProcess = null;
  74238. this.lensFlareComposePostProcess = null;
  74239. this.luminancePostProcess = null;
  74240. this.hdrPostProcess = null;
  74241. this.hdrFinalPostProcess = null;
  74242. this.depthOfFieldPostProcess = null;
  74243. this.motionBlurPostProcess = null;
  74244. this.luminanceDownSamplePostProcesses = [];
  74245. this.blurHPostProcesses = [];
  74246. this.blurVPostProcesses = [];
  74247. };
  74248. /**
  74249. * Dispose of the pipeline and stop all post processes
  74250. */
  74251. StandardRenderingPipeline.prototype.dispose = function () {
  74252. this._disposePostProcesses();
  74253. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74254. _super.prototype.dispose.call(this);
  74255. };
  74256. /**
  74257. * Serialize the rendering pipeline (Used when exporting)
  74258. * @returns the serialized object
  74259. */
  74260. StandardRenderingPipeline.prototype.serialize = function () {
  74261. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74262. if (this.sourceLight) {
  74263. serializationObject.sourceLightId = this.sourceLight.id;
  74264. }
  74265. serializationObject.customType = "StandardRenderingPipeline";
  74266. return serializationObject;
  74267. };
  74268. /**
  74269. * Parse the serialized pipeline
  74270. * @param source Source pipeline.
  74271. * @param scene The scene to load the pipeline to.
  74272. * @param rootUrl The URL of the serialized pipeline.
  74273. * @returns An instantiated pipeline from the serialized object.
  74274. */
  74275. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74276. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74277. if (source.sourceLightId) {
  74278. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74279. }
  74280. return p;
  74281. };
  74282. // Luminance steps
  74283. StandardRenderingPipeline.LuminanceSteps = 6;
  74284. __decorate([
  74285. BABYLON.serialize()
  74286. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74287. __decorate([
  74288. BABYLON.serialize()
  74289. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74290. __decorate([
  74291. BABYLON.serialize()
  74292. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74293. __decorate([
  74294. BABYLON.serialize()
  74295. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74296. __decorate([
  74297. BABYLON.serializeAsTexture("lensTexture")
  74298. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74299. __decorate([
  74300. BABYLON.serialize()
  74301. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74302. __decorate([
  74303. BABYLON.serialize()
  74304. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74305. __decorate([
  74306. BABYLON.serialize()
  74307. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74308. __decorate([
  74309. BABYLON.serialize()
  74310. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74311. __decorate([
  74312. BABYLON.serialize()
  74313. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74314. __decorate([
  74315. BABYLON.serialize()
  74316. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74317. __decorate([
  74318. BABYLON.serializeAsTexture("lensColorTexture")
  74319. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74320. __decorate([
  74321. BABYLON.serialize()
  74322. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74323. __decorate([
  74324. BABYLON.serialize()
  74325. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74326. __decorate([
  74327. BABYLON.serialize()
  74328. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74329. __decorate([
  74330. BABYLON.serialize()
  74331. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74332. __decorate([
  74333. BABYLON.serializeAsTexture("lensStarTexture")
  74334. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74335. __decorate([
  74336. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74337. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74338. __decorate([
  74339. BABYLON.serialize()
  74340. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74341. __decorate([
  74342. BABYLON.serialize()
  74343. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74344. __decorate([
  74345. BABYLON.serialize()
  74346. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74347. __decorate([
  74348. BABYLON.serialize()
  74349. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74350. __decorate([
  74351. BABYLON.serialize()
  74352. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74353. __decorate([
  74354. BABYLON.serialize()
  74355. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74356. __decorate([
  74357. BABYLON.serialize()
  74358. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74359. __decorate([
  74360. BABYLON.serialize()
  74361. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74362. __decorate([
  74363. BABYLON.serialize()
  74364. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74365. __decorate([
  74366. BABYLON.serialize()
  74367. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74368. __decorate([
  74369. BABYLON.serialize()
  74370. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74371. __decorate([
  74372. BABYLON.serialize()
  74373. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74374. return StandardRenderingPipeline;
  74375. }(BABYLON.PostProcessRenderPipeline));
  74376. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74377. })(BABYLON || (BABYLON = {}));
  74378. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74379. var BABYLON;
  74380. (function (BABYLON) {
  74381. var FxaaPostProcess = /** @class */ (function (_super) {
  74382. __extends(FxaaPostProcess, _super);
  74383. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74384. if (camera === void 0) { camera = null; }
  74385. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74386. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  74387. _this.onApplyObservable.add(function (effect) {
  74388. var texelSize = _this.texelSize;
  74389. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74390. });
  74391. return _this;
  74392. }
  74393. return FxaaPostProcess;
  74394. }(BABYLON.PostProcess));
  74395. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74396. })(BABYLON || (BABYLON = {}));
  74397. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74398. var BABYLON;
  74399. (function (BABYLON) {
  74400. /**
  74401. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74402. */
  74403. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74404. __extends(ChromaticAberrationPostProcess, _super);
  74405. /**
  74406. * Creates a new instance ChromaticAberrationPostProcess
  74407. * @param name The name of the effect.
  74408. * @param screenWidth The width of the screen to apply the effect on.
  74409. * @param screenHeight The height of the screen to apply the effect on.
  74410. * @param options The required width/height ratio to downsize to before computing the render pass.
  74411. * @param camera The camera to apply the render pass to.
  74412. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74413. * @param engine The engine which the post process will be applied. (default: current engine)
  74414. * @param reusable If the post process can be reused on the same frame. (default: false)
  74415. * @param textureType Type of textures used when performing the post process. (default: 0)
  74416. * @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)
  74417. */
  74418. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74419. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74420. if (blockCompilation === void 0) { blockCompilation = false; }
  74421. 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;
  74422. /**
  74423. * The amount of seperation of rgb channels (default: 30)
  74424. */
  74425. _this.aberrationAmount = 30;
  74426. /**
  74427. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74428. */
  74429. _this.radialIntensity = 0;
  74430. /**
  74431. * 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))
  74432. */
  74433. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74434. /**
  74435. * 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))
  74436. */
  74437. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74438. _this.onApplyObservable.add(function (effect) {
  74439. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74440. effect.setFloat('screen_width', screenWidth);
  74441. effect.setFloat('screen_height', screenHeight);
  74442. effect.setFloat('radialIntensity', _this.radialIntensity);
  74443. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74444. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74445. });
  74446. return _this;
  74447. }
  74448. return ChromaticAberrationPostProcess;
  74449. }(BABYLON.PostProcess));
  74450. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74451. })(BABYLON || (BABYLON = {}));
  74452. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74453. var BABYLON;
  74454. (function (BABYLON) {
  74455. /**
  74456. * The GrainPostProcess adds noise to the image at mid luminance levels
  74457. */
  74458. var GrainPostProcess = /** @class */ (function (_super) {
  74459. __extends(GrainPostProcess, _super);
  74460. /**
  74461. * Creates a new instance of @see GrainPostProcess
  74462. * @param name The name of the effect.
  74463. * @param options The required width/height ratio to downsize to before computing the render pass.
  74464. * @param camera The camera to apply the render pass to.
  74465. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74466. * @param engine The engine which the post process will be applied. (default: current engine)
  74467. * @param reusable If the post process can be reused on the same frame. (default: false)
  74468. * @param textureType Type of textures used when performing the post process. (default: 0)
  74469. * @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)
  74470. */
  74471. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74472. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74473. if (blockCompilation === void 0) { blockCompilation = false; }
  74474. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74475. /**
  74476. * The intensity of the grain added (default: 30)
  74477. */
  74478. _this.intensity = 30;
  74479. /**
  74480. * If the grain should be randomized on every frame
  74481. */
  74482. _this.animated = false;
  74483. _this.onApplyObservable.add(function (effect) {
  74484. effect.setFloat('intensity', _this.intensity);
  74485. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74486. });
  74487. return _this;
  74488. }
  74489. return GrainPostProcess;
  74490. }(BABYLON.PostProcess));
  74491. BABYLON.GrainPostProcess = GrainPostProcess;
  74492. })(BABYLON || (BABYLON = {}));
  74493. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74494. var BABYLON;
  74495. (function (BABYLON) {
  74496. /**
  74497. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74498. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74499. */
  74500. var SharpenPostProcess = /** @class */ (function (_super) {
  74501. __extends(SharpenPostProcess, _super);
  74502. /**
  74503. * Creates a new instance ConvolutionPostProcess
  74504. * @param name The name of the effect.
  74505. * @param options The required width/height ratio to downsize to before computing the render pass.
  74506. * @param camera The camera to apply the render pass to.
  74507. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74508. * @param engine The engine which the post process will be applied. (default: current engine)
  74509. * @param reusable If the post process can be reused on the same frame. (default: false)
  74510. * @param textureType Type of textures used when performing the post process. (default: 0)
  74511. * @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)
  74512. */
  74513. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74514. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74515. if (blockCompilation === void 0) { blockCompilation = false; }
  74516. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74517. /**
  74518. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74519. */
  74520. _this.colorAmount = 1.0;
  74521. /**
  74522. * How much sharpness should be applied (default: 0.3)
  74523. */
  74524. _this.edgeAmount = 0.3;
  74525. _this.onApply = function (effect) {
  74526. effect.setFloat2("screenSize", _this.width, _this.height);
  74527. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74528. };
  74529. return _this;
  74530. }
  74531. return SharpenPostProcess;
  74532. }(BABYLON.PostProcess));
  74533. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74534. })(BABYLON || (BABYLON = {}));
  74535. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74536. var BABYLON;
  74537. (function (BABYLON) {
  74538. /**
  74539. * The Blur Post Process which blurs an image based on a kernel and direction.
  74540. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74541. */
  74542. var BlurPostProcess = /** @class */ (function (_super) {
  74543. __extends(BlurPostProcess, _super);
  74544. /**
  74545. * Creates a new instance BlurPostProcess
  74546. * @param name The name of the effect.
  74547. * @param direction The direction in which to blur the image.
  74548. * @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.
  74549. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74550. * @param camera The camera to apply the render pass to.
  74551. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74552. * @param engine The engine which the post process will be applied. (default: current engine)
  74553. * @param reusable If the post process can be reused on the same frame. (default: false)
  74554. * @param textureType Type of textures used when performing the post process. (default: 0)
  74555. * @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)
  74556. */
  74557. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74558. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74559. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74560. if (defines === void 0) { defines = ""; }
  74561. if (blockCompilation === void 0) { blockCompilation = false; }
  74562. 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;
  74563. _this.direction = direction;
  74564. _this.blockCompilation = blockCompilation;
  74565. _this._packedFloat = false;
  74566. _this._staticDefines = "";
  74567. _this._staticDefines = defines;
  74568. _this.onApplyObservable.add(function (effect) {
  74569. if (_this._outputTexture) {
  74570. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74571. }
  74572. else {
  74573. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74574. }
  74575. });
  74576. _this.kernel = kernel;
  74577. return _this;
  74578. }
  74579. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74580. /**
  74581. * Gets the length in pixels of the blur sample region
  74582. */
  74583. get: function () {
  74584. return this._idealKernel;
  74585. },
  74586. /**
  74587. * Sets the length in pixels of the blur sample region
  74588. */
  74589. set: function (v) {
  74590. if (this._idealKernel === v) {
  74591. return;
  74592. }
  74593. v = Math.max(v, 1);
  74594. this._idealKernel = v;
  74595. this._kernel = this._nearestBestKernel(v);
  74596. if (!this.blockCompilation) {
  74597. this._updateParameters();
  74598. }
  74599. },
  74600. enumerable: true,
  74601. configurable: true
  74602. });
  74603. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74604. /**
  74605. * Gets wether or not the blur is unpacking/repacking floats
  74606. */
  74607. get: function () {
  74608. return this._packedFloat;
  74609. },
  74610. /**
  74611. * Sets wether or not the blur needs to unpack/repack floats
  74612. */
  74613. set: function (v) {
  74614. if (this._packedFloat === v) {
  74615. return;
  74616. }
  74617. this._packedFloat = v;
  74618. if (!this.blockCompilation) {
  74619. this._updateParameters();
  74620. }
  74621. },
  74622. enumerable: true,
  74623. configurable: true
  74624. });
  74625. /**
  74626. * Updates the effect with the current post process compile time values and recompiles the shader.
  74627. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74628. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74629. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74630. * @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
  74631. * @param onCompiled Called when the shader has been compiled.
  74632. * @param onError Called if there is an error when compiling a shader.
  74633. */
  74634. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74635. if (defines === void 0) { defines = null; }
  74636. if (uniforms === void 0) { uniforms = null; }
  74637. if (samplers === void 0) { samplers = null; }
  74638. this._updateParameters(onCompiled, onError);
  74639. };
  74640. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74641. // Generate sampling offsets and weights
  74642. var N = this._kernel;
  74643. var centerIndex = (N - 1) / 2;
  74644. // Generate Gaussian sampling weights over kernel
  74645. var offsets = [];
  74646. var weights = [];
  74647. var totalWeight = 0;
  74648. for (var i = 0; i < N; i++) {
  74649. var u = i / (N - 1);
  74650. var w = this._gaussianWeight(u * 2.0 - 1);
  74651. offsets[i] = (i - centerIndex);
  74652. weights[i] = w;
  74653. totalWeight += w;
  74654. }
  74655. // Normalize weights
  74656. for (var i = 0; i < weights.length; i++) {
  74657. weights[i] /= totalWeight;
  74658. }
  74659. // Optimize: combine samples to take advantage of hardware linear sampling
  74660. // Walk from left to center, combining pairs (symmetrically)
  74661. var linearSamplingWeights = [];
  74662. var linearSamplingOffsets = [];
  74663. var linearSamplingMap = [];
  74664. for (var i = 0; i <= centerIndex; i += 2) {
  74665. var j = Math.min(i + 1, Math.floor(centerIndex));
  74666. var singleCenterSample = i === j;
  74667. if (singleCenterSample) {
  74668. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74669. }
  74670. else {
  74671. var sharedCell = j === centerIndex;
  74672. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74673. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74674. if (offsetLinear === 0) {
  74675. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74676. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74677. }
  74678. else {
  74679. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74680. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74681. }
  74682. }
  74683. }
  74684. for (var i = 0; i < linearSamplingMap.length; i++) {
  74685. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74686. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74687. }
  74688. // Replace with optimized
  74689. offsets = linearSamplingOffsets;
  74690. weights = linearSamplingWeights;
  74691. // Generate shaders
  74692. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74693. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74694. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74695. var defines = "";
  74696. defines += this._staticDefines;
  74697. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74698. if (this._staticDefines.indexOf("DOF") != -1) {
  74699. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74700. varyingCount--;
  74701. }
  74702. for (var i = 0; i < varyingCount; i++) {
  74703. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74704. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74705. }
  74706. var depCount = 0;
  74707. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74708. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74709. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74710. depCount++;
  74711. }
  74712. if (this.packedFloat) {
  74713. defines += "#define PACKEDFLOAT 1";
  74714. }
  74715. this.blockCompilation = false;
  74716. _super.prototype.updateEffect.call(this, defines, null, null, {
  74717. varyingCount: varyingCount,
  74718. depCount: depCount
  74719. }, onCompiled, onError);
  74720. };
  74721. /**
  74722. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74723. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74724. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74725. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74726. * The gaps between physical kernels are compensated for in the weighting of the samples
  74727. * @param idealKernel Ideal blur kernel.
  74728. * @return Nearest best kernel.
  74729. */
  74730. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74731. var v = Math.round(idealKernel);
  74732. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74733. var k = _a[_i];
  74734. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74735. return Math.max(k, 3);
  74736. }
  74737. }
  74738. return Math.max(v, 3);
  74739. };
  74740. /**
  74741. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74742. * @param x The point on the Gaussian distribution to sample.
  74743. * @return the value of the Gaussian function at x.
  74744. */
  74745. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74746. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74747. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74748. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74749. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74750. // truncated at around 1.3% of peak strength.
  74751. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74752. var sigma = (1 / 3);
  74753. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74754. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74755. var weight = (1.0 / denominator) * Math.exp(exponent);
  74756. return weight;
  74757. };
  74758. /**
  74759. * Generates a string that can be used as a floating point number in GLSL.
  74760. * @param x Value to print.
  74761. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74762. * @return GLSL float string.
  74763. */
  74764. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74765. if (decimalFigures === void 0) { decimalFigures = 8; }
  74766. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74767. };
  74768. return BlurPostProcess;
  74769. }(BABYLON.PostProcess));
  74770. BABYLON.BlurPostProcess = BlurPostProcess;
  74771. })(BABYLON || (BABYLON = {}));
  74772. //# sourceMappingURL=babylon.blurPostProcess.js.map
  74773. var BABYLON;
  74774. (function (BABYLON) {
  74775. /**
  74776. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  74777. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  74778. * based on samples that have a large difference in distance than the center pixel.
  74779. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74780. */
  74781. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  74782. __extends(DepthOfFieldBlurPostProcess, _super);
  74783. /**
  74784. * Creates a new instance CircleOfConfusionPostProcess
  74785. * @param name The name of the effect.
  74786. * @param scene The scene the effect belongs to.
  74787. * @param direction The direction the blur should be applied.
  74788. * @param kernel The size of the kernel used to blur.
  74789. * @param options The required width/height ratio to downsize to before computing the render pass.
  74790. * @param camera The camera to apply the render pass to.
  74791. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  74792. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  74793. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74794. * @param engine The engine which the post process will be applied. (default: current engine)
  74795. * @param reusable If the post process can be reused on the same frame. (default: false)
  74796. * @param textureType Type of textures used when performing the post process. (default: 0)
  74797. * @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)
  74798. */
  74799. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  74800. if (imageToBlur === void 0) { imageToBlur = null; }
  74801. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74802. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74803. if (blockCompilation === void 0) { blockCompilation = false; }
  74804. 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;
  74805. _this.direction = direction;
  74806. _this.onApplyObservable.add(function (effect) {
  74807. if (imageToBlur != null) {
  74808. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  74809. }
  74810. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74811. if (scene.activeCamera) {
  74812. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74813. }
  74814. });
  74815. return _this;
  74816. }
  74817. return DepthOfFieldBlurPostProcess;
  74818. }(BABYLON.BlurPostProcess));
  74819. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  74820. })(BABYLON || (BABYLON = {}));
  74821. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  74822. var BABYLON;
  74823. (function (BABYLON) {
  74824. /**
  74825. * Options to be set when merging outputs from the default pipeline.
  74826. */
  74827. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  74828. function DepthOfFieldMergePostProcessOptions() {
  74829. }
  74830. return DepthOfFieldMergePostProcessOptions;
  74831. }());
  74832. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  74833. /**
  74834. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74835. */
  74836. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  74837. __extends(DepthOfFieldMergePostProcess, _super);
  74838. /**
  74839. * Creates a new instance of DepthOfFieldMergePostProcess
  74840. * @param name The name of the effect.
  74841. * @param originalFromInput Post process which's input will be used for the merge.
  74842. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  74843. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  74844. * @param options The required width/height ratio to downsize to before computing the render pass.
  74845. * @param camera The camera to apply the render pass to.
  74846. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74847. * @param engine The engine which the post process will be applied. (default: current engine)
  74848. * @param reusable If the post process can be reused on the same frame. (default: false)
  74849. * @param textureType Type of textures used when performing the post process. (default: 0)
  74850. * @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)
  74851. */
  74852. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74853. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74854. if (blockCompilation === void 0) { blockCompilation = false; }
  74855. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  74856. _this.blurSteps = blurSteps;
  74857. _this.onApplyObservable.add(function (effect) {
  74858. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  74859. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74860. blurSteps.forEach(function (step, index) {
  74861. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  74862. });
  74863. });
  74864. if (!blockCompilation) {
  74865. _this.updateEffect();
  74866. }
  74867. return _this;
  74868. }
  74869. /**
  74870. * Updates the effect with the current post process compile time values and recompiles the shader.
  74871. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74872. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74873. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74874. * @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
  74875. * @param onCompiled Called when the shader has been compiled.
  74876. * @param onError Called if there is an error when compiling a shader.
  74877. */
  74878. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74879. if (defines === void 0) { defines = null; }
  74880. if (uniforms === void 0) { uniforms = null; }
  74881. if (samplers === void 0) { samplers = null; }
  74882. if (!defines) {
  74883. defines = "";
  74884. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  74885. }
  74886. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  74887. };
  74888. return DepthOfFieldMergePostProcess;
  74889. }(BABYLON.PostProcess));
  74890. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  74891. })(BABYLON || (BABYLON = {}));
  74892. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  74893. var BABYLON;
  74894. (function (BABYLON) {
  74895. /**
  74896. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  74897. */
  74898. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  74899. __extends(CircleOfConfusionPostProcess, _super);
  74900. /**
  74901. * Creates a new instance CircleOfConfusionPostProcess
  74902. * @param name The name of the effect.
  74903. * @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.
  74904. * @param options The required width/height ratio to downsize to before computing the render pass.
  74905. * @param camera The camera to apply the render pass to.
  74906. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74907. * @param engine The engine which the post process will be applied. (default: current engine)
  74908. * @param reusable If the post process can be reused on the same frame. (default: false)
  74909. * @param textureType Type of textures used when performing the post process. (default: 0)
  74910. * @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)
  74911. */
  74912. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74913. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74914. if (blockCompilation === void 0) { blockCompilation = false; }
  74915. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74916. /**
  74917. * 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.
  74918. */
  74919. _this.lensSize = 50;
  74920. /**
  74921. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  74922. */
  74923. _this.fStop = 1.4;
  74924. /**
  74925. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  74926. */
  74927. _this.focusDistance = 2000;
  74928. /**
  74929. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  74930. */
  74931. _this.focalLength = 50;
  74932. _this._depthTexture = null;
  74933. _this._depthTexture = depthTexture;
  74934. _this.onApplyObservable.add(function (effect) {
  74935. if (!_this._depthTexture) {
  74936. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  74937. return;
  74938. }
  74939. effect.setTexture("depthSampler", _this._depthTexture);
  74940. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  74941. var aperture = _this.lensSize / _this.fStop;
  74942. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  74943. effect.setFloat('focusDistance', _this.focusDistance);
  74944. effect.setFloat('cocPrecalculation', cocPrecalculation);
  74945. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  74946. });
  74947. return _this;
  74948. }
  74949. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  74950. /**
  74951. * 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.
  74952. */
  74953. set: function (value) {
  74954. this._depthTexture = value;
  74955. },
  74956. enumerable: true,
  74957. configurable: true
  74958. });
  74959. return CircleOfConfusionPostProcess;
  74960. }(BABYLON.PostProcess));
  74961. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  74962. })(BABYLON || (BABYLON = {}));
  74963. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  74964. var BABYLON;
  74965. (function (BABYLON) {
  74966. /**
  74967. * Specifies the level of max blur that should be applied when using the depth of field effect
  74968. */
  74969. var DepthOfFieldEffectBlurLevel;
  74970. (function (DepthOfFieldEffectBlurLevel) {
  74971. /**
  74972. * Subtle blur
  74973. */
  74974. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  74975. /**
  74976. * Medium blur
  74977. */
  74978. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  74979. /**
  74980. * Large blur
  74981. */
  74982. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  74983. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  74984. ;
  74985. /**
  74986. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  74987. */
  74988. var DepthOfFieldEffect = /** @class */ (function (_super) {
  74989. __extends(DepthOfFieldEffect, _super);
  74990. /**
  74991. * Creates a new instance DepthOfFieldEffect
  74992. * @param scene The scene the effect belongs to.
  74993. * @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.
  74994. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  74995. * @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)
  74996. */
  74997. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  74998. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  74999. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75000. if (blockCompilation === void 0) { blockCompilation = false; }
  75001. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75002. return _this._effects;
  75003. }, true) || this;
  75004. /**
  75005. * Internal post processes in depth of field effect
  75006. */
  75007. _this._effects = [];
  75008. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75009. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75010. // 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)
  75011. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75012. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75013. _this._depthOfFieldBlurY = [];
  75014. _this._depthOfFieldBlurX = [];
  75015. var blurCount = 1;
  75016. var kernelSize = 15;
  75017. switch (blurLevel) {
  75018. case DepthOfFieldEffectBlurLevel.High: {
  75019. blurCount = 3;
  75020. kernelSize = 51;
  75021. break;
  75022. }
  75023. case DepthOfFieldEffectBlurLevel.Medium: {
  75024. blurCount = 2;
  75025. kernelSize = 31;
  75026. break;
  75027. }
  75028. default: {
  75029. kernelSize = 15;
  75030. blurCount = 1;
  75031. break;
  75032. }
  75033. }
  75034. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75035. var ratio = 1.0;
  75036. for (var i = 0; i < blurCount; i++) {
  75037. 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);
  75038. blurY.autoClear = false;
  75039. ratio = 0.75 / Math.pow(2, i);
  75040. 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);
  75041. blurX.autoClear = false;
  75042. _this._depthOfFieldBlurY.push(blurY);
  75043. _this._depthOfFieldBlurX.push(blurX);
  75044. }
  75045. // Set all post processes on the effect.
  75046. _this._effects = [_this._circleOfConfusion];
  75047. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75048. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75049. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75050. }
  75051. // Merge blurred images with original image based on circleOfConfusion
  75052. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75053. _this._dofMerge.autoClear = false;
  75054. _this._effects.push(_this._dofMerge);
  75055. return _this;
  75056. }
  75057. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75058. get: function () {
  75059. return this._circleOfConfusion.focalLength;
  75060. },
  75061. /**
  75062. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75063. */
  75064. set: function (value) {
  75065. this._circleOfConfusion.focalLength = value;
  75066. },
  75067. enumerable: true,
  75068. configurable: true
  75069. });
  75070. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75071. get: function () {
  75072. return this._circleOfConfusion.fStop;
  75073. },
  75074. /**
  75075. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75076. */
  75077. set: function (value) {
  75078. this._circleOfConfusion.fStop = value;
  75079. },
  75080. enumerable: true,
  75081. configurable: true
  75082. });
  75083. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75084. get: function () {
  75085. return this._circleOfConfusion.focusDistance;
  75086. },
  75087. /**
  75088. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75089. */
  75090. set: function (value) {
  75091. this._circleOfConfusion.focusDistance = value;
  75092. },
  75093. enumerable: true,
  75094. configurable: true
  75095. });
  75096. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75097. get: function () {
  75098. return this._circleOfConfusion.lensSize;
  75099. },
  75100. /**
  75101. * 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.
  75102. */
  75103. set: function (value) {
  75104. this._circleOfConfusion.lensSize = value;
  75105. },
  75106. enumerable: true,
  75107. configurable: true
  75108. });
  75109. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75110. /**
  75111. * 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.
  75112. */
  75113. set: function (value) {
  75114. this._circleOfConfusion.depthTexture = value;
  75115. },
  75116. enumerable: true,
  75117. configurable: true
  75118. });
  75119. /**
  75120. * Disposes each of the internal effects for a given camera.
  75121. * @param camera The camera to dispose the effect on.
  75122. */
  75123. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75124. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75125. this._effects[effectIndex].dispose(camera);
  75126. }
  75127. };
  75128. /**
  75129. * Internal
  75130. */
  75131. DepthOfFieldEffect.prototype._updateEffects = function () {
  75132. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75133. this._effects[effectIndex].updateEffect();
  75134. }
  75135. };
  75136. /**
  75137. * Internal
  75138. * @returns if all the contained post processes are ready.
  75139. */
  75140. DepthOfFieldEffect.prototype._isReady = function () {
  75141. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75142. if (!this._effects[effectIndex].isReady()) {
  75143. return false;
  75144. }
  75145. }
  75146. return true;
  75147. };
  75148. return DepthOfFieldEffect;
  75149. }(BABYLON.PostProcessRenderEffect));
  75150. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75151. })(BABYLON || (BABYLON = {}));
  75152. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75153. var BABYLON;
  75154. (function (BABYLON) {
  75155. /**
  75156. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75157. */
  75158. var BloomMergePostProcess = /** @class */ (function (_super) {
  75159. __extends(BloomMergePostProcess, _super);
  75160. /**
  75161. * Creates a new instance of @see BloomMergePostProcess
  75162. * @param name The name of the effect.
  75163. * @param originalFromInput Post process which's input will be used for the merge.
  75164. * @param blurred Blurred highlights post process which's output will be used.
  75165. * @param weight Weight of the bloom to be added to the original input.
  75166. * @param options The required width/height ratio to downsize to before computing the render pass.
  75167. * @param camera The camera to apply the render pass to.
  75168. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75169. * @param engine The engine which the post process will be applied. (default: current engine)
  75170. * @param reusable If the post process can be reused on the same frame. (default: false)
  75171. * @param textureType Type of textures used when performing the post process. (default: 0)
  75172. * @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)
  75173. */
  75174. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75175. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75176. if (blockCompilation === void 0) { blockCompilation = false; }
  75177. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75178. _this.weight = weight;
  75179. _this.onApplyObservable.add(function (effect) {
  75180. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75181. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75182. effect.setFloat("bloomWeight", _this.weight);
  75183. });
  75184. if (!blockCompilation) {
  75185. _this.updateEffect();
  75186. }
  75187. return _this;
  75188. }
  75189. return BloomMergePostProcess;
  75190. }(BABYLON.PostProcess));
  75191. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75192. })(BABYLON || (BABYLON = {}));
  75193. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75194. var BABYLON;
  75195. (function (BABYLON) {
  75196. /**
  75197. * 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.
  75198. */
  75199. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75200. __extends(ExtractHighlightsPostProcess, _super);
  75201. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75202. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75203. if (blockCompilation === void 0) { blockCompilation = false; }
  75204. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75205. /**
  75206. * The luminance threshold, pixels below this value will be set to black.
  75207. */
  75208. _this.threshold = 0.9;
  75209. /**
  75210. * Internal
  75211. */
  75212. _this._exposure = 1;
  75213. /**
  75214. * Post process which has the input texture to be used when performing highlight extraction
  75215. */
  75216. _this._inputPostProcess = null;
  75217. _this.onApplyObservable.add(function (effect) {
  75218. if (_this._inputPostProcess) {
  75219. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75220. }
  75221. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75222. effect.setFloat('exposure', _this._exposure);
  75223. });
  75224. return _this;
  75225. }
  75226. return ExtractHighlightsPostProcess;
  75227. }(BABYLON.PostProcess));
  75228. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75229. })(BABYLON || (BABYLON = {}));
  75230. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75231. var BABYLON;
  75232. (function (BABYLON) {
  75233. /**
  75234. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75235. */
  75236. var BloomEffect = /** @class */ (function (_super) {
  75237. __extends(BloomEffect, _super);
  75238. /**
  75239. * Creates a new instance of @see BloomEffect
  75240. * @param scene The scene the effect belongs to.
  75241. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75242. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75243. * @param bloomWeight The the strength of bloom.
  75244. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75245. * @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)
  75246. */
  75247. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75248. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75249. if (blockCompilation === void 0) { blockCompilation = false; }
  75250. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75251. return _this._effects;
  75252. }, true) || this;
  75253. _this.bloomScale = bloomScale;
  75254. /**
  75255. * Internal
  75256. */
  75257. _this._effects = [];
  75258. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75259. _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);
  75260. _this._blurX.alwaysForcePOT = true;
  75261. _this._blurX.autoClear = false;
  75262. _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);
  75263. _this._blurY.alwaysForcePOT = true;
  75264. _this._blurY.autoClear = false;
  75265. _this.kernel = bloomKernel;
  75266. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75267. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75268. _this._merge.autoClear = false;
  75269. _this._effects.push(_this._merge);
  75270. return _this;
  75271. }
  75272. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75273. /**
  75274. * The luminance threshold to find bright areas of the image to bloom.
  75275. */
  75276. get: function () {
  75277. return this._downscale.threshold;
  75278. },
  75279. set: function (value) {
  75280. this._downscale.threshold = value;
  75281. },
  75282. enumerable: true,
  75283. configurable: true
  75284. });
  75285. Object.defineProperty(BloomEffect.prototype, "weight", {
  75286. /**
  75287. * The strength of the bloom.
  75288. */
  75289. get: function () {
  75290. return this._merge.weight;
  75291. },
  75292. set: function (value) {
  75293. this._merge.weight = value;
  75294. },
  75295. enumerable: true,
  75296. configurable: true
  75297. });
  75298. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75299. /**
  75300. * Specifies the size of the bloom blur kernel, relative to the final output size
  75301. */
  75302. get: function () {
  75303. return this._blurX.kernel / this.bloomScale;
  75304. },
  75305. set: function (value) {
  75306. this._blurX.kernel = value * this.bloomScale;
  75307. this._blurY.kernel = value * this.bloomScale;
  75308. },
  75309. enumerable: true,
  75310. configurable: true
  75311. });
  75312. /**
  75313. * Disposes each of the internal effects for a given camera.
  75314. * @param camera The camera to dispose the effect on.
  75315. */
  75316. BloomEffect.prototype.disposeEffects = function (camera) {
  75317. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75318. this._effects[effectIndex].dispose(camera);
  75319. }
  75320. };
  75321. /**
  75322. * Internal
  75323. */
  75324. BloomEffect.prototype._updateEffects = function () {
  75325. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75326. this._effects[effectIndex].updateEffect();
  75327. }
  75328. };
  75329. /**
  75330. * Internal
  75331. * @returns if all the contained post processes are ready.
  75332. */
  75333. BloomEffect.prototype._isReady = function () {
  75334. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75335. if (!this._effects[effectIndex].isReady()) {
  75336. return false;
  75337. }
  75338. }
  75339. return true;
  75340. };
  75341. return BloomEffect;
  75342. }(BABYLON.PostProcessRenderEffect));
  75343. BABYLON.BloomEffect = BloomEffect;
  75344. })(BABYLON || (BABYLON = {}));
  75345. //# sourceMappingURL=babylon.bloomEffect.js.map
  75346. var BABYLON;
  75347. (function (BABYLON) {
  75348. /**
  75349. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75350. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75351. */
  75352. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75353. __extends(DefaultRenderingPipeline, _super);
  75354. /**
  75355. * @constructor
  75356. * @param {string} name - The rendering pipeline name
  75357. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75358. * @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)
  75359. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75360. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  75361. */
  75362. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75363. if (automaticBuild === void 0) { automaticBuild = true; }
  75364. var _this = _super.call(this, scene.getEngine(), name) || this;
  75365. _this._originalCameras = [];
  75366. /**
  75367. * ID of the sharpen post process,
  75368. */
  75369. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75370. /**
  75371. * ID of the image processing post process;
  75372. */
  75373. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75374. /**
  75375. * ID of the Fast Approximate Anti-Aliasing post process;
  75376. */
  75377. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75378. /**
  75379. * ID of the chromatic aberration post process,
  75380. */
  75381. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75382. /**
  75383. * ID of the grain post process
  75384. */
  75385. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75386. /**
  75387. * Animations which can be used to tweak settings over a period of time
  75388. */
  75389. _this.animations = [];
  75390. _this._imageProcessingConfigurationObserver = null;
  75391. // Values
  75392. _this._sharpenEnabled = false;
  75393. _this._bloomEnabled = false;
  75394. _this._depthOfFieldEnabled = false;
  75395. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75396. _this._fxaaEnabled = false;
  75397. _this._imageProcessingEnabled = true;
  75398. _this._bloomScale = 0.5;
  75399. _this._chromaticAberrationEnabled = false;
  75400. _this._grainEnabled = false;
  75401. _this._buildAllowed = true;
  75402. _this._resizeObserver = null;
  75403. _this._hardwareScaleLevel = 1.0;
  75404. _this._bloomKernel = 64;
  75405. /**
  75406. * Specifies the weight of the bloom in the final rendering
  75407. */
  75408. _this._bloomWeight = 0.15;
  75409. /**
  75410. * Specifies the luma threshold for the area that will be blurred by the bloom
  75411. */
  75412. _this._bloomThreshold = 0.9;
  75413. _this._samples = 1;
  75414. _this._hasCleared = false;
  75415. _this._prevPostProcess = null;
  75416. _this._prevPrevPostProcess = null;
  75417. _this._cameras = cameras || [];
  75418. _this._originalCameras = _this._cameras.slice();
  75419. _this._buildAllowed = automaticBuild;
  75420. // Initialize
  75421. _this._scene = scene;
  75422. var caps = _this._scene.getEngine().getCaps();
  75423. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75424. // Misc
  75425. if (_this._hdr) {
  75426. if (caps.textureHalfFloatRender) {
  75427. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75428. }
  75429. else if (caps.textureFloatRender) {
  75430. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75431. }
  75432. }
  75433. else {
  75434. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75435. }
  75436. // Attach
  75437. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75438. var engine = _this._scene.getEngine();
  75439. // Create post processes before hand so they can be modified before enabled.
  75440. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75441. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75442. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75443. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75444. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75445. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75446. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75447. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75448. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75449. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75450. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75451. _this.bloomKernel = _this.bloomKernel;
  75452. });
  75453. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75454. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75455. });
  75456. _this._buildPipeline();
  75457. return _this;
  75458. }
  75459. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75460. get: function () {
  75461. return this._sharpenEnabled;
  75462. },
  75463. /**
  75464. * Enable or disable the sharpen process from the pipeline
  75465. */
  75466. set: function (enabled) {
  75467. if (this._sharpenEnabled === enabled) {
  75468. return;
  75469. }
  75470. this._sharpenEnabled = enabled;
  75471. this._buildPipeline();
  75472. },
  75473. enumerable: true,
  75474. configurable: true
  75475. });
  75476. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75477. /**
  75478. * Specifies the size of the bloom blur kernel, relative to the final output size
  75479. */
  75480. get: function () {
  75481. return this._bloomKernel;
  75482. },
  75483. set: function (value) {
  75484. this._bloomKernel = value;
  75485. this.bloom.kernel = value / this._hardwareScaleLevel;
  75486. },
  75487. enumerable: true,
  75488. configurable: true
  75489. });
  75490. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75491. get: function () {
  75492. return this._bloomWeight;
  75493. },
  75494. /**
  75495. * The strength of the bloom.
  75496. */
  75497. set: function (value) {
  75498. if (this._bloomWeight === value) {
  75499. return;
  75500. }
  75501. this.bloom.weight = value;
  75502. this._bloomWeight = value;
  75503. },
  75504. enumerable: true,
  75505. configurable: true
  75506. });
  75507. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75508. get: function () {
  75509. return this._bloomThreshold;
  75510. },
  75511. /**
  75512. * The strength of the bloom.
  75513. */
  75514. set: function (value) {
  75515. if (this._bloomThreshold === value) {
  75516. return;
  75517. }
  75518. this.bloom.threshold = value;
  75519. this._bloomThreshold = value;
  75520. },
  75521. enumerable: true,
  75522. configurable: true
  75523. });
  75524. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75525. get: function () {
  75526. return this._bloomScale;
  75527. },
  75528. /**
  75529. * The scale of the bloom, lower value will provide better performance.
  75530. */
  75531. set: function (value) {
  75532. if (this._bloomScale === value) {
  75533. return;
  75534. }
  75535. this._bloomScale = value;
  75536. // recreate bloom and dispose old as this setting is not dynamic
  75537. this._rebuildBloom();
  75538. this._buildPipeline();
  75539. },
  75540. enumerable: true,
  75541. configurable: true
  75542. });
  75543. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75544. get: function () {
  75545. return this._bloomEnabled;
  75546. },
  75547. /**
  75548. * Enable or disable the bloom from the pipeline
  75549. */
  75550. set: function (enabled) {
  75551. if (this._bloomEnabled === enabled) {
  75552. return;
  75553. }
  75554. this._bloomEnabled = enabled;
  75555. this._buildPipeline();
  75556. },
  75557. enumerable: true,
  75558. configurable: true
  75559. });
  75560. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75561. // recreate bloom and dispose old as this setting is not dynamic
  75562. var oldBloom = this.bloom;
  75563. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75564. this.bloom.threshold = oldBloom.threshold;
  75565. for (var i = 0; i < this._cameras.length; i++) {
  75566. oldBloom.disposeEffects(this._cameras[i]);
  75567. }
  75568. };
  75569. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75570. /**
  75571. * If the depth of field is enabled.
  75572. */
  75573. get: function () {
  75574. return this._depthOfFieldEnabled;
  75575. },
  75576. set: function (enabled) {
  75577. if (this._depthOfFieldEnabled === enabled) {
  75578. return;
  75579. }
  75580. this._depthOfFieldEnabled = enabled;
  75581. this._buildPipeline();
  75582. },
  75583. enumerable: true,
  75584. configurable: true
  75585. });
  75586. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75587. /**
  75588. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75589. */
  75590. get: function () {
  75591. return this._depthOfFieldBlurLevel;
  75592. },
  75593. set: function (value) {
  75594. if (this._depthOfFieldBlurLevel === value) {
  75595. return;
  75596. }
  75597. this._depthOfFieldBlurLevel = value;
  75598. // recreate dof and dispose old as this setting is not dynamic
  75599. var oldDof = this.depthOfField;
  75600. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75601. this.depthOfField.focalLength = oldDof.focalLength;
  75602. this.depthOfField.focusDistance = oldDof.focusDistance;
  75603. this.depthOfField.fStop = oldDof.fStop;
  75604. this.depthOfField.lensSize = oldDof.lensSize;
  75605. for (var i = 0; i < this._cameras.length; i++) {
  75606. oldDof.disposeEffects(this._cameras[i]);
  75607. }
  75608. this._buildPipeline();
  75609. },
  75610. enumerable: true,
  75611. configurable: true
  75612. });
  75613. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75614. get: function () {
  75615. return this._fxaaEnabled;
  75616. },
  75617. /**
  75618. * If the anti aliasing is enabled.
  75619. */
  75620. set: function (enabled) {
  75621. if (this._fxaaEnabled === enabled) {
  75622. return;
  75623. }
  75624. this._fxaaEnabled = enabled;
  75625. this._buildPipeline();
  75626. },
  75627. enumerable: true,
  75628. configurable: true
  75629. });
  75630. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75631. get: function () {
  75632. return this._samples;
  75633. },
  75634. /**
  75635. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75636. */
  75637. set: function (sampleCount) {
  75638. if (this._samples === sampleCount) {
  75639. return;
  75640. }
  75641. this._samples = sampleCount;
  75642. this._buildPipeline();
  75643. },
  75644. enumerable: true,
  75645. configurable: true
  75646. });
  75647. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75648. get: function () {
  75649. return this._imageProcessingEnabled;
  75650. },
  75651. /**
  75652. * If image processing is enabled.
  75653. */
  75654. set: function (enabled) {
  75655. if (this._imageProcessingEnabled === enabled) {
  75656. return;
  75657. }
  75658. this._imageProcessingEnabled = enabled;
  75659. this._buildPipeline();
  75660. },
  75661. enumerable: true,
  75662. configurable: true
  75663. });
  75664. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75665. get: function () {
  75666. return this._chromaticAberrationEnabled;
  75667. },
  75668. /**
  75669. * Enable or disable the chromaticAberration process from the pipeline
  75670. */
  75671. set: function (enabled) {
  75672. if (this._chromaticAberrationEnabled === enabled) {
  75673. return;
  75674. }
  75675. this._chromaticAberrationEnabled = enabled;
  75676. this._buildPipeline();
  75677. },
  75678. enumerable: true,
  75679. configurable: true
  75680. });
  75681. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75682. get: function () {
  75683. return this._grainEnabled;
  75684. },
  75685. /**
  75686. * Enable or disable the grain process from the pipeline
  75687. */
  75688. set: function (enabled) {
  75689. if (this._grainEnabled === enabled) {
  75690. return;
  75691. }
  75692. this._grainEnabled = enabled;
  75693. this._buildPipeline();
  75694. },
  75695. enumerable: true,
  75696. configurable: true
  75697. });
  75698. /**
  75699. * Force the compilation of the entire pipeline.
  75700. */
  75701. DefaultRenderingPipeline.prototype.prepare = function () {
  75702. var previousState = this._buildAllowed;
  75703. this._buildAllowed = true;
  75704. this._buildPipeline();
  75705. this._buildAllowed = previousState;
  75706. };
  75707. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75708. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75709. if (this._hasCleared) {
  75710. postProcess.autoClear = false;
  75711. }
  75712. else {
  75713. postProcess.autoClear = true;
  75714. this._scene.autoClear = false;
  75715. this._hasCleared = true;
  75716. }
  75717. if (!skipTextureSharing) {
  75718. if (this._prevPrevPostProcess) {
  75719. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75720. }
  75721. else {
  75722. postProcess.useOwnOutput();
  75723. }
  75724. if (this._prevPostProcess) {
  75725. this._prevPrevPostProcess = this._prevPostProcess;
  75726. }
  75727. this._prevPostProcess = postProcess;
  75728. }
  75729. };
  75730. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75731. var _this = this;
  75732. if (!this._buildAllowed) {
  75733. return;
  75734. }
  75735. this._scene.autoClear = true;
  75736. var engine = this._scene.getEngine();
  75737. this._disposePostProcesses();
  75738. if (this._cameras !== null) {
  75739. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75740. // get back cameras to be used to reattach pipeline
  75741. this._cameras = this._originalCameras.slice();
  75742. }
  75743. this._reset();
  75744. this._prevPostProcess = null;
  75745. this._prevPrevPostProcess = null;
  75746. this._hasCleared = false;
  75747. if (this.depthOfFieldEnabled) {
  75748. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  75749. this.depthOfField.depthTexture = depthTexture;
  75750. if (!this.depthOfField._isReady()) {
  75751. this.depthOfField._updateEffects();
  75752. }
  75753. this.addEffect(this.depthOfField);
  75754. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  75755. }
  75756. if (this.bloomEnabled) {
  75757. if (!this.bloom._isReady()) {
  75758. this.bloom._updateEffects();
  75759. }
  75760. this.addEffect(this.bloom);
  75761. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  75762. }
  75763. if (this._imageProcessingEnabled) {
  75764. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75765. if (this._hdr) {
  75766. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  75767. this._setAutoClearAndTextureSharing(this.imageProcessing);
  75768. }
  75769. else {
  75770. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  75771. }
  75772. }
  75773. if (this.sharpenEnabled) {
  75774. if (!this.sharpen.isReady()) {
  75775. this.sharpen.updateEffect();
  75776. }
  75777. this.addEffect(this._sharpenEffect);
  75778. this._setAutoClearAndTextureSharing(this.sharpen);
  75779. }
  75780. if (this.grainEnabled) {
  75781. if (!this.grain.isReady()) {
  75782. this.grain.updateEffect();
  75783. }
  75784. this.addEffect(this._grainEffect);
  75785. this._setAutoClearAndTextureSharing(this.grain);
  75786. }
  75787. if (this.chromaticAberrationEnabled) {
  75788. if (!this.chromaticAberration.isReady()) {
  75789. this.chromaticAberration.updateEffect();
  75790. }
  75791. this.addEffect(this._chromaticAberrationEffect);
  75792. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  75793. }
  75794. if (this.fxaaEnabled) {
  75795. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75796. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  75797. this._setAutoClearAndTextureSharing(this.fxaa, true);
  75798. }
  75799. if (this._cameras !== null) {
  75800. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75801. }
  75802. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  75803. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  75804. }
  75805. };
  75806. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  75807. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  75808. for (var i = 0; i < this._cameras.length; i++) {
  75809. var camera = this._cameras[i];
  75810. if (this.imageProcessing) {
  75811. this.imageProcessing.dispose(camera);
  75812. }
  75813. if (this.fxaa) {
  75814. this.fxaa.dispose(camera);
  75815. }
  75816. // These are created in the constructor and should not be disposed on every pipeline change
  75817. if (disposeNonRecreated) {
  75818. if (this.sharpen) {
  75819. this.sharpen.dispose(camera);
  75820. }
  75821. if (this.depthOfField) {
  75822. this.depthOfField.disposeEffects(camera);
  75823. }
  75824. if (this.bloom) {
  75825. this.bloom.disposeEffects(camera);
  75826. }
  75827. if (this.chromaticAberration) {
  75828. this.chromaticAberration.dispose(camera);
  75829. }
  75830. if (this.grain) {
  75831. this.grain.dispose(camera);
  75832. }
  75833. }
  75834. }
  75835. this.imageProcessing = null;
  75836. this.fxaa = null;
  75837. if (disposeNonRecreated) {
  75838. this.sharpen = null;
  75839. this._sharpenEffect = null;
  75840. this.depthOfField = null;
  75841. this.bloom = null;
  75842. this.chromaticAberration = null;
  75843. this._chromaticAberrationEffect = null;
  75844. this.grain = null;
  75845. this._grainEffect = null;
  75846. }
  75847. };
  75848. /**
  75849. * Dispose of the pipeline and stop all post processes
  75850. */
  75851. DefaultRenderingPipeline.prototype.dispose = function () {
  75852. this._disposePostProcesses(true);
  75853. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75854. this._scene.autoClear = true;
  75855. if (this._resizeObserver) {
  75856. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  75857. this._resizeObserver = null;
  75858. }
  75859. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  75860. _super.prototype.dispose.call(this);
  75861. };
  75862. /**
  75863. * Serialize the rendering pipeline (Used when exporting)
  75864. * @returns the serialized object
  75865. */
  75866. DefaultRenderingPipeline.prototype.serialize = function () {
  75867. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75868. serializationObject.customType = "DefaultRenderingPipeline";
  75869. return serializationObject;
  75870. };
  75871. /**
  75872. * Parse the serialized pipeline
  75873. * @param source Source pipeline.
  75874. * @param scene The scene to load the pipeline to.
  75875. * @param rootUrl The URL of the serialized pipeline.
  75876. * @returns An instantiated pipeline from the serialized object.
  75877. */
  75878. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75879. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  75880. };
  75881. __decorate([
  75882. BABYLON.serialize()
  75883. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  75884. __decorate([
  75885. BABYLON.serialize()
  75886. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  75887. __decorate([
  75888. BABYLON.serialize()
  75889. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  75890. __decorate([
  75891. BABYLON.serialize()
  75892. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  75893. __decorate([
  75894. BABYLON.serialize()
  75895. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  75896. __decorate([
  75897. BABYLON.serialize()
  75898. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  75899. __decorate([
  75900. BABYLON.serialize()
  75901. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  75902. __decorate([
  75903. BABYLON.serialize()
  75904. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  75905. __decorate([
  75906. BABYLON.serialize()
  75907. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  75908. __decorate([
  75909. BABYLON.serialize()
  75910. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  75911. __decorate([
  75912. BABYLON.serialize()
  75913. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  75914. __decorate([
  75915. BABYLON.serialize()
  75916. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  75917. __decorate([
  75918. BABYLON.serialize()
  75919. ], DefaultRenderingPipeline.prototype, "samples", null);
  75920. __decorate([
  75921. BABYLON.serialize()
  75922. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  75923. __decorate([
  75924. BABYLON.serialize()
  75925. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  75926. __decorate([
  75927. BABYLON.serialize()
  75928. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  75929. return DefaultRenderingPipeline;
  75930. }(BABYLON.PostProcessRenderPipeline));
  75931. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  75932. })(BABYLON || (BABYLON = {}));
  75933. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  75934. var BABYLON;
  75935. (function (BABYLON) {
  75936. /**
  75937. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  75938. */
  75939. var GeometryBufferRenderer = /** @class */ (function () {
  75940. /**
  75941. * Creates a new G Buffer for the scene
  75942. * @param scene The scene the buffer belongs to
  75943. * @param ratio How big is the buffer related to the main canvas.
  75944. */
  75945. function GeometryBufferRenderer(scene, ratio) {
  75946. if (ratio === void 0) { ratio = 1; }
  75947. this._enablePosition = false;
  75948. this._scene = scene;
  75949. this._ratio = ratio;
  75950. // Render target
  75951. this._createRenderTargets();
  75952. }
  75953. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  75954. /**
  75955. * Set the render list (meshes to be rendered) used in the G buffer.
  75956. */
  75957. set: function (meshes) {
  75958. this._multiRenderTarget.renderList = meshes;
  75959. },
  75960. enumerable: true,
  75961. configurable: true
  75962. });
  75963. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  75964. /**
  75965. * Gets wether or not G buffer are supported by the running hardware.
  75966. * This requires draw buffer supports
  75967. */
  75968. get: function () {
  75969. return this._multiRenderTarget.isSupported;
  75970. },
  75971. enumerable: true,
  75972. configurable: true
  75973. });
  75974. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  75975. /**
  75976. * Gets wether or not position are enabled for the G buffer.
  75977. */
  75978. get: function () {
  75979. return this._enablePosition;
  75980. },
  75981. /**
  75982. * Sets wether or not position are enabled for the G buffer.
  75983. */
  75984. set: function (enable) {
  75985. this._enablePosition = enable;
  75986. this.dispose();
  75987. this._createRenderTargets();
  75988. },
  75989. enumerable: true,
  75990. configurable: true
  75991. });
  75992. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  75993. /**
  75994. * Gets the scene associated with the buffer.
  75995. */
  75996. get: function () {
  75997. return this._scene;
  75998. },
  75999. enumerable: true,
  76000. configurable: true
  76001. });
  76002. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76003. /**
  76004. * Gets the ratio used by the buffer during its creation.
  76005. * How big is the buffer related to the main canvas.
  76006. */
  76007. get: function () {
  76008. return this._ratio;
  76009. },
  76010. enumerable: true,
  76011. configurable: true
  76012. });
  76013. /**
  76014. * Checks wether everything is ready to render a submesh to the G buffer.
  76015. * @param subMesh the submesh to check readiness for
  76016. * @param useInstances is the mesh drawn using instance or not
  76017. * @returns true if ready otherwise false
  76018. */
  76019. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76020. var material = subMesh.getMaterial();
  76021. if (material && material.disableDepthWrite) {
  76022. return false;
  76023. }
  76024. var defines = [];
  76025. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76026. var mesh = subMesh.getMesh();
  76027. // Alpha test
  76028. if (material && material.needAlphaTesting()) {
  76029. defines.push("#define ALPHATEST");
  76030. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76031. attribs.push(BABYLON.VertexBuffer.UVKind);
  76032. defines.push("#define UV1");
  76033. }
  76034. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76035. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76036. defines.push("#define UV2");
  76037. }
  76038. }
  76039. // Buffers
  76040. if (this._enablePosition) {
  76041. defines.push("#define POSITION");
  76042. }
  76043. // Bones
  76044. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76045. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76046. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76047. if (mesh.numBoneInfluencers > 4) {
  76048. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76049. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76050. }
  76051. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76052. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76053. }
  76054. else {
  76055. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76056. }
  76057. // Instances
  76058. if (useInstances) {
  76059. defines.push("#define INSTANCES");
  76060. attribs.push("world0");
  76061. attribs.push("world1");
  76062. attribs.push("world2");
  76063. attribs.push("world3");
  76064. }
  76065. // Get correct effect
  76066. var join = defines.join("\n");
  76067. if (this._cachedDefines !== join) {
  76068. this._cachedDefines = join;
  76069. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76070. }
  76071. return this._effect.isReady();
  76072. };
  76073. /**
  76074. * Gets the current underlying G Buffer.
  76075. * @returns the buffer
  76076. */
  76077. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76078. return this._multiRenderTarget;
  76079. };
  76080. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76081. /**
  76082. * Gets the number of samples used to render the buffer (anti aliasing).
  76083. */
  76084. get: function () {
  76085. return this._multiRenderTarget.samples;
  76086. },
  76087. /**
  76088. * Sets the number of samples used to render the buffer (anti aliasing).
  76089. */
  76090. set: function (value) {
  76091. this._multiRenderTarget.samples = value;
  76092. },
  76093. enumerable: true,
  76094. configurable: true
  76095. });
  76096. /**
  76097. * Disposes the renderer and frees up associated resources.
  76098. */
  76099. GeometryBufferRenderer.prototype.dispose = function () {
  76100. this.getGBuffer().dispose();
  76101. };
  76102. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76103. var _this = this;
  76104. var engine = this._scene.getEngine();
  76105. var count = this._enablePosition ? 3 : 2;
  76106. 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 });
  76107. if (!this.isSupported) {
  76108. return;
  76109. }
  76110. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76111. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76112. this._multiRenderTarget.refreshRate = 1;
  76113. this._multiRenderTarget.renderParticles = false;
  76114. this._multiRenderTarget.renderList = null;
  76115. // set default depth value to 1.0 (far away)
  76116. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76117. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76118. });
  76119. // Custom render function
  76120. var renderSubMesh = function (subMesh) {
  76121. var mesh = subMesh.getRenderingMesh();
  76122. var scene = _this._scene;
  76123. var engine = scene.getEngine();
  76124. var material = subMesh.getMaterial();
  76125. if (!material) {
  76126. return;
  76127. }
  76128. // Culling
  76129. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76130. // Managing instances
  76131. var batch = mesh._getInstancesRenderList(subMesh._id);
  76132. if (batch.mustReturn) {
  76133. return;
  76134. }
  76135. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76136. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76137. engine.enableEffect(_this._effect);
  76138. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76139. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76140. _this._effect.setMatrix("view", scene.getViewMatrix());
  76141. // Alpha test
  76142. if (material && material.needAlphaTesting()) {
  76143. var alphaTexture = material.getAlphaTestTexture();
  76144. if (alphaTexture) {
  76145. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76146. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76147. }
  76148. }
  76149. // Bones
  76150. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76151. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76152. }
  76153. // Draw
  76154. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76155. }
  76156. };
  76157. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76158. var index;
  76159. if (depthOnlySubMeshes.length) {
  76160. engine.setColorWrite(false);
  76161. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76162. renderSubMesh(depthOnlySubMeshes.data[index]);
  76163. }
  76164. engine.setColorWrite(true);
  76165. }
  76166. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76167. renderSubMesh(opaqueSubMeshes.data[index]);
  76168. }
  76169. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76170. renderSubMesh(alphaTestSubMeshes.data[index]);
  76171. }
  76172. };
  76173. };
  76174. return GeometryBufferRenderer;
  76175. }());
  76176. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76177. })(BABYLON || (BABYLON = {}));
  76178. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76179. var BABYLON;
  76180. (function (BABYLON) {
  76181. var RefractionPostProcess = /** @class */ (function (_super) {
  76182. __extends(RefractionPostProcess, _super);
  76183. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76184. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76185. _this.color = color;
  76186. _this.depth = depth;
  76187. _this.colorLevel = colorLevel;
  76188. _this._ownRefractionTexture = true;
  76189. _this.onActivateObservable.add(function (cam) {
  76190. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76191. });
  76192. _this.onApplyObservable.add(function (effect) {
  76193. effect.setColor3("baseColor", _this.color);
  76194. effect.setFloat("depth", _this.depth);
  76195. effect.setFloat("colorLevel", _this.colorLevel);
  76196. effect.setTexture("refractionSampler", _this._refTexture);
  76197. });
  76198. return _this;
  76199. }
  76200. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76201. /**
  76202. * Gets or sets the refraction texture
  76203. * Please note that you are responsible for disposing the texture if you set it manually
  76204. */
  76205. get: function () {
  76206. return this._refTexture;
  76207. },
  76208. set: function (value) {
  76209. if (this._refTexture && this._ownRefractionTexture) {
  76210. this._refTexture.dispose();
  76211. }
  76212. this._refTexture = value;
  76213. this._ownRefractionTexture = false;
  76214. },
  76215. enumerable: true,
  76216. configurable: true
  76217. });
  76218. // Methods
  76219. RefractionPostProcess.prototype.dispose = function (camera) {
  76220. if (this._refTexture && this._ownRefractionTexture) {
  76221. this._refTexture.dispose();
  76222. this._refTexture = null;
  76223. }
  76224. _super.prototype.dispose.call(this, camera);
  76225. };
  76226. return RefractionPostProcess;
  76227. }(BABYLON.PostProcess));
  76228. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76229. })(BABYLON || (BABYLON = {}));
  76230. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76231. var BABYLON;
  76232. (function (BABYLON) {
  76233. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76234. __extends(BlackAndWhitePostProcess, _super);
  76235. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76236. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76237. _this.degree = 1;
  76238. _this.onApplyObservable.add(function (effect) {
  76239. effect.setFloat("degree", _this.degree);
  76240. });
  76241. return _this;
  76242. }
  76243. return BlackAndWhitePostProcess;
  76244. }(BABYLON.PostProcess));
  76245. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76246. })(BABYLON || (BABYLON = {}));
  76247. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76248. var BABYLON;
  76249. (function (BABYLON) {
  76250. /**
  76251. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76252. * input texture to perform effects such as edge detection or sharpening
  76253. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76254. */
  76255. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76256. __extends(ConvolutionPostProcess, _super);
  76257. /**
  76258. * Creates a new instance ConvolutionPostProcess
  76259. * @param name The name of the effect.
  76260. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76261. * @param options The required width/height ratio to downsize to before computing the render pass.
  76262. * @param camera The camera to apply the render pass to.
  76263. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76264. * @param engine The engine which the post process will be applied. (default: current engine)
  76265. * @param reusable If the post process can be reused on the same frame. (default: false)
  76266. * @param textureType Type of textures used when performing the post process. (default: 0)
  76267. */
  76268. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76269. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76270. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76271. _this.kernel = kernel;
  76272. _this.onApply = function (effect) {
  76273. effect.setFloat2("screenSize", _this.width, _this.height);
  76274. effect.setArray("kernel", _this.kernel);
  76275. };
  76276. return _this;
  76277. }
  76278. // Statics
  76279. /**
  76280. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76281. */
  76282. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  76283. /**
  76284. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76285. */
  76286. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  76287. /**
  76288. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76289. */
  76290. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  76291. /**
  76292. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76293. */
  76294. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  76295. /**
  76296. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76297. */
  76298. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  76299. /**
  76300. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76301. */
  76302. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  76303. return ConvolutionPostProcess;
  76304. }(BABYLON.PostProcess));
  76305. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  76306. })(BABYLON || (BABYLON = {}));
  76307. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  76308. var BABYLON;
  76309. (function (BABYLON) {
  76310. var FilterPostProcess = /** @class */ (function (_super) {
  76311. __extends(FilterPostProcess, _super);
  76312. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  76313. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  76314. _this.kernelMatrix = kernelMatrix;
  76315. _this.onApply = function (effect) {
  76316. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  76317. };
  76318. return _this;
  76319. }
  76320. return FilterPostProcess;
  76321. }(BABYLON.PostProcess));
  76322. BABYLON.FilterPostProcess = FilterPostProcess;
  76323. })(BABYLON || (BABYLON = {}));
  76324. //# sourceMappingURL=babylon.filterPostProcess.js.map
  76325. var BABYLON;
  76326. (function (BABYLON) {
  76327. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  76328. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  76329. __extends(VolumetricLightScatteringPostProcess, _super);
  76330. /**
  76331. * @constructor
  76332. * @param {string} name - The post-process name
  76333. * @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)
  76334. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  76335. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  76336. * @param {number} samples - The post-process quality, default 100
  76337. * @param {number} samplingMode - The post-process filtering mode
  76338. * @param {BABYLON.Engine} engine - The babylon engine
  76339. * @param {boolean} reusable - If the post-process is reusable
  76340. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  76341. */
  76342. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  76343. if (samples === void 0) { samples = 100; }
  76344. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76345. 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;
  76346. _this._screenCoordinates = BABYLON.Vector2.Zero();
  76347. /**
  76348. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  76349. */
  76350. _this.customMeshPosition = BABYLON.Vector3.Zero();
  76351. /**
  76352. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  76353. */
  76354. _this.useCustomMeshPosition = false;
  76355. /**
  76356. * If the post-process should inverse the light scattering direction
  76357. */
  76358. _this.invert = true;
  76359. /**
  76360. * Array containing the excluded meshes not rendered in the internal pass
  76361. */
  76362. _this.excludedMeshes = new Array();
  76363. /**
  76364. * Controls the overall intensity of the post-process
  76365. */
  76366. _this.exposure = 0.3;
  76367. /**
  76368. * Dissipates each sample's contribution in range [0, 1]
  76369. */
  76370. _this.decay = 0.96815;
  76371. /**
  76372. * Controls the overall intensity of each sample
  76373. */
  76374. _this.weight = 0.58767;
  76375. /**
  76376. * Controls the density of each sample
  76377. */
  76378. _this.density = 0.926;
  76379. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  76380. engine = scene.getEngine();
  76381. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  76382. // Configure mesh
  76383. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  76384. // Configure
  76385. _this._createPass(scene, ratio.passRatio || ratio);
  76386. _this.onActivate = function (camera) {
  76387. if (!_this.isSupported) {
  76388. _this.dispose(camera);
  76389. }
  76390. _this.onActivate = null;
  76391. };
  76392. _this.onApplyObservable.add(function (effect) {
  76393. _this._updateMeshScreenCoordinates(scene);
  76394. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  76395. effect.setFloat("exposure", _this.exposure);
  76396. effect.setFloat("decay", _this.decay);
  76397. effect.setFloat("weight", _this.weight);
  76398. effect.setFloat("density", _this.density);
  76399. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  76400. });
  76401. return _this;
  76402. }
  76403. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  76404. get: function () {
  76405. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76406. return false;
  76407. },
  76408. set: function (useDiffuseColor) {
  76409. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76410. },
  76411. enumerable: true,
  76412. configurable: true
  76413. });
  76414. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  76415. return "VolumetricLightScatteringPostProcess";
  76416. };
  76417. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  76418. var mesh = subMesh.getMesh();
  76419. // Render this.mesh as default
  76420. if (mesh === this.mesh && mesh.material) {
  76421. return mesh.material.isReady(mesh);
  76422. }
  76423. var defines = [];
  76424. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76425. var material = subMesh.getMaterial();
  76426. // Alpha test
  76427. if (material) {
  76428. if (material.needAlphaTesting()) {
  76429. defines.push("#define ALPHATEST");
  76430. }
  76431. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76432. attribs.push(BABYLON.VertexBuffer.UVKind);
  76433. defines.push("#define UV1");
  76434. }
  76435. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76436. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76437. defines.push("#define UV2");
  76438. }
  76439. }
  76440. // Bones
  76441. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76442. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76443. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76444. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76445. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  76446. }
  76447. else {
  76448. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76449. }
  76450. // Instances
  76451. if (useInstances) {
  76452. defines.push("#define INSTANCES");
  76453. attribs.push("world0");
  76454. attribs.push("world1");
  76455. attribs.push("world2");
  76456. attribs.push("world3");
  76457. }
  76458. // Get correct effect
  76459. var join = defines.join("\n");
  76460. if (this._cachedDefines !== join) {
  76461. this._cachedDefines = join;
  76462. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  76463. }
  76464. return this._volumetricLightScatteringPass.isReady();
  76465. };
  76466. /**
  76467. * Sets the new light position for light scattering effect
  76468. * @param {BABYLON.Vector3} The new custom light position
  76469. */
  76470. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  76471. this.customMeshPosition = position;
  76472. };
  76473. /**
  76474. * Returns the light position for light scattering effect
  76475. * @return {BABYLON.Vector3} The custom light position
  76476. */
  76477. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  76478. return this.customMeshPosition;
  76479. };
  76480. /**
  76481. * Disposes the internal assets and detaches the post-process from the camera
  76482. */
  76483. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  76484. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  76485. if (rttIndex !== -1) {
  76486. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  76487. }
  76488. this._volumetricLightScatteringRTT.dispose();
  76489. _super.prototype.dispose.call(this, camera);
  76490. };
  76491. /**
  76492. * Returns the render target texture used by the post-process
  76493. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  76494. */
  76495. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  76496. return this._volumetricLightScatteringRTT;
  76497. };
  76498. // Private methods
  76499. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  76500. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  76501. return true;
  76502. }
  76503. return false;
  76504. };
  76505. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  76506. var _this = this;
  76507. var engine = scene.getEngine();
  76508. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76509. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76510. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76511. this._volumetricLightScatteringRTT.renderList = null;
  76512. this._volumetricLightScatteringRTT.renderParticles = false;
  76513. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  76514. var camera = this.getCamera();
  76515. if (camera) {
  76516. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76517. }
  76518. else {
  76519. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76520. }
  76521. // Custom render function for submeshes
  76522. var renderSubMesh = function (subMesh) {
  76523. var mesh = subMesh.getRenderingMesh();
  76524. if (_this._meshExcluded(mesh)) {
  76525. return;
  76526. }
  76527. var material = subMesh.getMaterial();
  76528. if (!material) {
  76529. return;
  76530. }
  76531. var scene = mesh.getScene();
  76532. var engine = scene.getEngine();
  76533. // Culling
  76534. engine.setState(material.backFaceCulling);
  76535. // Managing instances
  76536. var batch = mesh._getInstancesRenderList(subMesh._id);
  76537. if (batch.mustReturn) {
  76538. return;
  76539. }
  76540. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76541. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  76542. var effect = _this._volumetricLightScatteringPass;
  76543. if (mesh === _this.mesh) {
  76544. if (subMesh.effect) {
  76545. effect = subMesh.effect;
  76546. }
  76547. else {
  76548. effect = material.getEffect();
  76549. }
  76550. }
  76551. engine.enableEffect(effect);
  76552. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  76553. if (mesh === _this.mesh) {
  76554. material.bind(mesh.getWorldMatrix(), mesh);
  76555. }
  76556. else {
  76557. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  76558. // Alpha test
  76559. if (material && material.needAlphaTesting()) {
  76560. var alphaTexture = material.getAlphaTestTexture();
  76561. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  76562. if (alphaTexture) {
  76563. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76564. }
  76565. }
  76566. // Bones
  76567. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76568. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76569. }
  76570. }
  76571. // Draw
  76572. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  76573. }
  76574. };
  76575. // Render target texture callbacks
  76576. var savedSceneClearColor;
  76577. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  76578. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  76579. savedSceneClearColor = scene.clearColor;
  76580. scene.clearColor = sceneClearColor;
  76581. });
  76582. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  76583. scene.clearColor = savedSceneClearColor;
  76584. });
  76585. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76586. var engine = scene.getEngine();
  76587. var index;
  76588. if (depthOnlySubMeshes.length) {
  76589. engine.setColorWrite(false);
  76590. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76591. renderSubMesh(depthOnlySubMeshes.data[index]);
  76592. }
  76593. engine.setColorWrite(true);
  76594. }
  76595. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76596. renderSubMesh(opaqueSubMeshes.data[index]);
  76597. }
  76598. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76599. renderSubMesh(alphaTestSubMeshes.data[index]);
  76600. }
  76601. if (transparentSubMeshes.length) {
  76602. // Sort sub meshes
  76603. for (index = 0; index < transparentSubMeshes.length; index++) {
  76604. var submesh = transparentSubMeshes.data[index];
  76605. var boundingInfo = submesh.getBoundingInfo();
  76606. if (boundingInfo && scene.activeCamera) {
  76607. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  76608. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  76609. }
  76610. }
  76611. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  76612. sortedArray.sort(function (a, b) {
  76613. // Alpha index first
  76614. if (a._alphaIndex > b._alphaIndex) {
  76615. return 1;
  76616. }
  76617. if (a._alphaIndex < b._alphaIndex) {
  76618. return -1;
  76619. }
  76620. // Then distance to camera
  76621. if (a._distanceToCamera < b._distanceToCamera) {
  76622. return 1;
  76623. }
  76624. if (a._distanceToCamera > b._distanceToCamera) {
  76625. return -1;
  76626. }
  76627. return 0;
  76628. });
  76629. // Render sub meshes
  76630. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  76631. for (index = 0; index < sortedArray.length; index++) {
  76632. renderSubMesh(sortedArray[index]);
  76633. }
  76634. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76635. }
  76636. };
  76637. };
  76638. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  76639. var transform = scene.getTransformMatrix();
  76640. var meshPosition;
  76641. if (this.useCustomMeshPosition) {
  76642. meshPosition = this.customMeshPosition;
  76643. }
  76644. else if (this.attachedNode) {
  76645. meshPosition = this.attachedNode.position;
  76646. }
  76647. else {
  76648. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  76649. }
  76650. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  76651. this._screenCoordinates.x = pos.x / this._viewPort.width;
  76652. this._screenCoordinates.y = pos.y / this._viewPort.height;
  76653. if (this.invert)
  76654. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  76655. };
  76656. // Static methods
  76657. /**
  76658. * Creates a default mesh for the Volumeric Light Scattering post-process
  76659. * @param {string} The mesh name
  76660. * @param {BABYLON.Scene} The scene where to create the mesh
  76661. * @return {BABYLON.Mesh} the default mesh
  76662. */
  76663. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  76664. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  76665. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  76666. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  76667. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  76668. mesh.material = material;
  76669. return mesh;
  76670. };
  76671. __decorate([
  76672. BABYLON.serializeAsVector3()
  76673. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  76674. __decorate([
  76675. BABYLON.serialize()
  76676. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  76677. __decorate([
  76678. BABYLON.serialize()
  76679. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  76680. __decorate([
  76681. BABYLON.serializeAsMeshReference()
  76682. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  76683. __decorate([
  76684. BABYLON.serialize()
  76685. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  76686. __decorate([
  76687. BABYLON.serialize()
  76688. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  76689. __decorate([
  76690. BABYLON.serialize()
  76691. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  76692. __decorate([
  76693. BABYLON.serialize()
  76694. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  76695. __decorate([
  76696. BABYLON.serialize()
  76697. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  76698. return VolumetricLightScatteringPostProcess;
  76699. }(BABYLON.PostProcess));
  76700. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  76701. })(BABYLON || (BABYLON = {}));
  76702. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  76703. //
  76704. // This post-process allows the modification of rendered colors by using
  76705. // a 'look-up table' (LUT). This effect is also called Color Grading.
  76706. //
  76707. // The object needs to be provided an url to a texture containing the color
  76708. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  76709. // Use an image editing software to tweak the LUT to match your needs.
  76710. //
  76711. // For an example of a color LUT, see here:
  76712. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  76713. // For explanations on color grading, see here:
  76714. // http://udn.epicgames.com/Three/ColorGrading.html
  76715. //
  76716. var BABYLON;
  76717. (function (BABYLON) {
  76718. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  76719. __extends(ColorCorrectionPostProcess, _super);
  76720. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  76721. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  76722. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76723. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  76724. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76725. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76726. _this.onApply = function (effect) {
  76727. effect.setTexture("colorTable", _this._colorTableTexture);
  76728. };
  76729. return _this;
  76730. }
  76731. return ColorCorrectionPostProcess;
  76732. }(BABYLON.PostProcess));
  76733. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  76734. })(BABYLON || (BABYLON = {}));
  76735. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  76736. var BABYLON;
  76737. (function (BABYLON) {
  76738. /** Defines operator used for tonemapping */
  76739. var TonemappingOperator;
  76740. (function (TonemappingOperator) {
  76741. /** Hable */
  76742. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  76743. /** Reinhard */
  76744. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  76745. /** HejiDawson */
  76746. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  76747. /** Photographic */
  76748. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  76749. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  76750. ;
  76751. /**
  76752. * Defines a post process to apply tone mapping
  76753. */
  76754. var TonemapPostProcess = /** @class */ (function (_super) {
  76755. __extends(TonemapPostProcess, _super);
  76756. /**
  76757. * Creates a new TonemapPostProcess
  76758. * @param name defines the name of the postprocess
  76759. * @param _operator defines the operator to use
  76760. * @param exposureAdjustment defines the required exposure adjustement
  76761. * @param camera defines the camera to use (can be null)
  76762. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  76763. * @param engine defines the hosting engine (can be ignore if camera is set)
  76764. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  76765. */
  76766. function TonemapPostProcess(name, _operator,
  76767. /** Defines the required exposure adjustement */
  76768. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  76769. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76770. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76771. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  76772. _this._operator = _operator;
  76773. _this.exposureAdjustment = exposureAdjustment;
  76774. var defines = "#define ";
  76775. if (_this._operator === TonemappingOperator.Hable)
  76776. defines += "HABLE_TONEMAPPING";
  76777. else if (_this._operator === TonemappingOperator.Reinhard)
  76778. defines += "REINHARD_TONEMAPPING";
  76779. else if (_this._operator === TonemappingOperator.HejiDawson)
  76780. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  76781. else if (_this._operator === TonemappingOperator.Photographic)
  76782. defines += "PHOTOGRAPHIC_TONEMAPPING";
  76783. //sadly a second call to create the effect.
  76784. _this.updateEffect(defines);
  76785. _this.onApply = function (effect) {
  76786. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  76787. };
  76788. return _this;
  76789. }
  76790. return TonemapPostProcess;
  76791. }(BABYLON.PostProcess));
  76792. BABYLON.TonemapPostProcess = TonemapPostProcess;
  76793. })(BABYLON || (BABYLON = {}));
  76794. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  76795. var BABYLON;
  76796. (function (BABYLON) {
  76797. var DisplayPassPostProcess = /** @class */ (function (_super) {
  76798. __extends(DisplayPassPostProcess, _super);
  76799. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  76800. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  76801. }
  76802. return DisplayPassPostProcess;
  76803. }(BABYLON.PostProcess));
  76804. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  76805. })(BABYLON || (BABYLON = {}));
  76806. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  76807. var BABYLON;
  76808. (function (BABYLON) {
  76809. var HighlightsPostProcess = /** @class */ (function (_super) {
  76810. __extends(HighlightsPostProcess, _super);
  76811. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76812. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76813. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76814. }
  76815. return HighlightsPostProcess;
  76816. }(BABYLON.PostProcess));
  76817. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  76818. })(BABYLON || (BABYLON = {}));
  76819. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  76820. var BABYLON;
  76821. (function (BABYLON) {
  76822. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  76823. __extends(ImageProcessingPostProcess, _super);
  76824. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  76825. if (camera === void 0) { camera = null; }
  76826. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76827. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  76828. _this._fromLinearSpace = true;
  76829. /**
  76830. * Defines cache preventing GC.
  76831. */
  76832. _this._defines = {
  76833. IMAGEPROCESSING: false,
  76834. VIGNETTE: false,
  76835. VIGNETTEBLENDMODEMULTIPLY: false,
  76836. VIGNETTEBLENDMODEOPAQUE: false,
  76837. TONEMAPPING: false,
  76838. CONTRAST: false,
  76839. COLORCURVES: false,
  76840. COLORGRADING: false,
  76841. COLORGRADING3D: false,
  76842. FROMLINEARSPACE: false,
  76843. SAMPLER3DGREENDEPTH: false,
  76844. SAMPLER3DBGRMAP: false,
  76845. IMAGEPROCESSINGPOSTPROCESS: false,
  76846. EXPOSURE: false,
  76847. };
  76848. // Setup the configuration as forced by the constructor. This would then not force the
  76849. // scene materials output in linear space and let untouched the default forward pass.
  76850. if (imageProcessingConfiguration) {
  76851. imageProcessingConfiguration.applyByPostProcess = true;
  76852. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  76853. // This will cause the shader to be compiled
  76854. _this.fromLinearSpace = false;
  76855. }
  76856. // Setup the default processing configuration to the scene.
  76857. else {
  76858. _this._attachImageProcessingConfiguration(null, true);
  76859. _this.imageProcessingConfiguration.applyByPostProcess = true;
  76860. }
  76861. _this.onApply = function (effect) {
  76862. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  76863. };
  76864. return _this;
  76865. }
  76866. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  76867. /**
  76868. * Gets the image processing configuration used either in this material.
  76869. */
  76870. get: function () {
  76871. return this._imageProcessingConfiguration;
  76872. },
  76873. /**
  76874. * Sets the Default image processing configuration used either in the this material.
  76875. *
  76876. * If sets to null, the scene one is in use.
  76877. */
  76878. set: function (value) {
  76879. this._attachImageProcessingConfiguration(value);
  76880. },
  76881. enumerable: true,
  76882. configurable: true
  76883. });
  76884. /**
  76885. * Attaches a new image processing configuration to the PBR Material.
  76886. * @param configuration
  76887. */
  76888. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  76889. var _this = this;
  76890. if (doNotBuild === void 0) { doNotBuild = false; }
  76891. if (configuration === this._imageProcessingConfiguration) {
  76892. return;
  76893. }
  76894. // Detaches observer.
  76895. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  76896. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  76897. }
  76898. // Pick the scene configuration if needed.
  76899. if (!configuration) {
  76900. var scene = null;
  76901. var engine = this.getEngine();
  76902. var camera = this.getCamera();
  76903. if (camera) {
  76904. scene = camera.getScene();
  76905. }
  76906. else if (engine && engine.scenes) {
  76907. var scenes = engine.scenes;
  76908. scene = scenes[scenes.length - 1];
  76909. }
  76910. else {
  76911. scene = BABYLON.Engine.LastCreatedScene;
  76912. }
  76913. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  76914. }
  76915. else {
  76916. this._imageProcessingConfiguration = configuration;
  76917. }
  76918. // Attaches observer.
  76919. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  76920. _this._updateParameters();
  76921. });
  76922. // Ensure the effect will be rebuilt.
  76923. if (!doNotBuild) {
  76924. this._updateParameters();
  76925. }
  76926. };
  76927. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  76928. /**
  76929. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76930. */
  76931. get: function () {
  76932. return this.imageProcessingConfiguration.colorCurves;
  76933. },
  76934. /**
  76935. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  76936. */
  76937. set: function (value) {
  76938. this.imageProcessingConfiguration.colorCurves = value;
  76939. },
  76940. enumerable: true,
  76941. configurable: true
  76942. });
  76943. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  76944. /**
  76945. * Gets wether the color curves effect is enabled.
  76946. */
  76947. get: function () {
  76948. return this.imageProcessingConfiguration.colorCurvesEnabled;
  76949. },
  76950. /**
  76951. * Sets wether the color curves effect is enabled.
  76952. */
  76953. set: function (value) {
  76954. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  76955. },
  76956. enumerable: true,
  76957. configurable: true
  76958. });
  76959. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  76960. /**
  76961. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76962. */
  76963. get: function () {
  76964. return this.imageProcessingConfiguration.colorGradingTexture;
  76965. },
  76966. /**
  76967. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  76968. */
  76969. set: function (value) {
  76970. this.imageProcessingConfiguration.colorGradingTexture = value;
  76971. },
  76972. enumerable: true,
  76973. configurable: true
  76974. });
  76975. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  76976. /**
  76977. * Gets wether the color grading effect is enabled.
  76978. */
  76979. get: function () {
  76980. return this.imageProcessingConfiguration.colorGradingEnabled;
  76981. },
  76982. /**
  76983. * Gets wether the color grading effect is enabled.
  76984. */
  76985. set: function (value) {
  76986. this.imageProcessingConfiguration.colorGradingEnabled = value;
  76987. },
  76988. enumerable: true,
  76989. configurable: true
  76990. });
  76991. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  76992. /**
  76993. * Gets exposure used in the effect.
  76994. */
  76995. get: function () {
  76996. return this.imageProcessingConfiguration.exposure;
  76997. },
  76998. /**
  76999. * Sets exposure used in the effect.
  77000. */
  77001. set: function (value) {
  77002. this.imageProcessingConfiguration.exposure = value;
  77003. },
  77004. enumerable: true,
  77005. configurable: true
  77006. });
  77007. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77008. /**
  77009. * Gets wether tonemapping is enabled or not.
  77010. */
  77011. get: function () {
  77012. return this._imageProcessingConfiguration.toneMappingEnabled;
  77013. },
  77014. /**
  77015. * Sets wether tonemapping is enabled or not
  77016. */
  77017. set: function (value) {
  77018. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77019. },
  77020. enumerable: true,
  77021. configurable: true
  77022. });
  77023. ;
  77024. ;
  77025. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77026. /**
  77027. * Gets contrast used in the effect.
  77028. */
  77029. get: function () {
  77030. return this.imageProcessingConfiguration.contrast;
  77031. },
  77032. /**
  77033. * Sets contrast used in the effect.
  77034. */
  77035. set: function (value) {
  77036. this.imageProcessingConfiguration.contrast = value;
  77037. },
  77038. enumerable: true,
  77039. configurable: true
  77040. });
  77041. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77042. /**
  77043. * Gets Vignette stretch size.
  77044. */
  77045. get: function () {
  77046. return this.imageProcessingConfiguration.vignetteStretch;
  77047. },
  77048. /**
  77049. * Sets Vignette stretch size.
  77050. */
  77051. set: function (value) {
  77052. this.imageProcessingConfiguration.vignetteStretch = value;
  77053. },
  77054. enumerable: true,
  77055. configurable: true
  77056. });
  77057. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77058. /**
  77059. * Gets Vignette centre X Offset.
  77060. */
  77061. get: function () {
  77062. return this.imageProcessingConfiguration.vignetteCentreX;
  77063. },
  77064. /**
  77065. * Sets Vignette centre X Offset.
  77066. */
  77067. set: function (value) {
  77068. this.imageProcessingConfiguration.vignetteCentreX = value;
  77069. },
  77070. enumerable: true,
  77071. configurable: true
  77072. });
  77073. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77074. /**
  77075. * Gets Vignette centre Y Offset.
  77076. */
  77077. get: function () {
  77078. return this.imageProcessingConfiguration.vignetteCentreY;
  77079. },
  77080. /**
  77081. * Sets Vignette centre Y Offset.
  77082. */
  77083. set: function (value) {
  77084. this.imageProcessingConfiguration.vignetteCentreY = value;
  77085. },
  77086. enumerable: true,
  77087. configurable: true
  77088. });
  77089. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77090. /**
  77091. * Gets Vignette weight or intensity of the vignette effect.
  77092. */
  77093. get: function () {
  77094. return this.imageProcessingConfiguration.vignetteWeight;
  77095. },
  77096. /**
  77097. * Sets Vignette weight or intensity of the vignette effect.
  77098. */
  77099. set: function (value) {
  77100. this.imageProcessingConfiguration.vignetteWeight = value;
  77101. },
  77102. enumerable: true,
  77103. configurable: true
  77104. });
  77105. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77106. /**
  77107. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77108. * if vignetteEnabled is set to true.
  77109. */
  77110. get: function () {
  77111. return this.imageProcessingConfiguration.vignetteColor;
  77112. },
  77113. /**
  77114. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77115. * if vignetteEnabled is set to true.
  77116. */
  77117. set: function (value) {
  77118. this.imageProcessingConfiguration.vignetteColor = value;
  77119. },
  77120. enumerable: true,
  77121. configurable: true
  77122. });
  77123. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77124. /**
  77125. * Gets Camera field of view used by the Vignette effect.
  77126. */
  77127. get: function () {
  77128. return this.imageProcessingConfiguration.vignetteCameraFov;
  77129. },
  77130. /**
  77131. * Sets Camera field of view used by the Vignette effect.
  77132. */
  77133. set: function (value) {
  77134. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77135. },
  77136. enumerable: true,
  77137. configurable: true
  77138. });
  77139. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77140. /**
  77141. * Gets the vignette blend mode allowing different kind of effect.
  77142. */
  77143. get: function () {
  77144. return this.imageProcessingConfiguration.vignetteBlendMode;
  77145. },
  77146. /**
  77147. * Sets the vignette blend mode allowing different kind of effect.
  77148. */
  77149. set: function (value) {
  77150. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77151. },
  77152. enumerable: true,
  77153. configurable: true
  77154. });
  77155. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77156. /**
  77157. * Gets wether the vignette effect is enabled.
  77158. */
  77159. get: function () {
  77160. return this.imageProcessingConfiguration.vignetteEnabled;
  77161. },
  77162. /**
  77163. * Sets wether the vignette effect is enabled.
  77164. */
  77165. set: function (value) {
  77166. this.imageProcessingConfiguration.vignetteEnabled = value;
  77167. },
  77168. enumerable: true,
  77169. configurable: true
  77170. });
  77171. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77172. /**
  77173. * Gets wether the input of the processing is in Gamma or Linear Space.
  77174. */
  77175. get: function () {
  77176. return this._fromLinearSpace;
  77177. },
  77178. /**
  77179. * Sets wether the input of the processing is in Gamma or Linear Space.
  77180. */
  77181. set: function (value) {
  77182. if (this._fromLinearSpace === value) {
  77183. return;
  77184. }
  77185. this._fromLinearSpace = value;
  77186. this._updateParameters();
  77187. },
  77188. enumerable: true,
  77189. configurable: true
  77190. });
  77191. ImageProcessingPostProcess.prototype.getClassName = function () {
  77192. return "ImageProcessingPostProcess";
  77193. };
  77194. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77195. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77196. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77197. var defines = "";
  77198. for (var define in this._defines) {
  77199. if (this._defines[define]) {
  77200. defines += "#define " + define + ";\r\n";
  77201. }
  77202. }
  77203. var samplers = ["textureSampler"];
  77204. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77205. var uniforms = ["scale"];
  77206. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77207. this.updateEffect(defines, uniforms, samplers);
  77208. };
  77209. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77210. _super.prototype.dispose.call(this, camera);
  77211. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77212. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77213. }
  77214. this.imageProcessingConfiguration.applyByPostProcess = false;
  77215. };
  77216. __decorate([
  77217. BABYLON.serialize()
  77218. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77219. return ImageProcessingPostProcess;
  77220. }(BABYLON.PostProcess));
  77221. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77222. })(BABYLON || (BABYLON = {}));
  77223. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77224. var BABYLON;
  77225. (function (BABYLON) {
  77226. /**
  77227. * Class used to store bone information
  77228. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77229. */
  77230. var Bone = /** @class */ (function (_super) {
  77231. __extends(Bone, _super);
  77232. /**
  77233. * Create a new bone
  77234. * @param name defines the bone name
  77235. * @param skeleton defines the parent skeleton
  77236. * @param parentBone defines the parent (can be null if the bone is the root)
  77237. * @param localMatrix defines the local matrix
  77238. * @param restPose defines the rest pose matrix
  77239. * @param baseMatrix defines the base matrix
  77240. * @param index defines index of the bone in the hiearchy
  77241. */
  77242. function Bone(
  77243. /**
  77244. * defines the bone name
  77245. */
  77246. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77247. if (parentBone === void 0) { parentBone = null; }
  77248. if (localMatrix === void 0) { localMatrix = null; }
  77249. if (restPose === void 0) { restPose = null; }
  77250. if (baseMatrix === void 0) { baseMatrix = null; }
  77251. if (index === void 0) { index = null; }
  77252. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77253. _this.name = name;
  77254. /**
  77255. * Gets the list of child bones
  77256. */
  77257. _this.children = new Array();
  77258. /** Gets the animations associated with this bone */
  77259. _this.animations = new Array();
  77260. /**
  77261. * @hidden Internal only
  77262. * Set this value to map this bone to a different index in the transform matrices
  77263. * Set this value to -1 to exclude the bone from the transform matrices
  77264. */
  77265. _this._index = null;
  77266. _this._absoluteTransform = new BABYLON.Matrix();
  77267. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77268. _this._scalingDeterminant = 1;
  77269. _this._worldTransform = new BABYLON.Matrix();
  77270. _this._needToDecompose = true;
  77271. _this._needToCompose = false;
  77272. _this._skeleton = skeleton;
  77273. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77274. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77275. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77276. _this._index = index;
  77277. skeleton.bones.push(_this);
  77278. _this.setParent(parentBone, false);
  77279. if (baseMatrix || localMatrix) {
  77280. _this._updateDifferenceMatrix();
  77281. }
  77282. return _this;
  77283. }
  77284. Object.defineProperty(Bone.prototype, "_matrix", {
  77285. /** @hidden */
  77286. get: function () {
  77287. this._compose();
  77288. return this._localMatrix;
  77289. },
  77290. /** @hidden */
  77291. set: function (value) {
  77292. this._localMatrix.copyFrom(value);
  77293. this._needToDecompose = true;
  77294. },
  77295. enumerable: true,
  77296. configurable: true
  77297. });
  77298. // Members
  77299. /**
  77300. * Gets the parent skeleton
  77301. * @returns a skeleton
  77302. */
  77303. Bone.prototype.getSkeleton = function () {
  77304. return this._skeleton;
  77305. };
  77306. /**
  77307. * Gets parent bone
  77308. * @returns a bone or null if the bone is the root of the bone hierarchy
  77309. */
  77310. Bone.prototype.getParent = function () {
  77311. return this._parent;
  77312. };
  77313. /**
  77314. * Sets the parent bone
  77315. * @param parent defines the parent (can be null if the bone is the root)
  77316. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77317. */
  77318. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  77319. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77320. if (this._parent === parent) {
  77321. return;
  77322. }
  77323. if (this._parent) {
  77324. var index = this._parent.children.indexOf(this);
  77325. if (index !== -1) {
  77326. this._parent.children.splice(index, 1);
  77327. }
  77328. }
  77329. this._parent = parent;
  77330. if (this._parent) {
  77331. this._parent.children.push(this);
  77332. }
  77333. if (updateDifferenceMatrix) {
  77334. this._updateDifferenceMatrix();
  77335. }
  77336. this.markAsDirty();
  77337. };
  77338. /**
  77339. * Gets the local matrix
  77340. * @returns a matrix
  77341. */
  77342. Bone.prototype.getLocalMatrix = function () {
  77343. this._compose();
  77344. return this._localMatrix;
  77345. };
  77346. /**
  77347. * Gets the base matrix (initial matrix which remains unchanged)
  77348. * @returns a matrix
  77349. */
  77350. Bone.prototype.getBaseMatrix = function () {
  77351. return this._baseMatrix;
  77352. };
  77353. /**
  77354. * Gets the rest pose matrix
  77355. * @returns a matrix
  77356. */
  77357. Bone.prototype.getRestPose = function () {
  77358. return this._restPose;
  77359. };
  77360. /**
  77361. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  77362. */
  77363. Bone.prototype.getWorldMatrix = function () {
  77364. return this._worldTransform;
  77365. };
  77366. /**
  77367. * Sets the local matrix to rest pose matrix
  77368. */
  77369. Bone.prototype.returnToRest = function () {
  77370. this.updateMatrix(this._restPose.clone());
  77371. };
  77372. /**
  77373. * Gets the inverse of the absolute transform matrix.
  77374. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  77375. * @returns a matrix
  77376. */
  77377. Bone.prototype.getInvertedAbsoluteTransform = function () {
  77378. return this._invertedAbsoluteTransform;
  77379. };
  77380. /**
  77381. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  77382. * @returns a matrix
  77383. */
  77384. Bone.prototype.getAbsoluteTransform = function () {
  77385. return this._absoluteTransform;
  77386. };
  77387. Object.defineProperty(Bone.prototype, "position", {
  77388. // Properties (matches AbstractMesh properties)
  77389. /** Gets or sets current position (in local space) */
  77390. get: function () {
  77391. this._decompose();
  77392. return this._localPosition;
  77393. },
  77394. set: function (newPosition) {
  77395. this._decompose();
  77396. this._localPosition.copyFrom(newPosition);
  77397. this._markAsDirtyAndCompose();
  77398. },
  77399. enumerable: true,
  77400. configurable: true
  77401. });
  77402. Object.defineProperty(Bone.prototype, "rotation", {
  77403. /** Gets or sets current rotation (in local space) */
  77404. get: function () {
  77405. return this.getRotation();
  77406. },
  77407. set: function (newRotation) {
  77408. this.setRotation(newRotation);
  77409. },
  77410. enumerable: true,
  77411. configurable: true
  77412. });
  77413. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  77414. /** Gets or sets current rotation quaternion (in local space) */
  77415. get: function () {
  77416. this._decompose();
  77417. return this._localRotation;
  77418. },
  77419. set: function (newRotation) {
  77420. this.setRotationQuaternion(newRotation);
  77421. },
  77422. enumerable: true,
  77423. configurable: true
  77424. });
  77425. Object.defineProperty(Bone.prototype, "scaling", {
  77426. /** Gets or sets current scaling (in local space) */
  77427. get: function () {
  77428. return this.getScale();
  77429. },
  77430. set: function (newScaling) {
  77431. this.setScale(newScaling);
  77432. },
  77433. enumerable: true,
  77434. configurable: true
  77435. });
  77436. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  77437. /**
  77438. * Gets the animation properties override
  77439. */
  77440. get: function () {
  77441. return this._skeleton.animationPropertiesOverride;
  77442. },
  77443. enumerable: true,
  77444. configurable: true
  77445. });
  77446. // Methods
  77447. Bone.prototype._decompose = function () {
  77448. if (!this._needToDecompose) {
  77449. return;
  77450. }
  77451. this._needToDecompose = false;
  77452. if (!this._localScaling) {
  77453. this._localScaling = BABYLON.Vector3.Zero();
  77454. this._localRotation = BABYLON.Quaternion.Zero();
  77455. this._localPosition = BABYLON.Vector3.Zero();
  77456. }
  77457. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  77458. };
  77459. Bone.prototype._compose = function () {
  77460. if (!this._needToCompose) {
  77461. return;
  77462. }
  77463. this._needToCompose = false;
  77464. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  77465. };
  77466. /**
  77467. * Update the base and local matrices
  77468. * @param matrix defines the new base or local matrix
  77469. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77470. * @param updateLocalMatrix defines if the local matrix should be updated
  77471. */
  77472. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  77473. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77474. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  77475. this._baseMatrix.copyFrom(matrix);
  77476. if (updateDifferenceMatrix) {
  77477. this._updateDifferenceMatrix();
  77478. }
  77479. if (updateLocalMatrix) {
  77480. this._localMatrix.copyFrom(matrix);
  77481. this._markAsDirtyAndDecompose();
  77482. }
  77483. else {
  77484. this.markAsDirty();
  77485. }
  77486. };
  77487. /** @hidden */
  77488. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  77489. if (updateChildren === void 0) { updateChildren = true; }
  77490. if (!rootMatrix) {
  77491. rootMatrix = this._baseMatrix;
  77492. }
  77493. if (this._parent) {
  77494. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77495. }
  77496. else {
  77497. this._absoluteTransform.copyFrom(rootMatrix);
  77498. }
  77499. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  77500. if (updateChildren) {
  77501. for (var index = 0; index < this.children.length; index++) {
  77502. this.children[index]._updateDifferenceMatrix();
  77503. }
  77504. }
  77505. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  77506. };
  77507. /**
  77508. * Flag the bone as dirty (Forcing it to update everything)
  77509. */
  77510. Bone.prototype.markAsDirty = function () {
  77511. this._currentRenderId++;
  77512. this._childRenderId++;
  77513. this._skeleton._markAsDirty();
  77514. };
  77515. Bone.prototype._markAsDirtyAndCompose = function () {
  77516. this.markAsDirty();
  77517. this._needToCompose = true;
  77518. };
  77519. Bone.prototype._markAsDirtyAndDecompose = function () {
  77520. this.markAsDirty();
  77521. this._needToDecompose = true;
  77522. };
  77523. /**
  77524. * Copy an animation range from another bone
  77525. * @param source defines the source bone
  77526. * @param rangeName defines the range name to copy
  77527. * @param frameOffset defines the frame offset
  77528. * @param rescaleAsRequired defines if rescaling must be applied if required
  77529. * @param skelDimensionsRatio defines the scaling ratio
  77530. * @returns true if operation was successful
  77531. */
  77532. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  77533. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77534. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  77535. // all animation may be coming from a library skeleton, so may need to create animation
  77536. if (this.animations.length === 0) {
  77537. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  77538. this.animations[0].setKeys([]);
  77539. }
  77540. // get animation info / verify there is such a range from the source bone
  77541. var sourceRange = source.animations[0].getRange(rangeName);
  77542. if (!sourceRange) {
  77543. return false;
  77544. }
  77545. var from = sourceRange.from;
  77546. var to = sourceRange.to;
  77547. var sourceKeys = source.animations[0].getKeys();
  77548. // rescaling prep
  77549. var sourceBoneLength = source.length;
  77550. var sourceParent = source.getParent();
  77551. var parent = this.getParent();
  77552. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  77553. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  77554. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  77555. var destKeys = this.animations[0].getKeys();
  77556. // loop vars declaration
  77557. var orig;
  77558. var origTranslation;
  77559. var mat;
  77560. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  77561. orig = sourceKeys[key];
  77562. if (orig.frame >= from && orig.frame <= to) {
  77563. if (rescaleAsRequired) {
  77564. mat = orig.value.clone();
  77565. // scale based on parent ratio, when bone has parent
  77566. if (parentScalingReqd) {
  77567. origTranslation = mat.getTranslation();
  77568. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  77569. // scale based on skeleton dimension ratio when root bone, and value is passed
  77570. }
  77571. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  77572. origTranslation = mat.getTranslation();
  77573. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  77574. // use original when root bone, and no data for skelDimensionsRatio
  77575. }
  77576. else {
  77577. mat = orig.value;
  77578. }
  77579. }
  77580. else {
  77581. mat = orig.value;
  77582. }
  77583. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  77584. }
  77585. }
  77586. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  77587. return true;
  77588. };
  77589. /**
  77590. * Translate the bone in local or world space
  77591. * @param vec The amount to translate the bone
  77592. * @param space The space that the translation is in
  77593. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77594. */
  77595. Bone.prototype.translate = function (vec, space, mesh) {
  77596. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77597. var lm = this.getLocalMatrix();
  77598. if (space == BABYLON.Space.LOCAL) {
  77599. lm.m[12] += vec.x;
  77600. lm.m[13] += vec.y;
  77601. lm.m[14] += vec.z;
  77602. }
  77603. else {
  77604. var wm = null;
  77605. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77606. if (mesh) {
  77607. wm = mesh.getWorldMatrix();
  77608. }
  77609. this._skeleton.computeAbsoluteTransforms();
  77610. var tmat = Bone._tmpMats[0];
  77611. var tvec = Bone._tmpVecs[0];
  77612. if (this._parent) {
  77613. if (mesh && wm) {
  77614. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77615. tmat.multiplyToRef(wm, tmat);
  77616. }
  77617. else {
  77618. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77619. }
  77620. }
  77621. tmat.m[12] = 0;
  77622. tmat.m[13] = 0;
  77623. tmat.m[14] = 0;
  77624. tmat.invert();
  77625. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  77626. lm.m[12] += tvec.x;
  77627. lm.m[13] += tvec.y;
  77628. lm.m[14] += tvec.z;
  77629. }
  77630. this._markAsDirtyAndDecompose();
  77631. };
  77632. /**
  77633. * Set the postion of the bone in local or world space
  77634. * @param position The position to set the bone
  77635. * @param space The space that the position is in
  77636. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77637. */
  77638. Bone.prototype.setPosition = function (position, space, mesh) {
  77639. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77640. var lm = this.getLocalMatrix();
  77641. if (space == BABYLON.Space.LOCAL) {
  77642. lm.m[12] = position.x;
  77643. lm.m[13] = position.y;
  77644. lm.m[14] = position.z;
  77645. }
  77646. else {
  77647. var wm = null;
  77648. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77649. if (mesh) {
  77650. wm = mesh.getWorldMatrix();
  77651. }
  77652. this._skeleton.computeAbsoluteTransforms();
  77653. var tmat = Bone._tmpMats[0];
  77654. var vec = Bone._tmpVecs[0];
  77655. if (this._parent) {
  77656. if (mesh && wm) {
  77657. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77658. tmat.multiplyToRef(wm, tmat);
  77659. }
  77660. else {
  77661. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77662. }
  77663. }
  77664. tmat.invert();
  77665. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  77666. lm.m[12] = vec.x;
  77667. lm.m[13] = vec.y;
  77668. lm.m[14] = vec.z;
  77669. }
  77670. this._markAsDirtyAndDecompose();
  77671. };
  77672. /**
  77673. * Set the absolute position of the bone (world space)
  77674. * @param position The position to set the bone
  77675. * @param mesh The mesh that this bone is attached to
  77676. */
  77677. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  77678. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  77679. };
  77680. /**
  77681. * Scale the bone on the x, y and z axes (in local space)
  77682. * @param x The amount to scale the bone on the x axis
  77683. * @param y The amount to scale the bone on the y axis
  77684. * @param z The amount to scale the bone on the z axis
  77685. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  77686. */
  77687. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  77688. if (scaleChildren === void 0) { scaleChildren = false; }
  77689. var locMat = this.getLocalMatrix();
  77690. // Apply new scaling on top of current local matrix
  77691. var scaleMat = Bone._tmpMats[0];
  77692. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  77693. scaleMat.multiplyToRef(locMat, locMat);
  77694. // Invert scaling matrix and apply the inverse to all children
  77695. scaleMat.invert();
  77696. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  77697. var child = _a[_i];
  77698. var cm = child.getLocalMatrix();
  77699. cm.multiplyToRef(scaleMat, cm);
  77700. cm.m[12] *= x;
  77701. cm.m[13] *= y;
  77702. cm.m[14] *= z;
  77703. child._markAsDirtyAndDecompose();
  77704. }
  77705. this._markAsDirtyAndDecompose();
  77706. if (scaleChildren) {
  77707. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  77708. var child = _c[_b];
  77709. child.scale(x, y, z, scaleChildren);
  77710. }
  77711. }
  77712. };
  77713. /**
  77714. * Set the bone scaling in local space
  77715. * @param scale defines the scaling vector
  77716. */
  77717. Bone.prototype.setScale = function (scale) {
  77718. this._decompose();
  77719. this._localScaling.copyFrom(scale);
  77720. this._markAsDirtyAndCompose();
  77721. };
  77722. /**
  77723. * Gets the current scaling in local space
  77724. * @returns the current scaling vector
  77725. */
  77726. Bone.prototype.getScale = function () {
  77727. this._decompose();
  77728. return this._localScaling;
  77729. };
  77730. /**
  77731. * Gets the current scaling in local space and stores it in a target vector
  77732. * @param result defines the target vector
  77733. */
  77734. Bone.prototype.getScaleToRef = function (result) {
  77735. this._decompose();
  77736. result.copyFrom(this._localScaling);
  77737. };
  77738. /**
  77739. * Set the yaw, pitch, and roll of the bone in local or world space
  77740. * @param yaw The rotation of the bone on the y axis
  77741. * @param pitch The rotation of the bone on the x axis
  77742. * @param roll The rotation of the bone on the z axis
  77743. * @param space The space that the axes of rotation are in
  77744. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77745. */
  77746. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  77747. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77748. if (space === BABYLON.Space.LOCAL) {
  77749. var quat = Bone._tmpQuat;
  77750. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  77751. this.setRotationQuaternion(quat, space, mesh);
  77752. return;
  77753. }
  77754. var rotMatInv = Bone._tmpMats[0];
  77755. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77756. return;
  77757. }
  77758. var rotMat = Bone._tmpMats[1];
  77759. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  77760. rotMatInv.multiplyToRef(rotMat, rotMat);
  77761. this._rotateWithMatrix(rotMat, space, mesh);
  77762. };
  77763. /**
  77764. * Add a rotation to the bone on an axis in local or world space
  77765. * @param axis The axis to rotate the bone on
  77766. * @param amount The amount to rotate the bone
  77767. * @param space The space that the axis is in
  77768. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77769. */
  77770. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  77771. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77772. var rmat = Bone._tmpMats[0];
  77773. rmat.m[12] = 0;
  77774. rmat.m[13] = 0;
  77775. rmat.m[14] = 0;
  77776. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  77777. this._rotateWithMatrix(rmat, space, mesh);
  77778. };
  77779. /**
  77780. * Set the rotation of the bone to a particular axis angle in local or world space
  77781. * @param axis The axis to rotate the bone on
  77782. * @param angle The angle that the bone should be rotated to
  77783. * @param space The space that the axis is in
  77784. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77785. */
  77786. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  77787. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77788. if (space === BABYLON.Space.LOCAL) {
  77789. var quat = Bone._tmpQuat;
  77790. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  77791. this.setRotationQuaternion(quat, space, mesh);
  77792. return;
  77793. }
  77794. var rotMatInv = Bone._tmpMats[0];
  77795. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77796. return;
  77797. }
  77798. var rotMat = Bone._tmpMats[1];
  77799. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  77800. rotMatInv.multiplyToRef(rotMat, rotMat);
  77801. this._rotateWithMatrix(rotMat, space, mesh);
  77802. };
  77803. /**
  77804. * Set the euler rotation of the bone in local of world space
  77805. * @param rotation The euler rotation that the bone should be set to
  77806. * @param space The space that the rotation is in
  77807. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77808. */
  77809. Bone.prototype.setRotation = function (rotation, space, mesh) {
  77810. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77811. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  77812. };
  77813. /**
  77814. * Set the quaternion rotation of the bone in local of world space
  77815. * @param quat The quaternion rotation that the bone should be set to
  77816. * @param space The space that the rotation is in
  77817. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77818. */
  77819. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  77820. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77821. if (space === BABYLON.Space.LOCAL) {
  77822. this._decompose();
  77823. this._localRotation.copyFrom(quat);
  77824. this._markAsDirtyAndCompose();
  77825. return;
  77826. }
  77827. var rotMatInv = Bone._tmpMats[0];
  77828. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77829. return;
  77830. }
  77831. var rotMat = Bone._tmpMats[1];
  77832. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  77833. rotMatInv.multiplyToRef(rotMat, rotMat);
  77834. this._rotateWithMatrix(rotMat, space, mesh);
  77835. };
  77836. /**
  77837. * Set the rotation matrix of the bone in local of world space
  77838. * @param rotMat The rotation matrix that the bone should be set to
  77839. * @param space The space that the rotation is in
  77840. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77841. */
  77842. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  77843. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77844. if (space === BABYLON.Space.LOCAL) {
  77845. var quat = Bone._tmpQuat;
  77846. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  77847. this.setRotationQuaternion(quat, space, mesh);
  77848. return;
  77849. }
  77850. var rotMatInv = Bone._tmpMats[0];
  77851. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77852. return;
  77853. }
  77854. var rotMat2 = Bone._tmpMats[1];
  77855. rotMat2.copyFrom(rotMat);
  77856. rotMatInv.multiplyToRef(rotMat, rotMat2);
  77857. this._rotateWithMatrix(rotMat2, space, mesh);
  77858. };
  77859. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  77860. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77861. var lmat = this.getLocalMatrix();
  77862. var lx = lmat.m[12];
  77863. var ly = lmat.m[13];
  77864. var lz = lmat.m[14];
  77865. var parent = this.getParent();
  77866. var parentScale = Bone._tmpMats[3];
  77867. var parentScaleInv = Bone._tmpMats[4];
  77868. if (parent && space == BABYLON.Space.WORLD) {
  77869. if (mesh) {
  77870. parentScale.copyFrom(mesh.getWorldMatrix());
  77871. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  77872. }
  77873. else {
  77874. parentScale.copyFrom(parent.getAbsoluteTransform());
  77875. }
  77876. parentScaleInv.copyFrom(parentScale);
  77877. parentScaleInv.invert();
  77878. lmat.multiplyToRef(parentScale, lmat);
  77879. lmat.multiplyToRef(rmat, lmat);
  77880. lmat.multiplyToRef(parentScaleInv, lmat);
  77881. }
  77882. else {
  77883. if (space == BABYLON.Space.WORLD && mesh) {
  77884. parentScale.copyFrom(mesh.getWorldMatrix());
  77885. parentScaleInv.copyFrom(parentScale);
  77886. parentScaleInv.invert();
  77887. lmat.multiplyToRef(parentScale, lmat);
  77888. lmat.multiplyToRef(rmat, lmat);
  77889. lmat.multiplyToRef(parentScaleInv, lmat);
  77890. }
  77891. else {
  77892. lmat.multiplyToRef(rmat, lmat);
  77893. }
  77894. }
  77895. lmat.m[12] = lx;
  77896. lmat.m[13] = ly;
  77897. lmat.m[14] = lz;
  77898. this.computeAbsoluteTransforms();
  77899. this._markAsDirtyAndDecompose();
  77900. };
  77901. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  77902. var scaleMatrix = Bone._tmpMats[2];
  77903. rotMatInv.copyFrom(this.getAbsoluteTransform());
  77904. if (mesh) {
  77905. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  77906. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  77907. }
  77908. rotMatInv.invert();
  77909. if (isNaN(rotMatInv.m[0])) {
  77910. // Matrix failed to invert.
  77911. // This can happen if scale is zero for example.
  77912. return false;
  77913. }
  77914. scaleMatrix.m[0] *= this._scalingDeterminant;
  77915. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  77916. return true;
  77917. };
  77918. /**
  77919. * Get the position of the bone in local or world space
  77920. * @param space The space that the returned position is in
  77921. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77922. * @returns The position of the bone
  77923. */
  77924. Bone.prototype.getPosition = function (space, mesh) {
  77925. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77926. if (mesh === void 0) { mesh = null; }
  77927. var pos = BABYLON.Vector3.Zero();
  77928. this.getPositionToRef(space, mesh, pos);
  77929. return pos;
  77930. };
  77931. /**
  77932. * Copy the position of the bone to a vector3 in local or world space
  77933. * @param space The space that the returned position is in
  77934. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77935. * @param result The vector3 to copy the position to
  77936. */
  77937. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  77938. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77939. if (space == BABYLON.Space.LOCAL) {
  77940. var lm = this.getLocalMatrix();
  77941. result.x = lm.m[12];
  77942. result.y = lm.m[13];
  77943. result.z = lm.m[14];
  77944. }
  77945. else {
  77946. var wm = null;
  77947. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77948. if (mesh) {
  77949. wm = mesh.getWorldMatrix();
  77950. }
  77951. this._skeleton.computeAbsoluteTransforms();
  77952. var tmat = Bone._tmpMats[0];
  77953. if (mesh && wm) {
  77954. tmat.copyFrom(this.getAbsoluteTransform());
  77955. tmat.multiplyToRef(wm, tmat);
  77956. }
  77957. else {
  77958. tmat = this.getAbsoluteTransform();
  77959. }
  77960. result.x = tmat.m[12];
  77961. result.y = tmat.m[13];
  77962. result.z = tmat.m[14];
  77963. }
  77964. };
  77965. /**
  77966. * Get the absolute position of the bone (world space)
  77967. * @param mesh The mesh that this bone is attached to
  77968. * @returns The absolute position of the bone
  77969. */
  77970. Bone.prototype.getAbsolutePosition = function (mesh) {
  77971. if (mesh === void 0) { mesh = null; }
  77972. var pos = BABYLON.Vector3.Zero();
  77973. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  77974. return pos;
  77975. };
  77976. /**
  77977. * Copy the absolute position of the bone (world space) to the result param
  77978. * @param mesh The mesh that this bone is attached to
  77979. * @param result The vector3 to copy the absolute position to
  77980. */
  77981. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  77982. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  77983. };
  77984. /**
  77985. * Compute the absolute transforms of this bone and its children
  77986. */
  77987. Bone.prototype.computeAbsoluteTransforms = function () {
  77988. this._compose();
  77989. if (this._parent) {
  77990. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77991. }
  77992. else {
  77993. this._absoluteTransform.copyFrom(this._localMatrix);
  77994. var poseMatrix = this._skeleton.getPoseMatrix();
  77995. if (poseMatrix) {
  77996. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  77997. }
  77998. }
  77999. var children = this.children;
  78000. var len = children.length;
  78001. for (var i = 0; i < len; i++) {
  78002. children[i].computeAbsoluteTransforms();
  78003. }
  78004. };
  78005. /**
  78006. * Get the world direction from an axis that is in the local space of the bone
  78007. * @param localAxis The local direction that is used to compute the world direction
  78008. * @param mesh The mesh that this bone is attached to
  78009. * @returns The world direction
  78010. */
  78011. Bone.prototype.getDirection = function (localAxis, mesh) {
  78012. if (mesh === void 0) { mesh = null; }
  78013. var result = BABYLON.Vector3.Zero();
  78014. this.getDirectionToRef(localAxis, mesh, result);
  78015. return result;
  78016. };
  78017. /**
  78018. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78019. * @param localAxis The local direction that is used to compute the world direction
  78020. * @param mesh The mesh that this bone is attached to
  78021. * @param result The vector3 that the world direction will be copied to
  78022. */
  78023. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78024. if (mesh === void 0) { mesh = null; }
  78025. var wm = null;
  78026. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78027. if (mesh) {
  78028. wm = mesh.getWorldMatrix();
  78029. }
  78030. this._skeleton.computeAbsoluteTransforms();
  78031. var mat = Bone._tmpMats[0];
  78032. mat.copyFrom(this.getAbsoluteTransform());
  78033. if (mesh && wm) {
  78034. mat.multiplyToRef(wm, mat);
  78035. }
  78036. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78037. result.normalize();
  78038. };
  78039. /**
  78040. * Get the euler rotation of the bone in local or world space
  78041. * @param space The space that the rotation should be in
  78042. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78043. * @returns The euler rotation
  78044. */
  78045. Bone.prototype.getRotation = function (space, mesh) {
  78046. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78047. if (mesh === void 0) { mesh = null; }
  78048. var result = BABYLON.Vector3.Zero();
  78049. this.getRotationToRef(space, mesh, result);
  78050. return result;
  78051. };
  78052. /**
  78053. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78054. * @param space The space that the rotation should be in
  78055. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78056. * @param result The vector3 that the rotation should be copied to
  78057. */
  78058. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78059. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78060. if (mesh === void 0) { mesh = null; }
  78061. var quat = Bone._tmpQuat;
  78062. this.getRotationQuaternionToRef(space, mesh, quat);
  78063. quat.toEulerAnglesToRef(result);
  78064. };
  78065. /**
  78066. * Get the quaternion rotation of the bone in either local or world space
  78067. * @param space The space that the rotation should be in
  78068. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78069. * @returns The quaternion rotation
  78070. */
  78071. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78072. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78073. if (mesh === void 0) { mesh = null; }
  78074. var result = BABYLON.Quaternion.Identity();
  78075. this.getRotationQuaternionToRef(space, mesh, result);
  78076. return result;
  78077. };
  78078. /**
  78079. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78080. * @param space The space that the rotation should be in
  78081. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78082. * @param result The quaternion that the rotation should be copied to
  78083. */
  78084. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78085. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78086. if (mesh === void 0) { mesh = null; }
  78087. if (space == BABYLON.Space.LOCAL) {
  78088. this._decompose();
  78089. result.copyFrom(this._localRotation);
  78090. }
  78091. else {
  78092. var mat = Bone._tmpMats[0];
  78093. var amat = this.getAbsoluteTransform();
  78094. if (mesh) {
  78095. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78096. }
  78097. else {
  78098. mat.copyFrom(amat);
  78099. }
  78100. mat.m[0] *= this._scalingDeterminant;
  78101. mat.m[1] *= this._scalingDeterminant;
  78102. mat.m[2] *= this._scalingDeterminant;
  78103. mat.decompose(undefined, result, undefined);
  78104. }
  78105. };
  78106. /**
  78107. * Get the rotation matrix of the bone in local or world space
  78108. * @param space The space that the rotation should be in
  78109. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78110. * @returns The rotation matrix
  78111. */
  78112. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78113. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78114. var result = BABYLON.Matrix.Identity();
  78115. this.getRotationMatrixToRef(space, mesh, result);
  78116. return result;
  78117. };
  78118. /**
  78119. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78120. * @param space The space that the rotation should be in
  78121. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78122. * @param result The quaternion that the rotation should be copied to
  78123. */
  78124. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78125. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78126. if (space == BABYLON.Space.LOCAL) {
  78127. this.getLocalMatrix().getRotationMatrixToRef(result);
  78128. }
  78129. else {
  78130. var mat = Bone._tmpMats[0];
  78131. var amat = this.getAbsoluteTransform();
  78132. if (mesh) {
  78133. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78134. }
  78135. else {
  78136. mat.copyFrom(amat);
  78137. }
  78138. mat.m[0] *= this._scalingDeterminant;
  78139. mat.m[1] *= this._scalingDeterminant;
  78140. mat.m[2] *= this._scalingDeterminant;
  78141. mat.getRotationMatrixToRef(result);
  78142. }
  78143. };
  78144. /**
  78145. * Get the world position of a point that is in the local space of the bone
  78146. * @param position The local position
  78147. * @param mesh The mesh that this bone is attached to
  78148. * @returns The world position
  78149. */
  78150. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78151. if (mesh === void 0) { mesh = null; }
  78152. var result = BABYLON.Vector3.Zero();
  78153. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78154. return result;
  78155. };
  78156. /**
  78157. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78158. * @param position The local position
  78159. * @param mesh The mesh that this bone is attached to
  78160. * @param result The vector3 that the world position should be copied to
  78161. */
  78162. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78163. if (mesh === void 0) { mesh = null; }
  78164. var wm = null;
  78165. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78166. if (mesh) {
  78167. wm = mesh.getWorldMatrix();
  78168. }
  78169. this._skeleton.computeAbsoluteTransforms();
  78170. var tmat = Bone._tmpMats[0];
  78171. if (mesh && wm) {
  78172. tmat.copyFrom(this.getAbsoluteTransform());
  78173. tmat.multiplyToRef(wm, tmat);
  78174. }
  78175. else {
  78176. tmat = this.getAbsoluteTransform();
  78177. }
  78178. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78179. };
  78180. /**
  78181. * Get the local position of a point that is in world space
  78182. * @param position The world position
  78183. * @param mesh The mesh that this bone is attached to
  78184. * @returns The local position
  78185. */
  78186. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78187. if (mesh === void 0) { mesh = null; }
  78188. var result = BABYLON.Vector3.Zero();
  78189. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78190. return result;
  78191. };
  78192. /**
  78193. * Get the local position of a point that is in world space and copy it to the result param
  78194. * @param position The world position
  78195. * @param mesh The mesh that this bone is attached to
  78196. * @param result The vector3 that the local position should be copied to
  78197. */
  78198. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78199. if (mesh === void 0) { mesh = null; }
  78200. var wm = null;
  78201. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78202. if (mesh) {
  78203. wm = mesh.getWorldMatrix();
  78204. }
  78205. this._skeleton.computeAbsoluteTransforms();
  78206. var tmat = Bone._tmpMats[0];
  78207. tmat.copyFrom(this.getAbsoluteTransform());
  78208. if (mesh && wm) {
  78209. tmat.multiplyToRef(wm, tmat);
  78210. }
  78211. tmat.invert();
  78212. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78213. };
  78214. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78215. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78216. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78217. return Bone;
  78218. }(BABYLON.Node));
  78219. BABYLON.Bone = Bone;
  78220. })(BABYLON || (BABYLON = {}));
  78221. //# sourceMappingURL=babylon.bone.js.map
  78222. var BABYLON;
  78223. (function (BABYLON) {
  78224. /**
  78225. * Class used to apply inverse kinematics to bones
  78226. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78227. */
  78228. var BoneIKController = /** @class */ (function () {
  78229. /**
  78230. * Creates a new BoneIKController
  78231. * @param mesh defines the mesh to control
  78232. * @param bone defines the bone to control
  78233. * @param options defines options to set up the controller
  78234. */
  78235. function BoneIKController(mesh, bone, options) {
  78236. /**
  78237. * Gets or sets the target position
  78238. */
  78239. this.targetPosition = BABYLON.Vector3.Zero();
  78240. /**
  78241. * Gets or sets the pole target position
  78242. */
  78243. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78244. /**
  78245. * Gets or sets the pole target local offset
  78246. */
  78247. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78248. /**
  78249. * Gets or sets the pole angle
  78250. */
  78251. this.poleAngle = 0;
  78252. /**
  78253. * 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)
  78254. */
  78255. this.slerpAmount = 1;
  78256. this._bone1Quat = BABYLON.Quaternion.Identity();
  78257. this._bone1Mat = BABYLON.Matrix.Identity();
  78258. this._bone2Ang = Math.PI;
  78259. this._maxAngle = Math.PI;
  78260. this._rightHandedSystem = false;
  78261. this._bendAxis = BABYLON.Vector3.Right();
  78262. this._slerping = false;
  78263. this._adjustRoll = 0;
  78264. this._bone2 = bone;
  78265. this._bone1 = bone.getParent();
  78266. if (!this._bone1) {
  78267. return;
  78268. }
  78269. this.mesh = mesh;
  78270. var bonePos = bone.getPosition();
  78271. if (bone.getAbsoluteTransform().determinant() > 0) {
  78272. this._rightHandedSystem = true;
  78273. this._bendAxis.x = 0;
  78274. this._bendAxis.y = 0;
  78275. this._bendAxis.z = -1;
  78276. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78277. this._adjustRoll = Math.PI * .5;
  78278. this._bendAxis.z = 1;
  78279. }
  78280. }
  78281. if (this._bone1.length) {
  78282. var boneScale1 = this._bone1.getScale();
  78283. var boneScale2 = this._bone2.getScale();
  78284. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  78285. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  78286. }
  78287. else if (this._bone1.children[0]) {
  78288. mesh.computeWorldMatrix(true);
  78289. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  78290. var pos2 = this._bone2.getAbsolutePosition(mesh);
  78291. var pos3 = this._bone1.getAbsolutePosition(mesh);
  78292. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  78293. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  78294. }
  78295. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  78296. this.maxAngle = Math.PI;
  78297. if (options) {
  78298. if (options.targetMesh) {
  78299. this.targetMesh = options.targetMesh;
  78300. this.targetMesh.computeWorldMatrix(true);
  78301. }
  78302. if (options.poleTargetMesh) {
  78303. this.poleTargetMesh = options.poleTargetMesh;
  78304. this.poleTargetMesh.computeWorldMatrix(true);
  78305. }
  78306. else if (options.poleTargetBone) {
  78307. this.poleTargetBone = options.poleTargetBone;
  78308. }
  78309. else if (this._bone1.getParent()) {
  78310. this.poleTargetBone = this._bone1.getParent();
  78311. }
  78312. if (options.poleTargetLocalOffset) {
  78313. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  78314. }
  78315. if (options.poleAngle) {
  78316. this.poleAngle = options.poleAngle;
  78317. }
  78318. if (options.bendAxis) {
  78319. this._bendAxis.copyFrom(options.bendAxis);
  78320. }
  78321. if (options.maxAngle) {
  78322. this.maxAngle = options.maxAngle;
  78323. }
  78324. if (options.slerpAmount) {
  78325. this.slerpAmount = options.slerpAmount;
  78326. }
  78327. }
  78328. }
  78329. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  78330. /**
  78331. * Gets or sets maximum allowed angle
  78332. */
  78333. get: function () {
  78334. return this._maxAngle;
  78335. },
  78336. set: function (value) {
  78337. this._setMaxAngle(value);
  78338. },
  78339. enumerable: true,
  78340. configurable: true
  78341. });
  78342. BoneIKController.prototype._setMaxAngle = function (ang) {
  78343. if (ang < 0) {
  78344. ang = 0;
  78345. }
  78346. if (ang > Math.PI || ang == undefined) {
  78347. ang = Math.PI;
  78348. }
  78349. this._maxAngle = ang;
  78350. var a = this._bone1Length;
  78351. var b = this._bone2Length;
  78352. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  78353. };
  78354. /**
  78355. * Force the controller to update the bones
  78356. */
  78357. BoneIKController.prototype.update = function () {
  78358. var bone1 = this._bone1;
  78359. if (!bone1) {
  78360. return;
  78361. }
  78362. var target = this.targetPosition;
  78363. var poleTarget = this.poleTargetPosition;
  78364. var mat1 = BoneIKController._tmpMats[0];
  78365. var mat2 = BoneIKController._tmpMats[1];
  78366. if (this.targetMesh) {
  78367. target.copyFrom(this.targetMesh.getAbsolutePosition());
  78368. }
  78369. if (this.poleTargetBone) {
  78370. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  78371. }
  78372. else if (this.poleTargetMesh) {
  78373. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  78374. }
  78375. var bonePos = BoneIKController._tmpVecs[0];
  78376. var zaxis = BoneIKController._tmpVecs[1];
  78377. var xaxis = BoneIKController._tmpVecs[2];
  78378. var yaxis = BoneIKController._tmpVecs[3];
  78379. var upAxis = BoneIKController._tmpVecs[4];
  78380. var _tmpQuat = BoneIKController._tmpQuat;
  78381. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  78382. poleTarget.subtractToRef(bonePos, upAxis);
  78383. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  78384. upAxis.y = 1;
  78385. }
  78386. else {
  78387. upAxis.normalize();
  78388. }
  78389. target.subtractToRef(bonePos, yaxis);
  78390. yaxis.normalize();
  78391. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  78392. zaxis.normalize();
  78393. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  78394. xaxis.normalize();
  78395. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  78396. var a = this._bone1Length;
  78397. var b = this._bone2Length;
  78398. var c = BABYLON.Vector3.Distance(bonePos, target);
  78399. if (this._maxReach > 0) {
  78400. c = Math.min(this._maxReach, c);
  78401. }
  78402. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  78403. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  78404. if (acosa > 1) {
  78405. acosa = 1;
  78406. }
  78407. if (acosb > 1) {
  78408. acosb = 1;
  78409. }
  78410. if (acosa < -1) {
  78411. acosa = -1;
  78412. }
  78413. if (acosb < -1) {
  78414. acosb = -1;
  78415. }
  78416. var angA = Math.acos(acosa);
  78417. var angB = Math.acos(acosb);
  78418. var angC = -angA - angB;
  78419. if (this._rightHandedSystem) {
  78420. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  78421. mat2.multiplyToRef(mat1, mat1);
  78422. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  78423. mat2.multiplyToRef(mat1, mat1);
  78424. }
  78425. else {
  78426. var _tmpVec = BoneIKController._tmpVecs[5];
  78427. _tmpVec.copyFrom(this._bendAxis);
  78428. _tmpVec.x *= -1;
  78429. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  78430. mat2.multiplyToRef(mat1, mat1);
  78431. }
  78432. if (this.poleAngle) {
  78433. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  78434. mat1.multiplyToRef(mat2, mat1);
  78435. }
  78436. if (this._bone1) {
  78437. if (this.slerpAmount < 1) {
  78438. if (!this._slerping) {
  78439. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  78440. }
  78441. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  78442. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  78443. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  78444. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  78445. this._slerping = true;
  78446. }
  78447. else {
  78448. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  78449. this._bone1Mat.copyFrom(mat1);
  78450. this._slerping = false;
  78451. }
  78452. }
  78453. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  78454. this._bone2Ang = angC;
  78455. };
  78456. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78457. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  78458. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78459. return BoneIKController;
  78460. }());
  78461. BABYLON.BoneIKController = BoneIKController;
  78462. })(BABYLON || (BABYLON = {}));
  78463. //# sourceMappingURL=babylon.boneIKController.js.map
  78464. var BABYLON;
  78465. (function (BABYLON) {
  78466. /**
  78467. * Class used to make a bone look toward a point in space
  78468. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  78469. */
  78470. var BoneLookController = /** @class */ (function () {
  78471. /**
  78472. * Create a BoneLookController
  78473. * @param mesh the mesh that the bone belongs to
  78474. * @param bone the bone that will be looking to the target
  78475. * @param target the target Vector3 to look at
  78476. * @param settings optional settings:
  78477. * * maxYaw: the maximum angle the bone will yaw to
  78478. * * minYaw: the minimum angle the bone will yaw to
  78479. * * maxPitch: the maximum angle the bone will pitch to
  78480. * * minPitch: the minimum angle the bone will yaw to
  78481. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  78482. * * upAxis: the up axis of the coordinate system
  78483. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  78484. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  78485. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  78486. * * adjustYaw: used to make an adjustment to the yaw of the bone
  78487. * * adjustPitch: used to make an adjustment to the pitch of the bone
  78488. * * adjustRoll: used to make an adjustment to the roll of the bone
  78489. **/
  78490. function BoneLookController(mesh, bone, target, options) {
  78491. /**
  78492. * The up axis of the coordinate system that is used when the bone is rotated
  78493. */
  78494. this.upAxis = BABYLON.Vector3.Up();
  78495. /**
  78496. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  78497. */
  78498. this.upAxisSpace = BABYLON.Space.LOCAL;
  78499. /**
  78500. * Used to make an adjustment to the yaw of the bone
  78501. */
  78502. this.adjustYaw = 0;
  78503. /**
  78504. * Used to make an adjustment to the pitch of the bone
  78505. */
  78506. this.adjustPitch = 0;
  78507. /**
  78508. * Used to make an adjustment to the roll of the bone
  78509. */
  78510. this.adjustRoll = 0;
  78511. /**
  78512. * 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)
  78513. */
  78514. this.slerpAmount = 1;
  78515. this._boneQuat = BABYLON.Quaternion.Identity();
  78516. this._slerping = false;
  78517. this._firstFrameSkipped = false;
  78518. this._fowardAxis = BABYLON.Vector3.Forward();
  78519. this.mesh = mesh;
  78520. this.bone = bone;
  78521. this.target = target;
  78522. if (options) {
  78523. if (options.adjustYaw) {
  78524. this.adjustYaw = options.adjustYaw;
  78525. }
  78526. if (options.adjustPitch) {
  78527. this.adjustPitch = options.adjustPitch;
  78528. }
  78529. if (options.adjustRoll) {
  78530. this.adjustRoll = options.adjustRoll;
  78531. }
  78532. if (options.maxYaw != null) {
  78533. this.maxYaw = options.maxYaw;
  78534. }
  78535. else {
  78536. this.maxYaw = Math.PI;
  78537. }
  78538. if (options.minYaw != null) {
  78539. this.minYaw = options.minYaw;
  78540. }
  78541. else {
  78542. this.minYaw = -Math.PI;
  78543. }
  78544. if (options.maxPitch != null) {
  78545. this.maxPitch = options.maxPitch;
  78546. }
  78547. else {
  78548. this.maxPitch = Math.PI;
  78549. }
  78550. if (options.minPitch != null) {
  78551. this.minPitch = options.minPitch;
  78552. }
  78553. else {
  78554. this.minPitch = -Math.PI;
  78555. }
  78556. if (options.slerpAmount != null) {
  78557. this.slerpAmount = options.slerpAmount;
  78558. }
  78559. if (options.upAxis != null) {
  78560. this.upAxis = options.upAxis;
  78561. }
  78562. if (options.upAxisSpace != null) {
  78563. this.upAxisSpace = options.upAxisSpace;
  78564. }
  78565. if (options.yawAxis != null || options.pitchAxis != null) {
  78566. var newYawAxis = BABYLON.Axis.Y;
  78567. var newPitchAxis = BABYLON.Axis.X;
  78568. if (options.yawAxis != null) {
  78569. newYawAxis = options.yawAxis.clone();
  78570. newYawAxis.normalize();
  78571. }
  78572. if (options.pitchAxis != null) {
  78573. newPitchAxis = options.pitchAxis.clone();
  78574. newPitchAxis.normalize();
  78575. }
  78576. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  78577. this._transformYawPitch = BABYLON.Matrix.Identity();
  78578. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  78579. this._transformYawPitchInv = this._transformYawPitch.clone();
  78580. this._transformYawPitch.invert();
  78581. }
  78582. }
  78583. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  78584. this.upAxisSpace = BABYLON.Space.LOCAL;
  78585. }
  78586. }
  78587. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  78588. /**
  78589. * Gets or sets the minimum yaw angle that the bone can look to
  78590. */
  78591. get: function () {
  78592. return this._minYaw;
  78593. },
  78594. set: function (value) {
  78595. this._minYaw = value;
  78596. this._minYawSin = Math.sin(value);
  78597. this._minYawCos = Math.cos(value);
  78598. if (this._maxYaw != null) {
  78599. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78600. this._yawRange = this._maxYaw - this._minYaw;
  78601. }
  78602. },
  78603. enumerable: true,
  78604. configurable: true
  78605. });
  78606. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  78607. /**
  78608. * Gets or sets the maximum yaw angle that the bone can look to
  78609. */
  78610. get: function () {
  78611. return this._maxYaw;
  78612. },
  78613. set: function (value) {
  78614. this._maxYaw = value;
  78615. this._maxYawSin = Math.sin(value);
  78616. this._maxYawCos = Math.cos(value);
  78617. if (this._minYaw != null) {
  78618. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78619. this._yawRange = this._maxYaw - this._minYaw;
  78620. }
  78621. },
  78622. enumerable: true,
  78623. configurable: true
  78624. });
  78625. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  78626. /**
  78627. * Gets or sets the minimum pitch angle that the bone can look to
  78628. */
  78629. get: function () {
  78630. return this._minPitch;
  78631. },
  78632. set: function (value) {
  78633. this._minPitch = value;
  78634. this._minPitchTan = Math.tan(value);
  78635. },
  78636. enumerable: true,
  78637. configurable: true
  78638. });
  78639. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  78640. /**
  78641. * Gets or sets the maximum pitch angle that the bone can look to
  78642. */
  78643. get: function () {
  78644. return this._maxPitch;
  78645. },
  78646. set: function (value) {
  78647. this._maxPitch = value;
  78648. this._maxPitchTan = Math.tan(value);
  78649. },
  78650. enumerable: true,
  78651. configurable: true
  78652. });
  78653. /**
  78654. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  78655. */
  78656. BoneLookController.prototype.update = function () {
  78657. //skip the first frame when slerping so that the mesh rotation is correct
  78658. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  78659. this._firstFrameSkipped = true;
  78660. return;
  78661. }
  78662. var bone = this.bone;
  78663. var bonePos = BoneLookController._tmpVecs[0];
  78664. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  78665. var target = this.target;
  78666. var _tmpMat1 = BoneLookController._tmpMats[0];
  78667. var _tmpMat2 = BoneLookController._tmpMats[1];
  78668. var mesh = this.mesh;
  78669. var parentBone = bone.getParent();
  78670. var upAxis = BoneLookController._tmpVecs[1];
  78671. upAxis.copyFrom(this.upAxis);
  78672. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  78673. if (this._transformYawPitch) {
  78674. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  78675. }
  78676. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  78677. }
  78678. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  78679. mesh.getDirectionToRef(upAxis, upAxis);
  78680. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  78681. upAxis.normalize();
  78682. }
  78683. }
  78684. var checkYaw = false;
  78685. var checkPitch = false;
  78686. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  78687. checkYaw = true;
  78688. }
  78689. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  78690. checkPitch = true;
  78691. }
  78692. if (checkYaw || checkPitch) {
  78693. var spaceMat = BoneLookController._tmpMats[2];
  78694. var spaceMatInv = BoneLookController._tmpMats[3];
  78695. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  78696. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  78697. }
  78698. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  78699. spaceMat.copyFrom(mesh.getWorldMatrix());
  78700. }
  78701. else {
  78702. var forwardAxis = BoneLookController._tmpVecs[2];
  78703. forwardAxis.copyFrom(this._fowardAxis);
  78704. if (this._transformYawPitch) {
  78705. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  78706. }
  78707. if (parentBone) {
  78708. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  78709. }
  78710. else {
  78711. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  78712. }
  78713. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  78714. rightAxis.normalize();
  78715. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  78716. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  78717. }
  78718. spaceMat.invertToRef(spaceMatInv);
  78719. var xzlen = null;
  78720. if (checkPitch) {
  78721. var localTarget = BoneLookController._tmpVecs[3];
  78722. target.subtractToRef(bonePos, localTarget);
  78723. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78724. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78725. var pitch = Math.atan2(localTarget.y, xzlen);
  78726. var newPitch = pitch;
  78727. if (pitch > this._maxPitch) {
  78728. localTarget.y = this._maxPitchTan * xzlen;
  78729. newPitch = this._maxPitch;
  78730. }
  78731. else if (pitch < this._minPitch) {
  78732. localTarget.y = this._minPitchTan * xzlen;
  78733. newPitch = this._minPitch;
  78734. }
  78735. if (pitch != newPitch) {
  78736. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78737. localTarget.addInPlace(bonePos);
  78738. target = localTarget;
  78739. }
  78740. }
  78741. if (checkYaw) {
  78742. var localTarget = BoneLookController._tmpVecs[4];
  78743. target.subtractToRef(bonePos, localTarget);
  78744. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78745. var yaw = Math.atan2(localTarget.x, localTarget.z);
  78746. var newYaw = yaw;
  78747. if (yaw > this._maxYaw || yaw < this._minYaw) {
  78748. if (xzlen == null) {
  78749. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78750. }
  78751. if (this._yawRange > Math.PI) {
  78752. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  78753. localTarget.z = this._maxYawCos * xzlen;
  78754. localTarget.x = this._maxYawSin * xzlen;
  78755. newYaw = this._maxYaw;
  78756. }
  78757. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  78758. localTarget.z = this._minYawCos * xzlen;
  78759. localTarget.x = this._minYawSin * xzlen;
  78760. newYaw = this._minYaw;
  78761. }
  78762. }
  78763. else {
  78764. if (yaw > this._maxYaw) {
  78765. localTarget.z = this._maxYawCos * xzlen;
  78766. localTarget.x = this._maxYawSin * xzlen;
  78767. newYaw = this._maxYaw;
  78768. }
  78769. else if (yaw < this._minYaw) {
  78770. localTarget.z = this._minYawCos * xzlen;
  78771. localTarget.x = this._minYawSin * xzlen;
  78772. newYaw = this._minYaw;
  78773. }
  78774. }
  78775. }
  78776. if (this._slerping && this._yawRange > Math.PI) {
  78777. //are we going to be crossing into the min/max region?
  78778. var boneFwd = BoneLookController._tmpVecs[8];
  78779. boneFwd.copyFrom(BABYLON.Axis.Z);
  78780. if (this._transformYawPitch) {
  78781. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  78782. }
  78783. var boneRotMat = BoneLookController._tmpMats[4];
  78784. this._boneQuat.toRotationMatrix(boneRotMat);
  78785. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  78786. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  78787. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  78788. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  78789. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  78790. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  78791. if (angBtwTar > angBtwMidYaw) {
  78792. if (xzlen == null) {
  78793. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78794. }
  78795. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  78796. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  78797. if (angBtwMin < angBtwMax) {
  78798. newYaw = boneYaw + Math.PI * .75;
  78799. localTarget.z = Math.cos(newYaw) * xzlen;
  78800. localTarget.x = Math.sin(newYaw) * xzlen;
  78801. }
  78802. else {
  78803. newYaw = boneYaw - Math.PI * .75;
  78804. localTarget.z = Math.cos(newYaw) * xzlen;
  78805. localTarget.x = Math.sin(newYaw) * xzlen;
  78806. }
  78807. }
  78808. }
  78809. if (yaw != newYaw) {
  78810. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78811. localTarget.addInPlace(bonePos);
  78812. target = localTarget;
  78813. }
  78814. }
  78815. }
  78816. var zaxis = BoneLookController._tmpVecs[5];
  78817. var xaxis = BoneLookController._tmpVecs[6];
  78818. var yaxis = BoneLookController._tmpVecs[7];
  78819. var _tmpQuat = BoneLookController._tmpQuat;
  78820. target.subtractToRef(bonePos, zaxis);
  78821. zaxis.normalize();
  78822. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  78823. xaxis.normalize();
  78824. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  78825. yaxis.normalize();
  78826. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  78827. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  78828. return;
  78829. }
  78830. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  78831. return;
  78832. }
  78833. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  78834. return;
  78835. }
  78836. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  78837. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  78838. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  78839. }
  78840. if (this.slerpAmount < 1) {
  78841. if (!this._slerping) {
  78842. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  78843. }
  78844. if (this._transformYawPitch) {
  78845. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78846. }
  78847. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  78848. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  78849. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  78850. this._slerping = true;
  78851. }
  78852. else {
  78853. if (this._transformYawPitch) {
  78854. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  78855. }
  78856. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  78857. this._slerping = false;
  78858. }
  78859. };
  78860. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  78861. var angDiff = ang2 - ang1;
  78862. angDiff %= Math.PI * 2;
  78863. if (angDiff > Math.PI) {
  78864. angDiff -= Math.PI * 2;
  78865. }
  78866. else if (angDiff < -Math.PI) {
  78867. angDiff += Math.PI * 2;
  78868. }
  78869. return angDiff;
  78870. };
  78871. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  78872. ang1 %= (2 * Math.PI);
  78873. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78874. ang2 %= (2 * Math.PI);
  78875. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78876. var ab = 0;
  78877. if (ang1 < ang2) {
  78878. ab = ang2 - ang1;
  78879. }
  78880. else {
  78881. ab = ang1 - ang2;
  78882. }
  78883. if (ab > Math.PI) {
  78884. ab = Math.PI * 2 - ab;
  78885. }
  78886. return ab;
  78887. };
  78888. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  78889. ang %= (2 * Math.PI);
  78890. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  78891. ang1 %= (2 * Math.PI);
  78892. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  78893. ang2 %= (2 * Math.PI);
  78894. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  78895. if (ang1 < ang2) {
  78896. if (ang > ang1 && ang < ang2) {
  78897. return true;
  78898. }
  78899. }
  78900. else {
  78901. if (ang > ang2 && ang < ang1) {
  78902. return true;
  78903. }
  78904. }
  78905. return false;
  78906. };
  78907. 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()];
  78908. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  78909. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78910. return BoneLookController;
  78911. }());
  78912. BABYLON.BoneLookController = BoneLookController;
  78913. })(BABYLON || (BABYLON = {}));
  78914. //# sourceMappingURL=babylon.boneLookController.js.map
  78915. var BABYLON;
  78916. (function (BABYLON) {
  78917. /**
  78918. * Class used to handle skinning animations
  78919. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  78920. */
  78921. var Skeleton = /** @class */ (function () {
  78922. /**
  78923. * Creates a new skeleton
  78924. * @param name defines the skeleton name
  78925. * @param id defines the skeleton Id
  78926. * @param scene defines the hosting scene
  78927. */
  78928. function Skeleton(
  78929. /** defines the skeleton name */
  78930. name,
  78931. /** defines the skeleton Id */
  78932. id, scene) {
  78933. this.name = name;
  78934. this.id = id;
  78935. /**
  78936. * Gets the list of child bones
  78937. */
  78938. this.bones = new Array();
  78939. /**
  78940. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  78941. */
  78942. this.needInitialSkinMatrix = false;
  78943. this._isDirty = true;
  78944. this._meshesWithPoseMatrix = new Array();
  78945. this._identity = BABYLON.Matrix.Identity();
  78946. this._ranges = {};
  78947. this._lastAbsoluteTransformsUpdateId = -1;
  78948. /**
  78949. * Specifies if the skeleton should be serialized
  78950. */
  78951. this.doNotSerialize = false;
  78952. this._animationPropertiesOverride = null;
  78953. // Events
  78954. /**
  78955. * An observable triggered before computing the skeleton's matrices
  78956. */
  78957. this.onBeforeComputeObservable = new BABYLON.Observable();
  78958. this.bones = [];
  78959. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  78960. scene.skeletons.push(this);
  78961. //make sure it will recalculate the matrix next time prepare is called.
  78962. this._isDirty = true;
  78963. }
  78964. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  78965. /**
  78966. * Gets or sets the animation properties override
  78967. */
  78968. get: function () {
  78969. if (!this._animationPropertiesOverride) {
  78970. return this._scene.animationPropertiesOverride;
  78971. }
  78972. return this._animationPropertiesOverride;
  78973. },
  78974. set: function (value) {
  78975. this._animationPropertiesOverride = value;
  78976. },
  78977. enumerable: true,
  78978. configurable: true
  78979. });
  78980. // Members
  78981. /**
  78982. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  78983. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  78984. * @returns a Float32Array containing matrices data
  78985. */
  78986. Skeleton.prototype.getTransformMatrices = function (mesh) {
  78987. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  78988. return mesh._bonesTransformMatrices;
  78989. }
  78990. if (!this._transformMatrices) {
  78991. this.prepare();
  78992. }
  78993. return this._transformMatrices;
  78994. };
  78995. /**
  78996. * Gets the current hosting scene
  78997. * @returns a scene object
  78998. */
  78999. Skeleton.prototype.getScene = function () {
  79000. return this._scene;
  79001. };
  79002. // Methods
  79003. /**
  79004. * Gets a string representing the current skeleton data
  79005. * @param fullDetails defines a boolean indicating if we want a verbose version
  79006. * @returns a string representing the current skeleton data
  79007. */
  79008. Skeleton.prototype.toString = function (fullDetails) {
  79009. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79010. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79011. if (fullDetails) {
  79012. ret += ", Ranges: {";
  79013. var first = true;
  79014. for (var name_1 in this._ranges) {
  79015. if (first) {
  79016. ret += ", ";
  79017. first = false;
  79018. }
  79019. ret += name_1;
  79020. }
  79021. ret += "}";
  79022. }
  79023. return ret;
  79024. };
  79025. /**
  79026. * Get bone's index searching by name
  79027. * @param name defines bone's name to search for
  79028. * @return the indice of the bone. Returns -1 if not found
  79029. */
  79030. Skeleton.prototype.getBoneIndexByName = function (name) {
  79031. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79032. if (this.bones[boneIndex].name === name) {
  79033. return boneIndex;
  79034. }
  79035. }
  79036. return -1;
  79037. };
  79038. /**
  79039. * Creater a new animation range
  79040. * @param name defines the name of the range
  79041. * @param from defines the start key
  79042. * @param to defines the end key
  79043. */
  79044. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79045. // check name not already in use
  79046. if (!this._ranges[name]) {
  79047. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79048. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79049. if (this.bones[i].animations[0]) {
  79050. this.bones[i].animations[0].createRange(name, from, to);
  79051. }
  79052. }
  79053. }
  79054. };
  79055. /**
  79056. * Delete a specific animation range
  79057. * @param name defines the name of the range
  79058. * @param deleteFrames defines if frames must be removed as well
  79059. */
  79060. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79061. if (deleteFrames === void 0) { deleteFrames = true; }
  79062. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79063. if (this.bones[i].animations[0]) {
  79064. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79065. }
  79066. }
  79067. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79068. };
  79069. /**
  79070. * Gets a specific animation range
  79071. * @param name defines the name of the range to look for
  79072. * @returns the requested animation range or null if not found
  79073. */
  79074. Skeleton.prototype.getAnimationRange = function (name) {
  79075. return this._ranges[name];
  79076. };
  79077. /**
  79078. * Gets the list of all animation ranges defined on this skeleton
  79079. * @returns an array
  79080. */
  79081. Skeleton.prototype.getAnimationRanges = function () {
  79082. var animationRanges = [];
  79083. var name;
  79084. var i = 0;
  79085. for (name in this._ranges) {
  79086. animationRanges[i] = this._ranges[name];
  79087. i++;
  79088. }
  79089. return animationRanges;
  79090. };
  79091. /**
  79092. * Copy animation range from a source skeleton.
  79093. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79094. * @param source defines the source skeleton
  79095. * @param name defines the name of the range to copy
  79096. * @param rescaleAsRequired defines if rescaling must be applied if required
  79097. * @returns true if operation was successful
  79098. */
  79099. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79100. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79101. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79102. return false;
  79103. }
  79104. var ret = true;
  79105. var frameOffset = this._getHighestAnimationFrame() + 1;
  79106. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79107. var boneDict = {};
  79108. var sourceBones = source.bones;
  79109. var nBones;
  79110. var i;
  79111. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79112. boneDict[sourceBones[i].name] = sourceBones[i];
  79113. }
  79114. if (this.bones.length !== sourceBones.length) {
  79115. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79116. ret = false;
  79117. }
  79118. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79119. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79120. var boneName = this.bones[i].name;
  79121. var sourceBone = boneDict[boneName];
  79122. if (sourceBone) {
  79123. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79124. }
  79125. else {
  79126. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79127. ret = false;
  79128. }
  79129. }
  79130. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79131. var range = source.getAnimationRange(name);
  79132. if (range) {
  79133. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79134. }
  79135. return ret;
  79136. };
  79137. /**
  79138. * Forces the skeleton to go to rest pose
  79139. */
  79140. Skeleton.prototype.returnToRest = function () {
  79141. for (var index = 0; index < this.bones.length; index++) {
  79142. this.bones[index].returnToRest();
  79143. }
  79144. };
  79145. Skeleton.prototype._getHighestAnimationFrame = function () {
  79146. var ret = 0;
  79147. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79148. if (this.bones[i].animations[0]) {
  79149. var highest = this.bones[i].animations[0].getHighestFrame();
  79150. if (ret < highest) {
  79151. ret = highest;
  79152. }
  79153. }
  79154. }
  79155. return ret;
  79156. };
  79157. /**
  79158. * Begin a specific animation range
  79159. * @param name defines the name of the range to start
  79160. * @param loop defines if looping must be turned on (false by default)
  79161. * @param speedRatio defines the speed ratio to apply (1 by default)
  79162. * @param onAnimationEnd defines a callback which will be called when animation will end
  79163. * @returns a new animatable
  79164. */
  79165. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79166. var range = this.getAnimationRange(name);
  79167. if (!range) {
  79168. return null;
  79169. }
  79170. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79171. };
  79172. /** @hidden */
  79173. Skeleton.prototype._markAsDirty = function () {
  79174. this._isDirty = true;
  79175. };
  79176. /** @hidden */
  79177. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79178. this._meshesWithPoseMatrix.push(mesh);
  79179. };
  79180. /** @hidden */
  79181. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79182. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79183. if (index > -1) {
  79184. this._meshesWithPoseMatrix.splice(index, 1);
  79185. }
  79186. };
  79187. /** @hidden */
  79188. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79189. this.onBeforeComputeObservable.notifyObservers(this);
  79190. for (var index = 0; index < this.bones.length; index++) {
  79191. var bone = this.bones[index];
  79192. var parentBone = bone.getParent();
  79193. if (parentBone) {
  79194. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79195. }
  79196. else {
  79197. if (initialSkinMatrix) {
  79198. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79199. }
  79200. else {
  79201. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79202. }
  79203. }
  79204. if (bone._index !== -1) {
  79205. var mappedIndex = bone._index === null ? index : bone._index;
  79206. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79207. }
  79208. }
  79209. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79210. };
  79211. /**
  79212. * Build all resources required to render a skeleton
  79213. */
  79214. Skeleton.prototype.prepare = function () {
  79215. if (!this._isDirty) {
  79216. return;
  79217. }
  79218. if (this.needInitialSkinMatrix) {
  79219. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79220. var mesh = this._meshesWithPoseMatrix[index];
  79221. var poseMatrix = mesh.getPoseMatrix();
  79222. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79223. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79224. }
  79225. if (this._synchronizedWithMesh !== mesh) {
  79226. this._synchronizedWithMesh = mesh;
  79227. // Prepare bones
  79228. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79229. var bone = this.bones[boneIndex];
  79230. if (!bone.getParent()) {
  79231. var matrix = bone.getBaseMatrix();
  79232. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79233. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79234. }
  79235. }
  79236. }
  79237. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79238. }
  79239. }
  79240. else {
  79241. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79242. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79243. }
  79244. this._computeTransformMatrices(this._transformMatrices, null);
  79245. }
  79246. this._isDirty = false;
  79247. this._scene._activeBones.addCount(this.bones.length, false);
  79248. };
  79249. /**
  79250. * Gets the list of animatables currently running for this skeleton
  79251. * @returns an array of animatables
  79252. */
  79253. Skeleton.prototype.getAnimatables = function () {
  79254. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79255. this._animatables = [];
  79256. for (var index = 0; index < this.bones.length; index++) {
  79257. this._animatables.push(this.bones[index]);
  79258. }
  79259. }
  79260. return this._animatables;
  79261. };
  79262. /**
  79263. * Clone the current skeleton
  79264. * @param name defines the name of the new skeleton
  79265. * @param id defines the id of the enw skeleton
  79266. * @returns the new skeleton
  79267. */
  79268. Skeleton.prototype.clone = function (name, id) {
  79269. var result = new Skeleton(name, id || name, this._scene);
  79270. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79271. for (var index = 0; index < this.bones.length; index++) {
  79272. var source = this.bones[index];
  79273. var parentBone = null;
  79274. var parent_1 = source.getParent();
  79275. if (parent_1) {
  79276. var parentIndex = this.bones.indexOf(parent_1);
  79277. parentBone = result.bones[parentIndex];
  79278. }
  79279. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  79280. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  79281. }
  79282. if (this._ranges) {
  79283. result._ranges = {};
  79284. for (var rangeName in this._ranges) {
  79285. var range = this._ranges[rangeName];
  79286. if (range) {
  79287. result._ranges[rangeName] = range.clone();
  79288. }
  79289. }
  79290. }
  79291. this._isDirty = true;
  79292. return result;
  79293. };
  79294. /**
  79295. * Enable animation blending for this skeleton
  79296. * @param blendingSpeed defines the blending speed to apply
  79297. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  79298. */
  79299. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  79300. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  79301. this.bones.forEach(function (bone) {
  79302. bone.animations.forEach(function (animation) {
  79303. animation.enableBlending = true;
  79304. animation.blendingSpeed = blendingSpeed;
  79305. });
  79306. });
  79307. };
  79308. /**
  79309. * Releases all resources associated with the current skeleton
  79310. */
  79311. Skeleton.prototype.dispose = function () {
  79312. this._meshesWithPoseMatrix = [];
  79313. // Animations
  79314. this.getScene().stopAnimation(this);
  79315. // Remove from scene
  79316. this.getScene().removeSkeleton(this);
  79317. };
  79318. /**
  79319. * Serialize the skeleton in a JSON object
  79320. * @returns a JSON object
  79321. */
  79322. Skeleton.prototype.serialize = function () {
  79323. var serializationObject = {};
  79324. serializationObject.name = this.name;
  79325. serializationObject.id = this.id;
  79326. if (this.dimensionsAtRest) {
  79327. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  79328. }
  79329. serializationObject.bones = [];
  79330. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79331. for (var index = 0; index < this.bones.length; index++) {
  79332. var bone = this.bones[index];
  79333. var parent_2 = bone.getParent();
  79334. var serializedBone = {
  79335. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  79336. name: bone.name,
  79337. matrix: bone.getBaseMatrix().toArray(),
  79338. rest: bone.getRestPose().toArray()
  79339. };
  79340. serializationObject.bones.push(serializedBone);
  79341. if (bone.length) {
  79342. serializedBone.length = bone.length;
  79343. }
  79344. if (bone.animations && bone.animations.length > 0) {
  79345. serializedBone.animation = bone.animations[0].serialize();
  79346. }
  79347. serializationObject.ranges = [];
  79348. for (var name in this._ranges) {
  79349. var source = this._ranges[name];
  79350. if (!source) {
  79351. continue;
  79352. }
  79353. var range = {};
  79354. range.name = name;
  79355. range.from = source.from;
  79356. range.to = source.to;
  79357. serializationObject.ranges.push(range);
  79358. }
  79359. }
  79360. return serializationObject;
  79361. };
  79362. /**
  79363. * Creates a new skeleton from serialized data
  79364. * @param parsedSkeleton defines the serialized data
  79365. * @param scene defines the hosting scene
  79366. * @returns a new skeleton
  79367. */
  79368. Skeleton.Parse = function (parsedSkeleton, scene) {
  79369. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  79370. if (parsedSkeleton.dimensionsAtRest) {
  79371. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  79372. }
  79373. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  79374. var index;
  79375. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  79376. var parsedBone = parsedSkeleton.bones[index];
  79377. var parentBone = null;
  79378. if (parsedBone.parentBoneIndex > -1) {
  79379. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  79380. }
  79381. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  79382. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  79383. if (parsedBone.length) {
  79384. bone.length = parsedBone.length;
  79385. }
  79386. if (parsedBone.animation) {
  79387. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  79388. }
  79389. }
  79390. // placed after bones, so createAnimationRange can cascade down
  79391. if (parsedSkeleton.ranges) {
  79392. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  79393. var data = parsedSkeleton.ranges[index];
  79394. skeleton.createAnimationRange(data.name, data.from, data.to);
  79395. }
  79396. }
  79397. return skeleton;
  79398. };
  79399. /**
  79400. * Compute all node absolute transforms
  79401. * @param forceUpdate defines if computation must be done even if cache is up to date
  79402. */
  79403. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  79404. if (forceUpdate === void 0) { forceUpdate = false; }
  79405. var renderId = this._scene.getRenderId();
  79406. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  79407. this.bones[0].computeAbsoluteTransforms();
  79408. this._lastAbsoluteTransformsUpdateId = renderId;
  79409. }
  79410. };
  79411. /**
  79412. * Gets the root pose matrix
  79413. * @returns a matrix
  79414. */
  79415. Skeleton.prototype.getPoseMatrix = function () {
  79416. var poseMatrix = null;
  79417. if (this._meshesWithPoseMatrix.length > 0) {
  79418. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  79419. }
  79420. return poseMatrix;
  79421. };
  79422. /**
  79423. * Sorts bones per internal index
  79424. */
  79425. Skeleton.prototype.sortBones = function () {
  79426. var bones = new Array();
  79427. var visited = new Array(this.bones.length);
  79428. for (var index = 0; index < this.bones.length; index++) {
  79429. this._sortBones(index, bones, visited);
  79430. }
  79431. this.bones = bones;
  79432. };
  79433. Skeleton.prototype._sortBones = function (index, bones, visited) {
  79434. if (visited[index]) {
  79435. return;
  79436. }
  79437. visited[index] = true;
  79438. var bone = this.bones[index];
  79439. if (bone._index === undefined) {
  79440. bone._index = index;
  79441. }
  79442. var parentBone = bone.getParent();
  79443. if (parentBone) {
  79444. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  79445. }
  79446. bones.push(bone);
  79447. };
  79448. return Skeleton;
  79449. }());
  79450. BABYLON.Skeleton = Skeleton;
  79451. })(BABYLON || (BABYLON = {}));
  79452. //# sourceMappingURL=babylon.skeleton.js.map
  79453. var BABYLON;
  79454. (function (BABYLON) {
  79455. var SphericalPolynomial = /** @class */ (function () {
  79456. function SphericalPolynomial() {
  79457. this.x = BABYLON.Vector3.Zero();
  79458. this.y = BABYLON.Vector3.Zero();
  79459. this.z = BABYLON.Vector3.Zero();
  79460. this.xx = BABYLON.Vector3.Zero();
  79461. this.yy = BABYLON.Vector3.Zero();
  79462. this.zz = BABYLON.Vector3.Zero();
  79463. this.xy = BABYLON.Vector3.Zero();
  79464. this.yz = BABYLON.Vector3.Zero();
  79465. this.zx = BABYLON.Vector3.Zero();
  79466. }
  79467. SphericalPolynomial.prototype.addAmbient = function (color) {
  79468. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79469. this.xx = this.xx.add(colorVector);
  79470. this.yy = this.yy.add(colorVector);
  79471. this.zz = this.zz.add(colorVector);
  79472. };
  79473. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  79474. var result = new SphericalPolynomial();
  79475. result.x = harmonics.L11.scale(1.02333);
  79476. result.y = harmonics.L1_1.scale(1.02333);
  79477. result.z = harmonics.L10.scale(1.02333);
  79478. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  79479. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  79480. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  79481. result.yz = harmonics.L2_1.scale(0.858086);
  79482. result.zx = harmonics.L21.scale(0.858086);
  79483. result.xy = harmonics.L2_2.scale(0.858086);
  79484. result.scale(1.0 / Math.PI);
  79485. return result;
  79486. };
  79487. SphericalPolynomial.prototype.scale = function (scale) {
  79488. this.x = this.x.scale(scale);
  79489. this.y = this.y.scale(scale);
  79490. this.z = this.z.scale(scale);
  79491. this.xx = this.xx.scale(scale);
  79492. this.yy = this.yy.scale(scale);
  79493. this.zz = this.zz.scale(scale);
  79494. this.yz = this.yz.scale(scale);
  79495. this.zx = this.zx.scale(scale);
  79496. this.xy = this.xy.scale(scale);
  79497. };
  79498. return SphericalPolynomial;
  79499. }());
  79500. BABYLON.SphericalPolynomial = SphericalPolynomial;
  79501. var SphericalHarmonics = /** @class */ (function () {
  79502. function SphericalHarmonics() {
  79503. this.L00 = BABYLON.Vector3.Zero();
  79504. this.L1_1 = BABYLON.Vector3.Zero();
  79505. this.L10 = BABYLON.Vector3.Zero();
  79506. this.L11 = BABYLON.Vector3.Zero();
  79507. this.L2_2 = BABYLON.Vector3.Zero();
  79508. this.L2_1 = BABYLON.Vector3.Zero();
  79509. this.L20 = BABYLON.Vector3.Zero();
  79510. this.L21 = BABYLON.Vector3.Zero();
  79511. this.L22 = BABYLON.Vector3.Zero();
  79512. }
  79513. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  79514. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79515. var c = colorVector.scale(deltaSolidAngle);
  79516. this.L00 = this.L00.add(c.scale(0.282095));
  79517. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  79518. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  79519. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  79520. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  79521. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  79522. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  79523. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  79524. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  79525. };
  79526. SphericalHarmonics.prototype.scale = function (scale) {
  79527. this.L00 = this.L00.scale(scale);
  79528. this.L1_1 = this.L1_1.scale(scale);
  79529. this.L10 = this.L10.scale(scale);
  79530. this.L11 = this.L11.scale(scale);
  79531. this.L2_2 = this.L2_2.scale(scale);
  79532. this.L2_1 = this.L2_1.scale(scale);
  79533. this.L20 = this.L20.scale(scale);
  79534. this.L21 = this.L21.scale(scale);
  79535. this.L22 = this.L22.scale(scale);
  79536. };
  79537. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  79538. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  79539. //
  79540. // E_lm = A_l * L_lm
  79541. //
  79542. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  79543. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  79544. // the scaling factors are given in equation 9.
  79545. // Constant (Band 0)
  79546. this.L00 = this.L00.scale(3.141593);
  79547. // Linear (Band 1)
  79548. this.L1_1 = this.L1_1.scale(2.094395);
  79549. this.L10 = this.L10.scale(2.094395);
  79550. this.L11 = this.L11.scale(2.094395);
  79551. // Quadratic (Band 2)
  79552. this.L2_2 = this.L2_2.scale(0.785398);
  79553. this.L2_1 = this.L2_1.scale(0.785398);
  79554. this.L20 = this.L20.scale(0.785398);
  79555. this.L21 = this.L21.scale(0.785398);
  79556. this.L22 = this.L22.scale(0.785398);
  79557. };
  79558. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  79559. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  79560. // L = (1/pi) * E * rho
  79561. //
  79562. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  79563. this.scale(1.0 / Math.PI);
  79564. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  79565. // (The pixel shader must apply albedo after texture fetches, etc).
  79566. };
  79567. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  79568. var result = new SphericalHarmonics();
  79569. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  79570. result.L1_1 = polynomial.y.scale(0.977204);
  79571. result.L10 = polynomial.z.scale(0.977204);
  79572. result.L11 = polynomial.x.scale(0.977204);
  79573. result.L2_2 = polynomial.xy.scale(1.16538);
  79574. result.L2_1 = polynomial.yz.scale(1.16538);
  79575. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  79576. result.L21 = polynomial.zx.scale(1.16538);
  79577. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  79578. result.scale(Math.PI);
  79579. return result;
  79580. };
  79581. return SphericalHarmonics;
  79582. }());
  79583. BABYLON.SphericalHarmonics = SphericalHarmonics;
  79584. })(BABYLON || (BABYLON = {}));
  79585. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  79586. var BABYLON;
  79587. (function (BABYLON) {
  79588. var FileFaceOrientation = /** @class */ (function () {
  79589. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  79590. this.name = name;
  79591. this.worldAxisForNormal = worldAxisForNormal;
  79592. this.worldAxisForFileX = worldAxisForFileX;
  79593. this.worldAxisForFileY = worldAxisForFileY;
  79594. }
  79595. return FileFaceOrientation;
  79596. }());
  79597. ;
  79598. /**
  79599. * Helper class dealing with the extraction of spherical polynomial dataArray
  79600. * from a cube map.
  79601. */
  79602. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  79603. function CubeMapToSphericalPolynomialTools() {
  79604. }
  79605. /**
  79606. * Converts a texture to the according Spherical Polynomial data.
  79607. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79608. *
  79609. * @param texture The texture to extract the information from.
  79610. * @return The Spherical Polynomial data.
  79611. */
  79612. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  79613. if (!texture.isCube) {
  79614. // Only supports cube Textures currently.
  79615. return null;
  79616. }
  79617. var size = texture.getSize().width;
  79618. var right = texture.readPixels(0);
  79619. var left = texture.readPixels(1);
  79620. var up;
  79621. var down;
  79622. if (texture.isRenderTarget) {
  79623. up = texture.readPixels(3);
  79624. down = texture.readPixels(2);
  79625. }
  79626. else {
  79627. up = texture.readPixels(2);
  79628. down = texture.readPixels(3);
  79629. }
  79630. var front = texture.readPixels(4);
  79631. var back = texture.readPixels(5);
  79632. var gammaSpace = texture.gammaSpace;
  79633. // Always read as RGBA.
  79634. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  79635. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79636. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79637. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79638. }
  79639. var cubeInfo = {
  79640. size: size,
  79641. right: right,
  79642. left: left,
  79643. up: up,
  79644. down: down,
  79645. front: front,
  79646. back: back,
  79647. format: format,
  79648. type: type,
  79649. gammaSpace: gammaSpace,
  79650. };
  79651. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  79652. };
  79653. /**
  79654. * Converts a cubemap to the according Spherical Polynomial data.
  79655. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79656. *
  79657. * @param cubeInfo The Cube map to extract the information from.
  79658. * @return The Spherical Polynomial data.
  79659. */
  79660. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  79661. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  79662. var totalSolidAngle = 0.0;
  79663. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  79664. var du = 2.0 / cubeInfo.size;
  79665. var dv = du;
  79666. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  79667. var minUV = du * 0.5 - 1.0;
  79668. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79669. var fileFace = this.FileFaces[faceIndex];
  79670. var dataArray = cubeInfo[fileFace.name];
  79671. var v = minUV;
  79672. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  79673. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  79674. // Because SP is still linear, so summation is fine in that basis.
  79675. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  79676. for (var y = 0; y < cubeInfo.size; y++) {
  79677. var u = minUV;
  79678. for (var x = 0; x < cubeInfo.size; x++) {
  79679. // World direction (not normalised)
  79680. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  79681. worldDirection.normalize();
  79682. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  79683. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  79684. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  79685. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  79686. // Handle Integer types.
  79687. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79688. r /= 255;
  79689. g /= 255;
  79690. b /= 255;
  79691. }
  79692. // Handle Gamma space textures.
  79693. if (cubeInfo.gammaSpace) {
  79694. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  79695. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  79696. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  79697. }
  79698. var color = new BABYLON.Color3(r, g, b);
  79699. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  79700. totalSolidAngle += deltaSolidAngle;
  79701. u += du;
  79702. }
  79703. v += dv;
  79704. }
  79705. }
  79706. // Solid angle for entire sphere is 4*pi
  79707. var sphereSolidAngle = 4.0 * Math.PI;
  79708. // Adjust the solid angle to allow for how many faces we processed.
  79709. var facesProcessed = 6.0;
  79710. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  79711. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  79712. // This is needed because the numerical integration over the cube uses a
  79713. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  79714. // and also to compensate for accumulative error due to float precision in the summation.
  79715. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  79716. sphericalHarmonics.scale(correctionFactor);
  79717. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  79718. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  79719. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  79720. };
  79721. CubeMapToSphericalPolynomialTools.FileFaces = [
  79722. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  79723. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  79724. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  79725. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  79726. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  79727. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  79728. ];
  79729. return CubeMapToSphericalPolynomialTools;
  79730. }());
  79731. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  79732. })(BABYLON || (BABYLON = {}));
  79733. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  79734. var BABYLON;
  79735. (function (BABYLON) {
  79736. /**
  79737. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  79738. */
  79739. var PanoramaToCubeMapTools = /** @class */ (function () {
  79740. function PanoramaToCubeMapTools() {
  79741. }
  79742. /**
  79743. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  79744. *
  79745. * @param float32Array The source data.
  79746. * @param inputWidth The width of the input panorama.
  79747. * @param inputhHeight The height of the input panorama.
  79748. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  79749. * @return The cubemap data
  79750. */
  79751. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  79752. if (!float32Array) {
  79753. throw "ConvertPanoramaToCubemap: input cannot be null";
  79754. }
  79755. if (float32Array.length != inputWidth * inputHeight * 3) {
  79756. throw "ConvertPanoramaToCubemap: input size is wrong";
  79757. }
  79758. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  79759. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  79760. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  79761. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  79762. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  79763. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  79764. return {
  79765. front: textureFront,
  79766. back: textureBack,
  79767. left: textureLeft,
  79768. right: textureRight,
  79769. up: textureUp,
  79770. down: textureDown,
  79771. size: size,
  79772. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  79773. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  79774. gammaSpace: false,
  79775. };
  79776. };
  79777. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  79778. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  79779. var textureArray = new Float32Array(buffer);
  79780. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  79781. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  79782. var dy = 1 / texSize;
  79783. var fy = 0;
  79784. for (var y = 0; y < texSize; y++) {
  79785. var xv1 = faceData[0];
  79786. var xv2 = faceData[2];
  79787. for (var x = 0; x < texSize; x++) {
  79788. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  79789. v.normalize();
  79790. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  79791. // 3 channels per pixels
  79792. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  79793. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  79794. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  79795. xv1 = xv1.add(rotDX1);
  79796. xv2 = xv2.add(rotDX2);
  79797. }
  79798. fy += dy;
  79799. }
  79800. return textureArray;
  79801. };
  79802. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  79803. var theta = Math.atan2(vDir.z, vDir.x);
  79804. var phi = Math.acos(vDir.y);
  79805. while (theta < -Math.PI)
  79806. theta += 2 * Math.PI;
  79807. while (theta > Math.PI)
  79808. theta -= 2 * Math.PI;
  79809. var dx = theta / Math.PI;
  79810. var dy = phi / Math.PI;
  79811. // recenter.
  79812. dx = dx * 0.5 + 0.5;
  79813. var px = Math.round(dx * inputWidth);
  79814. if (px < 0)
  79815. px = 0;
  79816. else if (px >= inputWidth)
  79817. px = inputWidth - 1;
  79818. var py = Math.round(dy * inputHeight);
  79819. if (py < 0)
  79820. py = 0;
  79821. else if (py >= inputHeight)
  79822. py = inputHeight - 1;
  79823. var inputY = (inputHeight - py - 1);
  79824. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  79825. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  79826. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  79827. return {
  79828. r: r,
  79829. g: g,
  79830. b: b
  79831. };
  79832. };
  79833. PanoramaToCubeMapTools.FACE_FRONT = [
  79834. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79835. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79836. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79837. new BABYLON.Vector3(1.0, 1.0, -1.0)
  79838. ];
  79839. PanoramaToCubeMapTools.FACE_BACK = [
  79840. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79841. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79842. new BABYLON.Vector3(1.0, 1.0, 1.0),
  79843. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  79844. ];
  79845. PanoramaToCubeMapTools.FACE_RIGHT = [
  79846. new BABYLON.Vector3(1.0, -1.0, -1.0),
  79847. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79848. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79849. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79850. ];
  79851. PanoramaToCubeMapTools.FACE_LEFT = [
  79852. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79853. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79854. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79855. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  79856. ];
  79857. PanoramaToCubeMapTools.FACE_DOWN = [
  79858. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  79859. new BABYLON.Vector3(1.0, 1.0, -1.0),
  79860. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  79861. new BABYLON.Vector3(1.0, 1.0, 1.0)
  79862. ];
  79863. PanoramaToCubeMapTools.FACE_UP = [
  79864. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  79865. new BABYLON.Vector3(1.0, -1.0, 1.0),
  79866. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  79867. new BABYLON.Vector3(1.0, -1.0, -1.0)
  79868. ];
  79869. return PanoramaToCubeMapTools;
  79870. }());
  79871. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  79872. })(BABYLON || (BABYLON = {}));
  79873. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  79874. var BABYLON;
  79875. (function (BABYLON) {
  79876. ;
  79877. /**
  79878. * This groups tools to convert HDR texture to native colors array.
  79879. */
  79880. var HDRTools = /** @class */ (function () {
  79881. function HDRTools() {
  79882. }
  79883. HDRTools.Ldexp = function (mantissa, exponent) {
  79884. if (exponent > 1023) {
  79885. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  79886. }
  79887. if (exponent < -1074) {
  79888. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  79889. }
  79890. return mantissa * Math.pow(2, exponent);
  79891. };
  79892. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  79893. if (exponent > 0) { /*nonzero pixel*/
  79894. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  79895. float32array[index + 0] = red * exponent;
  79896. float32array[index + 1] = green * exponent;
  79897. float32array[index + 2] = blue * exponent;
  79898. }
  79899. else {
  79900. float32array[index + 0] = 0;
  79901. float32array[index + 1] = 0;
  79902. float32array[index + 2] = 0;
  79903. }
  79904. };
  79905. HDRTools.readStringLine = function (uint8array, startIndex) {
  79906. var line = "";
  79907. var character = "";
  79908. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  79909. character = String.fromCharCode(uint8array[i]);
  79910. if (character == "\n") {
  79911. break;
  79912. }
  79913. line += character;
  79914. }
  79915. return line;
  79916. };
  79917. /**
  79918. * Reads header information from an RGBE texture stored in a native array.
  79919. * More information on this format are available here:
  79920. * https://en.wikipedia.org/wiki/RGBE_image_format
  79921. *
  79922. * @param uint8array The binary file stored in native array.
  79923. * @return The header information.
  79924. */
  79925. HDRTools.RGBE_ReadHeader = function (uint8array) {
  79926. var height = 0;
  79927. var width = 0;
  79928. var line = this.readStringLine(uint8array, 0);
  79929. if (line[0] != '#' || line[1] != '?') {
  79930. throw "Bad HDR Format.";
  79931. }
  79932. var endOfHeader = false;
  79933. var findFormat = false;
  79934. var lineIndex = 0;
  79935. do {
  79936. lineIndex += (line.length + 1);
  79937. line = this.readStringLine(uint8array, lineIndex);
  79938. if (line == "FORMAT=32-bit_rle_rgbe") {
  79939. findFormat = true;
  79940. }
  79941. else if (line.length == 0) {
  79942. endOfHeader = true;
  79943. }
  79944. } while (!endOfHeader);
  79945. if (!findFormat) {
  79946. throw "HDR Bad header format, unsupported FORMAT";
  79947. }
  79948. lineIndex += (line.length + 1);
  79949. line = this.readStringLine(uint8array, lineIndex);
  79950. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  79951. var match = sizeRegexp.exec(line);
  79952. // TODO. Support +Y and -X if needed.
  79953. if (!match || match.length < 3) {
  79954. throw "HDR Bad header format, no size";
  79955. }
  79956. width = parseInt(match[2]);
  79957. height = parseInt(match[1]);
  79958. if (width < 8 || width > 0x7fff) {
  79959. throw "HDR Bad header format, unsupported size";
  79960. }
  79961. lineIndex += (line.length + 1);
  79962. return {
  79963. height: height,
  79964. width: width,
  79965. dataPosition: lineIndex
  79966. };
  79967. };
  79968. /**
  79969. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  79970. * This RGBE texture needs to store the information as a panorama.
  79971. *
  79972. * More information on this format are available here:
  79973. * https://en.wikipedia.org/wiki/RGBE_image_format
  79974. *
  79975. * @param buffer The binary file stored in an array buffer.
  79976. * @param size The expected size of the extracted cubemap.
  79977. * @return The Cube Map information.
  79978. */
  79979. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  79980. var uint8array = new Uint8Array(buffer);
  79981. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  79982. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  79983. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  79984. return cubeMapData;
  79985. };
  79986. /**
  79987. * Returns the pixels data extracted from an RGBE texture.
  79988. * This pixels will be stored left to right up to down in the R G B order in one array.
  79989. *
  79990. * More information on this format are available here:
  79991. * https://en.wikipedia.org/wiki/RGBE_image_format
  79992. *
  79993. * @param uint8array The binary file stored in an array buffer.
  79994. * @param hdrInfo The header information of the file.
  79995. * @return The pixels data in RGB right to left up to down order.
  79996. */
  79997. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  79998. // Keep for multi format supports.
  79999. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80000. };
  80001. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80002. var num_scanlines = hdrInfo.height;
  80003. var scanline_width = hdrInfo.width;
  80004. var a, b, c, d, count;
  80005. var dataIndex = hdrInfo.dataPosition;
  80006. var index = 0, endIndex = 0, i = 0;
  80007. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80008. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80009. // 3 channels of 4 bytes per pixel in float.
  80010. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80011. var resultArray = new Float32Array(resultBuffer);
  80012. // read in each successive scanline
  80013. while (num_scanlines > 0) {
  80014. a = uint8array[dataIndex++];
  80015. b = uint8array[dataIndex++];
  80016. c = uint8array[dataIndex++];
  80017. d = uint8array[dataIndex++];
  80018. if (a != 2 || b != 2 || (c & 0x80)) {
  80019. // this file is not run length encoded
  80020. throw "HDR Bad header format, not RLE";
  80021. }
  80022. if (((c << 8) | d) != scanline_width) {
  80023. throw "HDR Bad header format, wrong scan line width";
  80024. }
  80025. index = 0;
  80026. // read each of the four channels for the scanline into the buffer
  80027. for (i = 0; i < 4; i++) {
  80028. endIndex = (i + 1) * scanline_width;
  80029. while (index < endIndex) {
  80030. a = uint8array[dataIndex++];
  80031. b = uint8array[dataIndex++];
  80032. if (a > 128) {
  80033. // a run of the same value
  80034. count = a - 128;
  80035. if ((count == 0) || (count > endIndex - index)) {
  80036. throw "HDR Bad Format, bad scanline data (run)";
  80037. }
  80038. while (count-- > 0) {
  80039. scanLineArray[index++] = b;
  80040. }
  80041. }
  80042. else {
  80043. // a non-run
  80044. count = a;
  80045. if ((count == 0) || (count > endIndex - index)) {
  80046. throw "HDR Bad Format, bad scanline data (non-run)";
  80047. }
  80048. scanLineArray[index++] = b;
  80049. if (--count > 0) {
  80050. for (var j = 0; j < count; j++) {
  80051. scanLineArray[index++] = uint8array[dataIndex++];
  80052. }
  80053. }
  80054. }
  80055. }
  80056. }
  80057. // now convert data from buffer into floats
  80058. for (i = 0; i < scanline_width; i++) {
  80059. a = scanLineArray[i];
  80060. b = scanLineArray[i + scanline_width];
  80061. c = scanLineArray[i + 2 * scanline_width];
  80062. d = scanLineArray[i + 3 * scanline_width];
  80063. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80064. }
  80065. num_scanlines--;
  80066. }
  80067. return resultArray;
  80068. };
  80069. return HDRTools;
  80070. }());
  80071. BABYLON.HDRTools = HDRTools;
  80072. })(BABYLON || (BABYLON = {}));
  80073. //# sourceMappingURL=babylon.hdr.js.map
  80074. var BABYLON;
  80075. (function (BABYLON) {
  80076. /**
  80077. * This represents a texture coming from an HDR input.
  80078. *
  80079. * The only supported format is currently panorama picture stored in RGBE format.
  80080. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80081. */
  80082. var HDRCubeTexture = /** @class */ (function (_super) {
  80083. __extends(HDRCubeTexture, _super);
  80084. /**
  80085. * Instantiates an HDRTexture from the following parameters.
  80086. *
  80087. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80088. * @param scene The scene the texture will be used in
  80089. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80090. * @param noMipmap Forces to not generate the mipmap if true
  80091. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80092. * @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)
  80093. * @param reserved Reserved flag for internal use.
  80094. */
  80095. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80096. if (noMipmap === void 0) { noMipmap = false; }
  80097. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80098. if (gammaSpace === void 0) { gammaSpace = false; }
  80099. if (reserved === void 0) { reserved = false; }
  80100. if (onLoad === void 0) { onLoad = null; }
  80101. if (onError === void 0) { onError = null; }
  80102. var _this = _super.call(this, scene) || this;
  80103. _this._generateHarmonics = true;
  80104. _this._onLoad = null;
  80105. _this._onError = null;
  80106. /**
  80107. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80108. */
  80109. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80110. _this._isBlocking = true;
  80111. _this._rotationY = 0;
  80112. /**
  80113. * Gets or sets the center of the bounding box associated with the cube texture
  80114. * It must define where the camera used to render the texture was set
  80115. */
  80116. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80117. if (!url) {
  80118. return _this;
  80119. }
  80120. _this.name = url;
  80121. _this.url = url;
  80122. _this.hasAlpha = false;
  80123. _this.isCube = true;
  80124. _this._textureMatrix = BABYLON.Matrix.Identity();
  80125. _this._onLoad = onLoad;
  80126. _this._onError = onError;
  80127. _this.gammaSpace = gammaSpace;
  80128. _this._noMipmap = noMipmap;
  80129. _this._size = size;
  80130. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80131. if (!_this._texture) {
  80132. if (!scene.useDelayedTextureLoading) {
  80133. _this.loadTexture();
  80134. }
  80135. else {
  80136. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80137. }
  80138. }
  80139. return _this;
  80140. }
  80141. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80142. /**
  80143. * Gets wether or not the texture is blocking during loading.
  80144. */
  80145. get: function () {
  80146. return this._isBlocking;
  80147. },
  80148. /**
  80149. * Sets wether or not the texture is blocking during loading.
  80150. */
  80151. set: function (value) {
  80152. this._isBlocking = value;
  80153. },
  80154. enumerable: true,
  80155. configurable: true
  80156. });
  80157. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80158. /**
  80159. * Gets texture matrix rotation angle around Y axis radians.
  80160. */
  80161. get: function () {
  80162. return this._rotationY;
  80163. },
  80164. /**
  80165. * Sets texture matrix rotation angle around Y axis in radians.
  80166. */
  80167. set: function (value) {
  80168. this._rotationY = value;
  80169. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80170. },
  80171. enumerable: true,
  80172. configurable: true
  80173. });
  80174. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80175. get: function () {
  80176. return this._boundingBoxSize;
  80177. },
  80178. /**
  80179. * Gets or sets the size of the bounding box associated with the cube texture
  80180. * When defined, the cubemap will switch to local mode
  80181. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80182. * @example https://www.babylonjs-playground.com/#RNASML
  80183. */
  80184. set: function (value) {
  80185. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80186. return;
  80187. }
  80188. this._boundingBoxSize = value;
  80189. var scene = this.getScene();
  80190. if (scene) {
  80191. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80192. }
  80193. },
  80194. enumerable: true,
  80195. configurable: true
  80196. });
  80197. /**
  80198. * Occurs when the file is raw .hdr file.
  80199. */
  80200. HDRCubeTexture.prototype.loadTexture = function () {
  80201. var _this = this;
  80202. var callback = function (buffer) {
  80203. var scene = _this.getScene();
  80204. if (!scene) {
  80205. return null;
  80206. }
  80207. // Extract the raw linear data.
  80208. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80209. // Generate harmonics if needed.
  80210. if (_this._generateHarmonics) {
  80211. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80212. _this.sphericalPolynomial = sphericalPolynomial;
  80213. }
  80214. var results = [];
  80215. var byteArray = null;
  80216. // Push each faces.
  80217. for (var j = 0; j < 6; j++) {
  80218. // Create uintarray fallback.
  80219. if (!scene.getEngine().getCaps().textureFloat) {
  80220. // 3 channels of 1 bytes per pixel in bytes.
  80221. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80222. byteArray = new Uint8Array(byteBuffer);
  80223. }
  80224. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80225. // If special cases.
  80226. if (_this.gammaSpace || byteArray) {
  80227. for (var i = 0; i < _this._size * _this._size; i++) {
  80228. // Put in gamma space if requested.
  80229. if (_this.gammaSpace) {
  80230. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80231. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80232. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80233. }
  80234. // Convert to int texture for fallback.
  80235. if (byteArray) {
  80236. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80237. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80238. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80239. // May use luminance instead if the result is not accurate.
  80240. var max = Math.max(Math.max(r, g), b);
  80241. if (max > 255) {
  80242. var scale = 255 / max;
  80243. r *= scale;
  80244. g *= scale;
  80245. b *= scale;
  80246. }
  80247. byteArray[(i * 3) + 0] = r;
  80248. byteArray[(i * 3) + 1] = g;
  80249. byteArray[(i * 3) + 2] = b;
  80250. }
  80251. }
  80252. }
  80253. if (byteArray) {
  80254. results.push(byteArray);
  80255. }
  80256. else {
  80257. results.push(dataFace);
  80258. }
  80259. }
  80260. return results;
  80261. };
  80262. var scene = this.getScene();
  80263. if (scene) {
  80264. 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);
  80265. }
  80266. };
  80267. HDRCubeTexture.prototype.clone = function () {
  80268. var scene = this.getScene();
  80269. if (!scene) {
  80270. return this;
  80271. }
  80272. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  80273. // Base texture
  80274. newTexture.level = this.level;
  80275. newTexture.wrapU = this.wrapU;
  80276. newTexture.wrapV = this.wrapV;
  80277. newTexture.coordinatesIndex = this.coordinatesIndex;
  80278. newTexture.coordinatesMode = this.coordinatesMode;
  80279. return newTexture;
  80280. };
  80281. // Methods
  80282. HDRCubeTexture.prototype.delayLoad = function () {
  80283. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80284. return;
  80285. }
  80286. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80287. this._texture = this._getFromCache(this.url, this._noMipmap);
  80288. if (!this._texture) {
  80289. this.loadTexture();
  80290. }
  80291. };
  80292. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  80293. return this._textureMatrix;
  80294. };
  80295. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  80296. this._textureMatrix = value;
  80297. };
  80298. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80299. var texture = null;
  80300. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80301. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  80302. texture.name = parsedTexture.name;
  80303. texture.hasAlpha = parsedTexture.hasAlpha;
  80304. texture.level = parsedTexture.level;
  80305. texture.coordinatesMode = parsedTexture.coordinatesMode;
  80306. texture.isBlocking = parsedTexture.isBlocking;
  80307. }
  80308. if (texture) {
  80309. if (parsedTexture.boundingBoxPosition) {
  80310. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  80311. }
  80312. if (parsedTexture.boundingBoxSize) {
  80313. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  80314. }
  80315. if (parsedTexture.rotationY) {
  80316. texture.rotationY = parsedTexture.rotationY;
  80317. }
  80318. }
  80319. return texture;
  80320. };
  80321. HDRCubeTexture.prototype.serialize = function () {
  80322. if (!this.name) {
  80323. return null;
  80324. }
  80325. var serializationObject = {};
  80326. serializationObject.name = this.name;
  80327. serializationObject.hasAlpha = this.hasAlpha;
  80328. serializationObject.isCube = true;
  80329. serializationObject.level = this.level;
  80330. serializationObject.size = this._size;
  80331. serializationObject.coordinatesMode = this.coordinatesMode;
  80332. serializationObject.useInGammaSpace = this.gammaSpace;
  80333. serializationObject.generateHarmonics = this._generateHarmonics;
  80334. serializationObject.customType = "BABYLON.HDRCubeTexture";
  80335. serializationObject.noMipmap = this._noMipmap;
  80336. serializationObject.isBlocking = this._isBlocking;
  80337. serializationObject.rotationY = this._rotationY;
  80338. return serializationObject;
  80339. };
  80340. HDRCubeTexture._facesMapping = [
  80341. "right",
  80342. "left",
  80343. "up",
  80344. "down",
  80345. "front",
  80346. "back"
  80347. ];
  80348. return HDRCubeTexture;
  80349. }(BABYLON.BaseTexture));
  80350. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80351. })(BABYLON || (BABYLON = {}));
  80352. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80353. var BABYLON;
  80354. (function (BABYLON) {
  80355. var IndexedVector2 = /** @class */ (function (_super) {
  80356. __extends(IndexedVector2, _super);
  80357. function IndexedVector2(original, index) {
  80358. var _this = _super.call(this, original.x, original.y) || this;
  80359. _this.index = index;
  80360. return _this;
  80361. }
  80362. return IndexedVector2;
  80363. }(BABYLON.Vector2));
  80364. var PolygonPoints = /** @class */ (function () {
  80365. function PolygonPoints() {
  80366. this.elements = new Array();
  80367. }
  80368. PolygonPoints.prototype.add = function (originalPoints) {
  80369. var _this = this;
  80370. var result = new Array();
  80371. originalPoints.forEach(function (point) {
  80372. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80373. var newPoint = new IndexedVector2(point, _this.elements.length);
  80374. result.push(newPoint);
  80375. _this.elements.push(newPoint);
  80376. }
  80377. });
  80378. return result;
  80379. };
  80380. PolygonPoints.prototype.computeBounds = function () {
  80381. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80382. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80383. this.elements.forEach(function (point) {
  80384. // x
  80385. if (point.x < lmin.x) {
  80386. lmin.x = point.x;
  80387. }
  80388. else if (point.x > lmax.x) {
  80389. lmax.x = point.x;
  80390. }
  80391. // y
  80392. if (point.y < lmin.y) {
  80393. lmin.y = point.y;
  80394. }
  80395. else if (point.y > lmax.y) {
  80396. lmax.y = point.y;
  80397. }
  80398. });
  80399. return {
  80400. min: lmin,
  80401. max: lmax,
  80402. width: lmax.x - lmin.x,
  80403. height: lmax.y - lmin.y
  80404. };
  80405. };
  80406. return PolygonPoints;
  80407. }());
  80408. var Polygon = /** @class */ (function () {
  80409. function Polygon() {
  80410. }
  80411. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  80412. return [
  80413. new BABYLON.Vector2(xmin, ymin),
  80414. new BABYLON.Vector2(xmax, ymin),
  80415. new BABYLON.Vector2(xmax, ymax),
  80416. new BABYLON.Vector2(xmin, ymax)
  80417. ];
  80418. };
  80419. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  80420. if (cx === void 0) { cx = 0; }
  80421. if (cy === void 0) { cy = 0; }
  80422. if (numberOfSides === void 0) { numberOfSides = 32; }
  80423. var result = new Array();
  80424. var angle = 0;
  80425. var increment = (Math.PI * 2) / numberOfSides;
  80426. for (var i = 0; i < numberOfSides; i++) {
  80427. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  80428. angle -= increment;
  80429. }
  80430. return result;
  80431. };
  80432. Polygon.Parse = function (input) {
  80433. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  80434. var i, result = [];
  80435. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  80436. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  80437. }
  80438. return result;
  80439. };
  80440. Polygon.StartingAt = function (x, y) {
  80441. return BABYLON.Path2.StartingAt(x, y);
  80442. };
  80443. return Polygon;
  80444. }());
  80445. BABYLON.Polygon = Polygon;
  80446. var PolygonMeshBuilder = /** @class */ (function () {
  80447. function PolygonMeshBuilder(name, contours, scene) {
  80448. this._points = new PolygonPoints();
  80449. this._outlinepoints = new PolygonPoints();
  80450. this._holes = new Array();
  80451. this._epoints = new Array();
  80452. this._eholes = new Array();
  80453. this._name = name;
  80454. this._scene = scene;
  80455. var points;
  80456. if (contours instanceof BABYLON.Path2) {
  80457. points = contours.getPoints();
  80458. }
  80459. else {
  80460. points = contours;
  80461. }
  80462. this._addToepoint(points);
  80463. this._points.add(points);
  80464. this._outlinepoints.add(points);
  80465. if (typeof earcut === 'undefined') {
  80466. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  80467. }
  80468. }
  80469. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80470. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80471. var p = points_1[_i];
  80472. this._epoints.push(p.x, p.y);
  80473. }
  80474. };
  80475. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80476. this._points.add(hole);
  80477. var holepoints = new PolygonPoints();
  80478. holepoints.add(hole);
  80479. this._holes.push(holepoints);
  80480. this._eholes.push(this._epoints.length / 2);
  80481. this._addToepoint(hole);
  80482. return this;
  80483. };
  80484. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80485. var _this = this;
  80486. if (updatable === void 0) { updatable = false; }
  80487. if (depth === void 0) { depth = 0; }
  80488. var result = new BABYLON.Mesh(this._name, this._scene);
  80489. var normals = new Array();
  80490. var positions = new Array();
  80491. var uvs = new Array();
  80492. var bounds = this._points.computeBounds();
  80493. this._points.elements.forEach(function (p) {
  80494. normals.push(0, 1.0, 0);
  80495. positions.push(p.x, 0, p.y);
  80496. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80497. });
  80498. var indices = new Array();
  80499. var res = earcut(this._epoints, this._eholes, 2);
  80500. for (var i = 0; i < res.length; i++) {
  80501. indices.push(res[i]);
  80502. }
  80503. if (depth > 0) {
  80504. var positionscount = (positions.length / 3); //get the current pointcount
  80505. this._points.elements.forEach(function (p) {
  80506. normals.push(0, -1.0, 0);
  80507. positions.push(p.x, -depth, p.y);
  80508. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80509. });
  80510. var totalCount = indices.length;
  80511. for (var i = 0; i < totalCount; i += 3) {
  80512. var i0 = indices[i + 0];
  80513. var i1 = indices[i + 1];
  80514. var i2 = indices[i + 2];
  80515. indices.push(i2 + positionscount);
  80516. indices.push(i1 + positionscount);
  80517. indices.push(i0 + positionscount);
  80518. }
  80519. //Add the sides
  80520. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80521. this._holes.forEach(function (hole) {
  80522. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80523. });
  80524. }
  80525. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80526. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80527. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80528. result.setIndices(indices);
  80529. return result;
  80530. };
  80531. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80532. var StartIndex = positions.length / 3;
  80533. var ulength = 0;
  80534. for (var i = 0; i < points.elements.length; i++) {
  80535. var p = points.elements[i];
  80536. var p1;
  80537. if ((i + 1) > points.elements.length - 1) {
  80538. p1 = points.elements[0];
  80539. }
  80540. else {
  80541. p1 = points.elements[i + 1];
  80542. }
  80543. positions.push(p.x, 0, p.y);
  80544. positions.push(p.x, -depth, p.y);
  80545. positions.push(p1.x, 0, p1.y);
  80546. positions.push(p1.x, -depth, p1.y);
  80547. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80548. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80549. var v3 = v2.subtract(v1);
  80550. var v4 = new BABYLON.Vector3(0, 1, 0);
  80551. var vn = BABYLON.Vector3.Cross(v3, v4);
  80552. vn = vn.normalize();
  80553. uvs.push(ulength / bounds.width, 0);
  80554. uvs.push(ulength / bounds.width, 1);
  80555. ulength += v3.length();
  80556. uvs.push((ulength / bounds.width), 0);
  80557. uvs.push((ulength / bounds.width), 1);
  80558. if (!flip) {
  80559. normals.push(-vn.x, -vn.y, -vn.z);
  80560. normals.push(-vn.x, -vn.y, -vn.z);
  80561. normals.push(-vn.x, -vn.y, -vn.z);
  80562. normals.push(-vn.x, -vn.y, -vn.z);
  80563. indices.push(StartIndex);
  80564. indices.push(StartIndex + 1);
  80565. indices.push(StartIndex + 2);
  80566. indices.push(StartIndex + 1);
  80567. indices.push(StartIndex + 3);
  80568. indices.push(StartIndex + 2);
  80569. }
  80570. else {
  80571. normals.push(vn.x, vn.y, vn.z);
  80572. normals.push(vn.x, vn.y, vn.z);
  80573. normals.push(vn.x, vn.y, vn.z);
  80574. normals.push(vn.x, vn.y, vn.z);
  80575. indices.push(StartIndex);
  80576. indices.push(StartIndex + 2);
  80577. indices.push(StartIndex + 1);
  80578. indices.push(StartIndex + 1);
  80579. indices.push(StartIndex + 2);
  80580. indices.push(StartIndex + 3);
  80581. }
  80582. StartIndex += 4;
  80583. }
  80584. ;
  80585. };
  80586. return PolygonMeshBuilder;
  80587. }());
  80588. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  80589. })(BABYLON || (BABYLON = {}));
  80590. //# sourceMappingURL=babylon.polygonMesh.js.map
  80591. var BABYLON;
  80592. (function (BABYLON) {
  80593. // Unique ID when we import meshes from Babylon to CSG
  80594. var currentCSGMeshId = 0;
  80595. // # class Vertex
  80596. // Represents a vertex of a polygon. Use your own vertex class instead of this
  80597. // one to provide additional features like texture coordinates and vertex
  80598. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  80599. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  80600. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  80601. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  80602. // is not used anywhere else.
  80603. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  80604. var Vertex = /** @class */ (function () {
  80605. function Vertex(pos, normal, uv) {
  80606. this.pos = pos;
  80607. this.normal = normal;
  80608. this.uv = uv;
  80609. }
  80610. Vertex.prototype.clone = function () {
  80611. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  80612. };
  80613. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  80614. // orientation of a polygon is flipped.
  80615. Vertex.prototype.flip = function () {
  80616. this.normal = this.normal.scale(-1);
  80617. };
  80618. // Create a new vertex between this vertex and `other` by linearly
  80619. // interpolating all properties using a parameter of `t`. Subclasses should
  80620. // override this to interpolate additional properties.
  80621. Vertex.prototype.interpolate = function (other, t) {
  80622. 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));
  80623. };
  80624. return Vertex;
  80625. }());
  80626. // # class Plane
  80627. // Represents a plane in 3D space.
  80628. var Plane = /** @class */ (function () {
  80629. function Plane(normal, w) {
  80630. this.normal = normal;
  80631. this.w = w;
  80632. }
  80633. Plane.FromPoints = function (a, b, c) {
  80634. var v0 = c.subtract(a);
  80635. var v1 = b.subtract(a);
  80636. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  80637. return null;
  80638. }
  80639. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  80640. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  80641. };
  80642. Plane.prototype.clone = function () {
  80643. return new Plane(this.normal.clone(), this.w);
  80644. };
  80645. Plane.prototype.flip = function () {
  80646. this.normal.scaleInPlace(-1);
  80647. this.w = -this.w;
  80648. };
  80649. // Split `polygon` by this plane if needed, then put the polygon or polygon
  80650. // fragments in the appropriate lists. Coplanar polygons go into either
  80651. // `coplanarFront` or `coplanarBack` depending on their orientation with
  80652. // respect to this plane. Polygons in front or in back of this plane go into
  80653. // either `front` or `back`.
  80654. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  80655. var COPLANAR = 0;
  80656. var FRONT = 1;
  80657. var BACK = 2;
  80658. var SPANNING = 3;
  80659. // Classify each point as well as the entire polygon into one of the above
  80660. // four classes.
  80661. var polygonType = 0;
  80662. var types = [];
  80663. var i;
  80664. var t;
  80665. for (i = 0; i < polygon.vertices.length; i++) {
  80666. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  80667. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  80668. polygonType |= type;
  80669. types.push(type);
  80670. }
  80671. // Put the polygon in the correct list, splitting it when necessary.
  80672. switch (polygonType) {
  80673. case COPLANAR:
  80674. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  80675. break;
  80676. case FRONT:
  80677. front.push(polygon);
  80678. break;
  80679. case BACK:
  80680. back.push(polygon);
  80681. break;
  80682. case SPANNING:
  80683. var f = [], b = [];
  80684. for (i = 0; i < polygon.vertices.length; i++) {
  80685. var j = (i + 1) % polygon.vertices.length;
  80686. var ti = types[i], tj = types[j];
  80687. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  80688. if (ti !== BACK)
  80689. f.push(vi);
  80690. if (ti !== FRONT)
  80691. b.push(ti !== BACK ? vi.clone() : vi);
  80692. if ((ti | tj) === SPANNING) {
  80693. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  80694. var v = vi.interpolate(vj, t);
  80695. f.push(v);
  80696. b.push(v.clone());
  80697. }
  80698. }
  80699. var poly;
  80700. if (f.length >= 3) {
  80701. poly = new Polygon(f, polygon.shared);
  80702. if (poly.plane)
  80703. front.push(poly);
  80704. }
  80705. if (b.length >= 3) {
  80706. poly = new Polygon(b, polygon.shared);
  80707. if (poly.plane)
  80708. back.push(poly);
  80709. }
  80710. break;
  80711. }
  80712. };
  80713. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  80714. // point is on the plane.
  80715. Plane.EPSILON = 1e-5;
  80716. return Plane;
  80717. }());
  80718. // # class Polygon
  80719. // Represents a convex polygon. The vertices used to initialize a polygon must
  80720. // be coplanar and form a convex loop.
  80721. //
  80722. // Each convex polygon has a `shared` property, which is shared between all
  80723. // polygons that are clones of each other or were split from the same polygon.
  80724. // This can be used to define per-polygon properties (such as surface color).
  80725. var Polygon = /** @class */ (function () {
  80726. function Polygon(vertices, shared) {
  80727. this.vertices = vertices;
  80728. this.shared = shared;
  80729. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  80730. }
  80731. Polygon.prototype.clone = function () {
  80732. var vertices = this.vertices.map(function (v) { return v.clone(); });
  80733. return new Polygon(vertices, this.shared);
  80734. };
  80735. Polygon.prototype.flip = function () {
  80736. this.vertices.reverse().map(function (v) { v.flip(); });
  80737. this.plane.flip();
  80738. };
  80739. return Polygon;
  80740. }());
  80741. // # class Node
  80742. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  80743. // by picking a polygon to split along. That polygon (and all other coplanar
  80744. // polygons) are added directly to that node and the other polygons are added to
  80745. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  80746. // no distinction between internal and leaf nodes.
  80747. var Node = /** @class */ (function () {
  80748. function Node(polygons) {
  80749. this.plane = null;
  80750. this.front = null;
  80751. this.back = null;
  80752. this.polygons = new Array();
  80753. if (polygons) {
  80754. this.build(polygons);
  80755. }
  80756. }
  80757. Node.prototype.clone = function () {
  80758. var node = new Node();
  80759. node.plane = this.plane && this.plane.clone();
  80760. node.front = this.front && this.front.clone();
  80761. node.back = this.back && this.back.clone();
  80762. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  80763. return node;
  80764. };
  80765. // Convert solid space to empty space and empty space to solid space.
  80766. Node.prototype.invert = function () {
  80767. for (var i = 0; i < this.polygons.length; i++) {
  80768. this.polygons[i].flip();
  80769. }
  80770. if (this.plane) {
  80771. this.plane.flip();
  80772. }
  80773. if (this.front) {
  80774. this.front.invert();
  80775. }
  80776. if (this.back) {
  80777. this.back.invert();
  80778. }
  80779. var temp = this.front;
  80780. this.front = this.back;
  80781. this.back = temp;
  80782. };
  80783. // Recursively remove all polygons in `polygons` that are inside this BSP
  80784. // tree.
  80785. Node.prototype.clipPolygons = function (polygons) {
  80786. if (!this.plane)
  80787. return polygons.slice();
  80788. var front = new Array(), back = new Array();
  80789. for (var i = 0; i < polygons.length; i++) {
  80790. this.plane.splitPolygon(polygons[i], front, back, front, back);
  80791. }
  80792. if (this.front) {
  80793. front = this.front.clipPolygons(front);
  80794. }
  80795. if (this.back) {
  80796. back = this.back.clipPolygons(back);
  80797. }
  80798. else {
  80799. back = [];
  80800. }
  80801. return front.concat(back);
  80802. };
  80803. // Remove all polygons in this BSP tree that are inside the other BSP tree
  80804. // `bsp`.
  80805. Node.prototype.clipTo = function (bsp) {
  80806. this.polygons = bsp.clipPolygons(this.polygons);
  80807. if (this.front)
  80808. this.front.clipTo(bsp);
  80809. if (this.back)
  80810. this.back.clipTo(bsp);
  80811. };
  80812. // Return a list of all polygons in this BSP tree.
  80813. Node.prototype.allPolygons = function () {
  80814. var polygons = this.polygons.slice();
  80815. if (this.front)
  80816. polygons = polygons.concat(this.front.allPolygons());
  80817. if (this.back)
  80818. polygons = polygons.concat(this.back.allPolygons());
  80819. return polygons;
  80820. };
  80821. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  80822. // new polygons are filtered down to the bottom of the tree and become new
  80823. // nodes there. Each set of polygons is partitioned using the first polygon
  80824. // (no heuristic is used to pick a good split).
  80825. Node.prototype.build = function (polygons) {
  80826. if (!polygons.length)
  80827. return;
  80828. if (!this.plane)
  80829. this.plane = polygons[0].plane.clone();
  80830. var front = new Array(), back = new Array();
  80831. for (var i = 0; i < polygons.length; i++) {
  80832. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  80833. }
  80834. if (front.length) {
  80835. if (!this.front)
  80836. this.front = new Node();
  80837. this.front.build(front);
  80838. }
  80839. if (back.length) {
  80840. if (!this.back)
  80841. this.back = new Node();
  80842. this.back.build(back);
  80843. }
  80844. };
  80845. return Node;
  80846. }());
  80847. var CSG = /** @class */ (function () {
  80848. function CSG() {
  80849. this.polygons = new Array();
  80850. }
  80851. // Convert BABYLON.Mesh to BABYLON.CSG
  80852. CSG.FromMesh = function (mesh) {
  80853. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  80854. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  80855. if (mesh instanceof BABYLON.Mesh) {
  80856. mesh.computeWorldMatrix(true);
  80857. matrix = mesh.getWorldMatrix();
  80858. meshPosition = mesh.position.clone();
  80859. meshRotation = mesh.rotation.clone();
  80860. if (mesh.rotationQuaternion) {
  80861. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  80862. }
  80863. meshScaling = mesh.scaling.clone();
  80864. }
  80865. else {
  80866. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  80867. }
  80868. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  80869. var subMeshes = mesh.subMeshes;
  80870. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  80871. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  80872. vertices = [];
  80873. for (var j = 0; j < 3; j++) {
  80874. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  80875. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  80876. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  80877. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  80878. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  80879. vertex = new Vertex(position, normal, uv);
  80880. vertices.push(vertex);
  80881. }
  80882. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  80883. // To handle the case of degenerated triangle
  80884. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  80885. if (polygon.plane)
  80886. polygons.push(polygon);
  80887. }
  80888. }
  80889. var csg = CSG.FromPolygons(polygons);
  80890. csg.matrix = matrix;
  80891. csg.position = meshPosition;
  80892. csg.rotation = meshRotation;
  80893. csg.scaling = meshScaling;
  80894. csg.rotationQuaternion = meshRotationQuaternion;
  80895. currentCSGMeshId++;
  80896. return csg;
  80897. };
  80898. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  80899. CSG.FromPolygons = function (polygons) {
  80900. var csg = new CSG();
  80901. csg.polygons = polygons;
  80902. return csg;
  80903. };
  80904. CSG.prototype.clone = function () {
  80905. var csg = new CSG();
  80906. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  80907. csg.copyTransformAttributes(this);
  80908. return csg;
  80909. };
  80910. CSG.prototype.union = function (csg) {
  80911. var a = new Node(this.clone().polygons);
  80912. var b = new Node(csg.clone().polygons);
  80913. a.clipTo(b);
  80914. b.clipTo(a);
  80915. b.invert();
  80916. b.clipTo(a);
  80917. b.invert();
  80918. a.build(b.allPolygons());
  80919. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80920. };
  80921. CSG.prototype.unionInPlace = function (csg) {
  80922. var a = new Node(this.polygons);
  80923. var b = new Node(csg.polygons);
  80924. a.clipTo(b);
  80925. b.clipTo(a);
  80926. b.invert();
  80927. b.clipTo(a);
  80928. b.invert();
  80929. a.build(b.allPolygons());
  80930. this.polygons = a.allPolygons();
  80931. };
  80932. CSG.prototype.subtract = function (csg) {
  80933. var a = new Node(this.clone().polygons);
  80934. var b = new Node(csg.clone().polygons);
  80935. a.invert();
  80936. a.clipTo(b);
  80937. b.clipTo(a);
  80938. b.invert();
  80939. b.clipTo(a);
  80940. b.invert();
  80941. a.build(b.allPolygons());
  80942. a.invert();
  80943. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80944. };
  80945. CSG.prototype.subtractInPlace = function (csg) {
  80946. var a = new Node(this.polygons);
  80947. var b = new Node(csg.polygons);
  80948. a.invert();
  80949. a.clipTo(b);
  80950. b.clipTo(a);
  80951. b.invert();
  80952. b.clipTo(a);
  80953. b.invert();
  80954. a.build(b.allPolygons());
  80955. a.invert();
  80956. this.polygons = a.allPolygons();
  80957. };
  80958. CSG.prototype.intersect = function (csg) {
  80959. var a = new Node(this.clone().polygons);
  80960. var b = new Node(csg.clone().polygons);
  80961. a.invert();
  80962. b.clipTo(a);
  80963. b.invert();
  80964. a.clipTo(b);
  80965. b.clipTo(a);
  80966. a.build(b.allPolygons());
  80967. a.invert();
  80968. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  80969. };
  80970. CSG.prototype.intersectInPlace = function (csg) {
  80971. var a = new Node(this.polygons);
  80972. var b = new Node(csg.polygons);
  80973. a.invert();
  80974. b.clipTo(a);
  80975. b.invert();
  80976. a.clipTo(b);
  80977. b.clipTo(a);
  80978. a.build(b.allPolygons());
  80979. a.invert();
  80980. this.polygons = a.allPolygons();
  80981. };
  80982. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  80983. // not modified.
  80984. CSG.prototype.inverse = function () {
  80985. var csg = this.clone();
  80986. csg.inverseInPlace();
  80987. return csg;
  80988. };
  80989. CSG.prototype.inverseInPlace = function () {
  80990. this.polygons.map(function (p) { p.flip(); });
  80991. };
  80992. // This is used to keep meshes transformations so they can be restored
  80993. // when we build back a Babylon Mesh
  80994. // NB : All CSG operations are performed in world coordinates
  80995. CSG.prototype.copyTransformAttributes = function (csg) {
  80996. this.matrix = csg.matrix;
  80997. this.position = csg.position;
  80998. this.rotation = csg.rotation;
  80999. this.scaling = csg.scaling;
  81000. this.rotationQuaternion = csg.rotationQuaternion;
  81001. return this;
  81002. };
  81003. // Build Raw mesh from CSG
  81004. // Coordinates here are in world space
  81005. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81006. var matrix = this.matrix.clone();
  81007. matrix.invert();
  81008. 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;
  81009. if (keepSubMeshes) {
  81010. // Sort Polygons, since subMeshes are indices range
  81011. polygons.sort(function (a, b) {
  81012. if (a.shared.meshId === b.shared.meshId) {
  81013. return a.shared.subMeshId - b.shared.subMeshId;
  81014. }
  81015. else {
  81016. return a.shared.meshId - b.shared.meshId;
  81017. }
  81018. });
  81019. }
  81020. for (var i = 0, il = polygons.length; i < il; i++) {
  81021. polygon = polygons[i];
  81022. // Building SubMeshes
  81023. if (!subMesh_dict[polygon.shared.meshId]) {
  81024. subMesh_dict[polygon.shared.meshId] = {};
  81025. }
  81026. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81027. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81028. indexStart: +Infinity,
  81029. indexEnd: -Infinity,
  81030. materialIndex: polygon.shared.materialIndex
  81031. };
  81032. }
  81033. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81034. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81035. polygonIndices[0] = 0;
  81036. polygonIndices[1] = j - 1;
  81037. polygonIndices[2] = j;
  81038. for (var k = 0; k < 3; k++) {
  81039. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81040. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81041. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81042. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81043. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81044. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81045. // Check if 2 points can be merged
  81046. if (!(typeof vertex_idx !== 'undefined' &&
  81047. normals[vertex_idx * 3] === localNormal.x &&
  81048. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81049. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81050. uvs[vertex_idx * 2] === uv.x &&
  81051. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81052. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81053. uvs.push(uv.x, uv.y);
  81054. normals.push(normal.x, normal.y, normal.z);
  81055. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81056. }
  81057. indices.push(vertex_idx);
  81058. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81059. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81060. currentIndex++;
  81061. }
  81062. }
  81063. }
  81064. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81065. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81066. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81067. mesh.setIndices(indices, null);
  81068. if (keepSubMeshes) {
  81069. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81070. var materialIndexOffset = 0, materialMaxIndex;
  81071. mesh.subMeshes = new Array();
  81072. for (var m in subMesh_dict) {
  81073. materialMaxIndex = -1;
  81074. for (var sm in subMesh_dict[m]) {
  81075. subMesh_obj = subMesh_dict[m][sm];
  81076. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81077. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81078. }
  81079. materialIndexOffset += ++materialMaxIndex;
  81080. }
  81081. }
  81082. return mesh;
  81083. };
  81084. // Build Mesh from CSG taking material and transforms into account
  81085. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81086. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81087. mesh.material = material;
  81088. mesh.position.copyFrom(this.position);
  81089. mesh.rotation.copyFrom(this.rotation);
  81090. if (this.rotationQuaternion) {
  81091. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81092. }
  81093. mesh.scaling.copyFrom(this.scaling);
  81094. mesh.computeWorldMatrix(true);
  81095. return mesh;
  81096. };
  81097. return CSG;
  81098. }());
  81099. BABYLON.CSG = CSG;
  81100. })(BABYLON || (BABYLON = {}));
  81101. //# sourceMappingURL=babylon.csg.js.map
  81102. var BABYLON;
  81103. (function (BABYLON) {
  81104. var LensFlare = /** @class */ (function () {
  81105. function LensFlare(size, position, color, imgUrl, system) {
  81106. this.size = size;
  81107. this.position = position;
  81108. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81109. this.color = color || new BABYLON.Color3(1, 1, 1);
  81110. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81111. this._system = system;
  81112. system.lensFlares.push(this);
  81113. }
  81114. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81115. return new LensFlare(size, position, color, imgUrl, system);
  81116. };
  81117. LensFlare.prototype.dispose = function () {
  81118. if (this.texture) {
  81119. this.texture.dispose();
  81120. }
  81121. // Remove from scene
  81122. var index = this._system.lensFlares.indexOf(this);
  81123. this._system.lensFlares.splice(index, 1);
  81124. };
  81125. ;
  81126. return LensFlare;
  81127. }());
  81128. BABYLON.LensFlare = LensFlare;
  81129. })(BABYLON || (BABYLON = {}));
  81130. //# sourceMappingURL=babylon.lensFlare.js.map
  81131. var BABYLON;
  81132. (function (BABYLON) {
  81133. var LensFlareSystem = /** @class */ (function () {
  81134. function LensFlareSystem(name, emitter, scene) {
  81135. this.name = name;
  81136. this.lensFlares = new Array();
  81137. this.borderLimit = 300;
  81138. this.viewportBorder = 0;
  81139. this.layerMask = 0x0FFFFFFF;
  81140. this._vertexBuffers = {};
  81141. this._isEnabled = true;
  81142. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81143. this._emitter = emitter;
  81144. this.id = name;
  81145. scene.lensFlareSystems.push(this);
  81146. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81147. var engine = scene.getEngine();
  81148. // VBO
  81149. var vertices = [];
  81150. vertices.push(1, 1);
  81151. vertices.push(-1, 1);
  81152. vertices.push(-1, -1);
  81153. vertices.push(1, -1);
  81154. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81155. // Indices
  81156. var indices = [];
  81157. indices.push(0);
  81158. indices.push(1);
  81159. indices.push(2);
  81160. indices.push(0);
  81161. indices.push(2);
  81162. indices.push(3);
  81163. this._indexBuffer = engine.createIndexBuffer(indices);
  81164. // Effects
  81165. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81166. }
  81167. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81168. get: function () {
  81169. return this._isEnabled;
  81170. },
  81171. set: function (value) {
  81172. this._isEnabled = value;
  81173. },
  81174. enumerable: true,
  81175. configurable: true
  81176. });
  81177. LensFlareSystem.prototype.getScene = function () {
  81178. return this._scene;
  81179. };
  81180. LensFlareSystem.prototype.getEmitter = function () {
  81181. return this._emitter;
  81182. };
  81183. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81184. this._emitter = newEmitter;
  81185. };
  81186. LensFlareSystem.prototype.getEmitterPosition = function () {
  81187. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81188. };
  81189. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81190. var position = this.getEmitterPosition();
  81191. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81192. this._positionX = position.x;
  81193. this._positionY = position.y;
  81194. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81195. if (this.viewportBorder > 0) {
  81196. globalViewport.x -= this.viewportBorder;
  81197. globalViewport.y -= this.viewportBorder;
  81198. globalViewport.width += this.viewportBorder * 2;
  81199. globalViewport.height += this.viewportBorder * 2;
  81200. position.x += this.viewportBorder;
  81201. position.y += this.viewportBorder;
  81202. this._positionX += this.viewportBorder;
  81203. this._positionY += this.viewportBorder;
  81204. }
  81205. if (position.z > 0) {
  81206. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81207. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81208. return true;
  81209. }
  81210. return true;
  81211. }
  81212. return false;
  81213. };
  81214. LensFlareSystem.prototype._isVisible = function () {
  81215. if (!this._isEnabled || !this._scene.activeCamera) {
  81216. return false;
  81217. }
  81218. var emitterPosition = this.getEmitterPosition();
  81219. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81220. var distance = direction.length();
  81221. direction.normalize();
  81222. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81223. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81224. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81225. };
  81226. LensFlareSystem.prototype.render = function () {
  81227. if (!this._effect.isReady() || !this._scene.activeCamera)
  81228. return false;
  81229. var engine = this._scene.getEngine();
  81230. var viewport = this._scene.activeCamera.viewport;
  81231. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81232. // Position
  81233. if (!this.computeEffectivePosition(globalViewport)) {
  81234. return false;
  81235. }
  81236. // Visibility
  81237. if (!this._isVisible()) {
  81238. return false;
  81239. }
  81240. // Intensity
  81241. var awayX;
  81242. var awayY;
  81243. if (this._positionX < this.borderLimit + globalViewport.x) {
  81244. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81245. }
  81246. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81247. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81248. }
  81249. else {
  81250. awayX = 0;
  81251. }
  81252. if (this._positionY < this.borderLimit + globalViewport.y) {
  81253. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81254. }
  81255. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81256. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81257. }
  81258. else {
  81259. awayY = 0;
  81260. }
  81261. var away = (awayX > awayY) ? awayX : awayY;
  81262. away -= this.viewportBorder;
  81263. if (away > this.borderLimit) {
  81264. away = this.borderLimit;
  81265. }
  81266. var intensity = 1.0 - (away / this.borderLimit);
  81267. if (intensity < 0) {
  81268. return false;
  81269. }
  81270. if (intensity > 1.0) {
  81271. intensity = 1.0;
  81272. }
  81273. if (this.viewportBorder > 0) {
  81274. globalViewport.x += this.viewportBorder;
  81275. globalViewport.y += this.viewportBorder;
  81276. globalViewport.width -= this.viewportBorder * 2;
  81277. globalViewport.height -= this.viewportBorder * 2;
  81278. this._positionX -= this.viewportBorder;
  81279. this._positionY -= this.viewportBorder;
  81280. }
  81281. // Position
  81282. var centerX = globalViewport.x + globalViewport.width / 2;
  81283. var centerY = globalViewport.y + globalViewport.height / 2;
  81284. var distX = centerX - this._positionX;
  81285. var distY = centerY - this._positionY;
  81286. // Effects
  81287. engine.enableEffect(this._effect);
  81288. engine.setState(false);
  81289. engine.setDepthBuffer(false);
  81290. // VBOs
  81291. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81292. // Flares
  81293. for (var index = 0; index < this.lensFlares.length; index++) {
  81294. var flare = this.lensFlares[index];
  81295. engine.setAlphaMode(flare.alphaMode);
  81296. var x = centerX - (distX * flare.position);
  81297. var y = centerY - (distY * flare.position);
  81298. var cw = flare.size;
  81299. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  81300. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  81301. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  81302. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  81303. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  81304. // Texture
  81305. this._effect.setTexture("textureSampler", flare.texture);
  81306. // Color
  81307. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  81308. // Draw order
  81309. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81310. }
  81311. engine.setDepthBuffer(true);
  81312. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81313. return true;
  81314. };
  81315. LensFlareSystem.prototype.dispose = function () {
  81316. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81317. if (vertexBuffer) {
  81318. vertexBuffer.dispose();
  81319. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81320. }
  81321. if (this._indexBuffer) {
  81322. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81323. this._indexBuffer = null;
  81324. }
  81325. while (this.lensFlares.length) {
  81326. this.lensFlares[0].dispose();
  81327. }
  81328. // Remove from scene
  81329. var index = this._scene.lensFlareSystems.indexOf(this);
  81330. this._scene.lensFlareSystems.splice(index, 1);
  81331. };
  81332. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  81333. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  81334. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  81335. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  81336. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  81337. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  81338. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  81339. var parsedFlare = parsedLensFlareSystem.flares[index];
  81340. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  81341. }
  81342. return lensFlareSystem;
  81343. };
  81344. LensFlareSystem.prototype.serialize = function () {
  81345. var serializationObject = {};
  81346. serializationObject.id = this.id;
  81347. serializationObject.name = this.name;
  81348. serializationObject.emitterId = this.getEmitter().id;
  81349. serializationObject.borderLimit = this.borderLimit;
  81350. serializationObject.flares = [];
  81351. for (var index = 0; index < this.lensFlares.length; index++) {
  81352. var flare = this.lensFlares[index];
  81353. serializationObject.flares.push({
  81354. size: flare.size,
  81355. position: flare.position,
  81356. color: flare.color.asArray(),
  81357. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81358. });
  81359. }
  81360. return serializationObject;
  81361. };
  81362. return LensFlareSystem;
  81363. }());
  81364. BABYLON.LensFlareSystem = LensFlareSystem;
  81365. })(BABYLON || (BABYLON = {}));
  81366. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81367. var BABYLON;
  81368. (function (BABYLON) {
  81369. /**
  81370. * This is a holder class for the physics joint created by the physics plugin.
  81371. * It holds a set of functions to control the underlying joint.
  81372. */
  81373. var PhysicsJoint = /** @class */ (function () {
  81374. function PhysicsJoint(type, jointData) {
  81375. this.type = type;
  81376. this.jointData = jointData;
  81377. jointData.nativeParams = jointData.nativeParams || {};
  81378. }
  81379. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81380. get: function () {
  81381. return this._physicsJoint;
  81382. },
  81383. set: function (newJoint) {
  81384. if (this._physicsJoint) {
  81385. //remove from the wolrd
  81386. }
  81387. this._physicsJoint = newJoint;
  81388. },
  81389. enumerable: true,
  81390. configurable: true
  81391. });
  81392. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  81393. set: function (physicsPlugin) {
  81394. this._physicsPlugin = physicsPlugin;
  81395. },
  81396. enumerable: true,
  81397. configurable: true
  81398. });
  81399. /**
  81400. * Execute a function that is physics-plugin specific.
  81401. * @param {Function} func the function that will be executed.
  81402. * It accepts two parameters: the physics world and the physics joint.
  81403. */
  81404. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  81405. func(this._physicsPlugin.world, this._physicsJoint);
  81406. };
  81407. //TODO check if the native joints are the same
  81408. //Joint Types
  81409. PhysicsJoint.DistanceJoint = 0;
  81410. PhysicsJoint.HingeJoint = 1;
  81411. PhysicsJoint.BallAndSocketJoint = 2;
  81412. PhysicsJoint.WheelJoint = 3;
  81413. PhysicsJoint.SliderJoint = 4;
  81414. //OIMO
  81415. PhysicsJoint.PrismaticJoint = 5;
  81416. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  81417. PhysicsJoint.UniversalJoint = 6;
  81418. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  81419. //Cannon
  81420. //Similar to a Ball-Joint. Different in params
  81421. PhysicsJoint.PointToPointJoint = 8;
  81422. //Cannon only at the moment
  81423. PhysicsJoint.SpringJoint = 9;
  81424. PhysicsJoint.LockJoint = 10;
  81425. return PhysicsJoint;
  81426. }());
  81427. BABYLON.PhysicsJoint = PhysicsJoint;
  81428. /**
  81429. * A class representing a physics distance joint.
  81430. */
  81431. var DistanceJoint = /** @class */ (function (_super) {
  81432. __extends(DistanceJoint, _super);
  81433. function DistanceJoint(jointData) {
  81434. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  81435. }
  81436. /**
  81437. * Update the predefined distance.
  81438. */
  81439. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  81440. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  81441. };
  81442. return DistanceJoint;
  81443. }(PhysicsJoint));
  81444. BABYLON.DistanceJoint = DistanceJoint;
  81445. var MotorEnabledJoint = /** @class */ (function (_super) {
  81446. __extends(MotorEnabledJoint, _super);
  81447. function MotorEnabledJoint(type, jointData) {
  81448. return _super.call(this, type, jointData) || this;
  81449. }
  81450. /**
  81451. * Set the motor values.
  81452. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81453. * @param {number} force the force to apply
  81454. * @param {number} maxForce max force for this motor.
  81455. */
  81456. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  81457. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81458. };
  81459. /**
  81460. * Set the motor's limits.
  81461. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81462. */
  81463. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81464. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81465. };
  81466. return MotorEnabledJoint;
  81467. }(PhysicsJoint));
  81468. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81469. /**
  81470. * This class represents a single hinge physics joint
  81471. */
  81472. var HingeJoint = /** @class */ (function (_super) {
  81473. __extends(HingeJoint, _super);
  81474. function HingeJoint(jointData) {
  81475. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81476. }
  81477. /**
  81478. * Set the motor values.
  81479. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81480. * @param {number} force the force to apply
  81481. * @param {number} maxForce max force for this motor.
  81482. */
  81483. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81484. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81485. };
  81486. /**
  81487. * Set the motor's limits.
  81488. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81489. */
  81490. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81491. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81492. };
  81493. return HingeJoint;
  81494. }(MotorEnabledJoint));
  81495. BABYLON.HingeJoint = HingeJoint;
  81496. /**
  81497. * This class represents a dual hinge physics joint (same as wheel joint)
  81498. */
  81499. var Hinge2Joint = /** @class */ (function (_super) {
  81500. __extends(Hinge2Joint, _super);
  81501. function Hinge2Joint(jointData) {
  81502. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81503. }
  81504. /**
  81505. * Set the motor values.
  81506. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81507. * @param {number} force the force to apply
  81508. * @param {number} maxForce max force for this motor.
  81509. * @param {motorIndex} the motor's index, 0 or 1.
  81510. */
  81511. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81512. if (motorIndex === void 0) { motorIndex = 0; }
  81513. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81514. };
  81515. /**
  81516. * Set the motor limits.
  81517. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81518. * @param {number} upperLimit the upper limit
  81519. * @param {number} lowerLimit lower limit
  81520. * @param {motorIndex} the motor's index, 0 or 1.
  81521. */
  81522. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81523. if (motorIndex === void 0) { motorIndex = 0; }
  81524. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81525. };
  81526. return Hinge2Joint;
  81527. }(MotorEnabledJoint));
  81528. BABYLON.Hinge2Joint = Hinge2Joint;
  81529. })(BABYLON || (BABYLON = {}));
  81530. //# sourceMappingURL=babylon.physicsJoint.js.map
  81531. var BABYLON;
  81532. (function (BABYLON) {
  81533. var PhysicsImpostor = /** @class */ (function () {
  81534. function PhysicsImpostor(object, type, _options, _scene) {
  81535. if (_options === void 0) { _options = { mass: 0 }; }
  81536. var _this = this;
  81537. this.object = object;
  81538. this.type = type;
  81539. this._options = _options;
  81540. this._scene = _scene;
  81541. this._bodyUpdateRequired = false;
  81542. this._onBeforePhysicsStepCallbacks = new Array();
  81543. this._onAfterPhysicsStepCallbacks = new Array();
  81544. this._onPhysicsCollideCallbacks = [];
  81545. this._deltaPosition = BABYLON.Vector3.Zero();
  81546. this._isDisposed = false;
  81547. //temp variables for parent rotation calculations
  81548. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81549. this._tmpQuat = new BABYLON.Quaternion();
  81550. this._tmpQuat2 = new BABYLON.Quaternion();
  81551. /**
  81552. * this function is executed by the physics engine.
  81553. */
  81554. this.beforeStep = function () {
  81555. if (!_this._physicsEngine) {
  81556. return;
  81557. }
  81558. _this.object.translate(_this._deltaPosition, -1);
  81559. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81560. _this.object.computeWorldMatrix(false);
  81561. if (_this.object.parent && _this.object.rotationQuaternion) {
  81562. _this.getParentsRotation();
  81563. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81564. }
  81565. else {
  81566. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81567. }
  81568. if (!_this._options.disableBidirectionalTransformation) {
  81569. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81570. }
  81571. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81572. func(_this);
  81573. });
  81574. };
  81575. /**
  81576. * this function is executed by the physics engine.
  81577. */
  81578. this.afterStep = function () {
  81579. if (!_this._physicsEngine) {
  81580. return;
  81581. }
  81582. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81583. func(_this);
  81584. });
  81585. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81586. // object has now its world rotation. needs to be converted to local.
  81587. if (_this.object.parent && _this.object.rotationQuaternion) {
  81588. _this.getParentsRotation();
  81589. _this._tmpQuat.conjugateInPlace();
  81590. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  81591. }
  81592. // take the position set and make it the absolute position of this object.
  81593. _this.object.setAbsolutePosition(_this.object.position);
  81594. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  81595. _this.object.translate(_this._deltaPosition, 1);
  81596. };
  81597. /**
  81598. * Legacy collision detection event support
  81599. */
  81600. this.onCollideEvent = null;
  81601. //event and body object due to cannon's event-based architecture.
  81602. this.onCollide = function (e) {
  81603. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  81604. return;
  81605. }
  81606. if (!_this._physicsEngine) {
  81607. return;
  81608. }
  81609. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  81610. if (otherImpostor) {
  81611. // Legacy collision detection event support
  81612. if (_this.onCollideEvent) {
  81613. _this.onCollideEvent(_this, otherImpostor);
  81614. }
  81615. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  81616. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  81617. }).forEach(function (obj) {
  81618. obj.callback(_this, otherImpostor);
  81619. });
  81620. }
  81621. };
  81622. //sanity check!
  81623. if (!this.object) {
  81624. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  81625. return;
  81626. }
  81627. //legacy support for old syntax.
  81628. if (!this._scene && object.getScene) {
  81629. this._scene = object.getScene();
  81630. }
  81631. if (!this._scene) {
  81632. return;
  81633. }
  81634. this._physicsEngine = this._scene.getPhysicsEngine();
  81635. if (!this._physicsEngine) {
  81636. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  81637. }
  81638. else {
  81639. //set the object's quaternion, if not set
  81640. if (!this.object.rotationQuaternion) {
  81641. if (this.object.rotation) {
  81642. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  81643. }
  81644. else {
  81645. this.object.rotationQuaternion = new BABYLON.Quaternion();
  81646. }
  81647. }
  81648. //default options params
  81649. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  81650. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  81651. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  81652. this._joints = [];
  81653. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  81654. if (!this.object.parent || this._options.ignoreParent) {
  81655. this._init();
  81656. }
  81657. else if (this.object.parent.physicsImpostor) {
  81658. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  81659. }
  81660. }
  81661. }
  81662. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  81663. get: function () {
  81664. return this._isDisposed;
  81665. },
  81666. enumerable: true,
  81667. configurable: true
  81668. });
  81669. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  81670. get: function () {
  81671. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  81672. },
  81673. set: function (value) {
  81674. this.setMass(value);
  81675. },
  81676. enumerable: true,
  81677. configurable: true
  81678. });
  81679. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  81680. get: function () {
  81681. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  81682. },
  81683. set: function (value) {
  81684. if (!this._physicsEngine) {
  81685. return;
  81686. }
  81687. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  81688. },
  81689. enumerable: true,
  81690. configurable: true
  81691. });
  81692. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  81693. get: function () {
  81694. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  81695. },
  81696. set: function (value) {
  81697. if (!this._physicsEngine) {
  81698. return;
  81699. }
  81700. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  81701. },
  81702. enumerable: true,
  81703. configurable: true
  81704. });
  81705. /**
  81706. * This function will completly initialize this impostor.
  81707. * It will create a new body - but only if this mesh has no parent.
  81708. * If it has, this impostor will not be used other than to define the impostor
  81709. * of the child mesh.
  81710. */
  81711. PhysicsImpostor.prototype._init = function () {
  81712. if (!this._physicsEngine) {
  81713. return;
  81714. }
  81715. this._physicsEngine.removeImpostor(this);
  81716. this.physicsBody = null;
  81717. this._parent = this._parent || this._getPhysicsParent();
  81718. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  81719. this._physicsEngine.addImpostor(this);
  81720. }
  81721. };
  81722. PhysicsImpostor.prototype._getPhysicsParent = function () {
  81723. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  81724. var parentMesh = this.object.parent;
  81725. return parentMesh.physicsImpostor;
  81726. }
  81727. return null;
  81728. };
  81729. /**
  81730. * Should a new body be generated.
  81731. */
  81732. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  81733. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  81734. };
  81735. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  81736. this.forceUpdate();
  81737. };
  81738. /**
  81739. * Force a regeneration of this or the parent's impostor's body.
  81740. * Use under cautious - This will remove all joints already implemented.
  81741. */
  81742. PhysicsImpostor.prototype.forceUpdate = function () {
  81743. this._init();
  81744. if (this.parent && !this._options.ignoreParent) {
  81745. this.parent.forceUpdate();
  81746. }
  81747. };
  81748. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  81749. /*public get mesh(): AbstractMesh {
  81750. return this._mesh;
  81751. }*/
  81752. /**
  81753. * Gets the body that holds this impostor. Either its own, or its parent.
  81754. */
  81755. get: function () {
  81756. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  81757. },
  81758. /**
  81759. * Set the physics body. Used mainly by the physics engine/plugin
  81760. */
  81761. set: function (physicsBody) {
  81762. if (this._physicsBody && this._physicsEngine) {
  81763. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  81764. }
  81765. this._physicsBody = physicsBody;
  81766. this.resetUpdateFlags();
  81767. },
  81768. enumerable: true,
  81769. configurable: true
  81770. });
  81771. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  81772. get: function () {
  81773. return !this._options.ignoreParent && this._parent ? this._parent : null;
  81774. },
  81775. set: function (value) {
  81776. this._parent = value;
  81777. },
  81778. enumerable: true,
  81779. configurable: true
  81780. });
  81781. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  81782. this._bodyUpdateRequired = false;
  81783. };
  81784. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  81785. if (this.object.getBoundingInfo) {
  81786. var q = this.object.rotationQuaternion;
  81787. //reset rotation
  81788. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  81789. //calculate the world matrix with no rotation
  81790. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81791. var boundingInfo = this.object.getBoundingInfo();
  81792. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  81793. //bring back the rotation
  81794. this.object.rotationQuaternion = q;
  81795. //calculate the world matrix with the new rotation
  81796. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81797. return size;
  81798. }
  81799. else {
  81800. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  81801. }
  81802. };
  81803. PhysicsImpostor.prototype.getObjectCenter = function () {
  81804. if (this.object.getBoundingInfo) {
  81805. var boundingInfo = this.object.getBoundingInfo();
  81806. return boundingInfo.boundingBox.centerWorld;
  81807. }
  81808. else {
  81809. return this.object.position;
  81810. }
  81811. };
  81812. /**
  81813. * Get a specific parametes from the options parameter.
  81814. */
  81815. PhysicsImpostor.prototype.getParam = function (paramName) {
  81816. return this._options[paramName];
  81817. };
  81818. /**
  81819. * Sets a specific parameter in the options given to the physics plugin
  81820. */
  81821. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  81822. this._options[paramName] = value;
  81823. this._bodyUpdateRequired = true;
  81824. };
  81825. /**
  81826. * Specifically change the body's mass option. Won't recreate the physics body object
  81827. */
  81828. PhysicsImpostor.prototype.setMass = function (mass) {
  81829. if (this.getParam("mass") !== mass) {
  81830. this.setParam("mass", mass);
  81831. }
  81832. if (this._physicsEngine) {
  81833. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  81834. }
  81835. };
  81836. PhysicsImpostor.prototype.getLinearVelocity = function () {
  81837. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  81838. };
  81839. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  81840. if (this._physicsEngine) {
  81841. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  81842. }
  81843. };
  81844. PhysicsImpostor.prototype.getAngularVelocity = function () {
  81845. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  81846. };
  81847. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  81848. if (this._physicsEngine) {
  81849. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  81850. }
  81851. };
  81852. /**
  81853. * Execute a function with the physics plugin native code.
  81854. * Provide a function the will have two variables - the world object and the physics body object.
  81855. */
  81856. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  81857. if (this._physicsEngine) {
  81858. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  81859. }
  81860. };
  81861. /**
  81862. * Register a function that will be executed before the physics world is stepping forward.
  81863. */
  81864. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  81865. this._onBeforePhysicsStepCallbacks.push(func);
  81866. };
  81867. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  81868. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  81869. if (index > -1) {
  81870. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  81871. }
  81872. else {
  81873. BABYLON.Tools.Warn("Function to remove was not found");
  81874. }
  81875. };
  81876. /**
  81877. * Register a function that will be executed after the physics step
  81878. */
  81879. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  81880. this._onAfterPhysicsStepCallbacks.push(func);
  81881. };
  81882. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  81883. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  81884. if (index > -1) {
  81885. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  81886. }
  81887. else {
  81888. BABYLON.Tools.Warn("Function to remove was not found");
  81889. }
  81890. };
  81891. /**
  81892. * register a function that will be executed when this impostor collides against a different body.
  81893. */
  81894. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  81895. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  81896. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  81897. };
  81898. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  81899. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  81900. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  81901. if (index > -1) {
  81902. this._onPhysicsCollideCallbacks.splice(index, 1);
  81903. }
  81904. else {
  81905. BABYLON.Tools.Warn("Function to remove was not found");
  81906. }
  81907. };
  81908. PhysicsImpostor.prototype.getParentsRotation = function () {
  81909. var parent = this.object.parent;
  81910. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  81911. while (parent) {
  81912. if (parent.rotationQuaternion) {
  81913. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  81914. }
  81915. else {
  81916. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  81917. }
  81918. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  81919. parent = parent.parent;
  81920. }
  81921. return this._tmpQuat;
  81922. };
  81923. /**
  81924. * Apply a force
  81925. */
  81926. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  81927. if (this._physicsEngine) {
  81928. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  81929. }
  81930. return this;
  81931. };
  81932. /**
  81933. * Apply an impulse
  81934. */
  81935. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  81936. if (this._physicsEngine) {
  81937. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  81938. }
  81939. return this;
  81940. };
  81941. /**
  81942. * A help function to create a joint.
  81943. */
  81944. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  81945. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  81946. this.addJoint(otherImpostor, joint);
  81947. return this;
  81948. };
  81949. /**
  81950. * Add a joint to this impostor with a different impostor.
  81951. */
  81952. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  81953. this._joints.push({
  81954. otherImpostor: otherImpostor,
  81955. joint: joint
  81956. });
  81957. if (this._physicsEngine) {
  81958. this._physicsEngine.addJoint(this, otherImpostor, joint);
  81959. }
  81960. return this;
  81961. };
  81962. /**
  81963. * Will keep this body still, in a sleep mode.
  81964. */
  81965. PhysicsImpostor.prototype.sleep = function () {
  81966. if (this._physicsEngine) {
  81967. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  81968. }
  81969. return this;
  81970. };
  81971. /**
  81972. * Wake the body up.
  81973. */
  81974. PhysicsImpostor.prototype.wakeUp = function () {
  81975. if (this._physicsEngine) {
  81976. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  81977. }
  81978. return this;
  81979. };
  81980. PhysicsImpostor.prototype.clone = function (newObject) {
  81981. if (!newObject)
  81982. return null;
  81983. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  81984. };
  81985. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  81986. var _this = this;
  81987. //no dispose if no physics engine is available.
  81988. if (!this._physicsEngine) {
  81989. return;
  81990. }
  81991. this._joints.forEach(function (j) {
  81992. if (_this._physicsEngine) {
  81993. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  81994. }
  81995. });
  81996. //dispose the physics body
  81997. this._physicsEngine.removeImpostor(this);
  81998. if (this.parent) {
  81999. this.parent.forceUpdate();
  82000. }
  82001. else {
  82002. /*this._object.getChildMeshes().forEach(function(mesh) {
  82003. if (mesh.physicsImpostor) {
  82004. if (disposeChildren) {
  82005. mesh.physicsImpostor.dispose();
  82006. mesh.physicsImpostor = null;
  82007. }
  82008. }
  82009. })*/
  82010. }
  82011. this._isDisposed = true;
  82012. };
  82013. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82014. this._deltaPosition.copyFrom(position);
  82015. };
  82016. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82017. if (!this._deltaRotation) {
  82018. this._deltaRotation = new BABYLON.Quaternion();
  82019. }
  82020. this._deltaRotation.copyFrom(rotation);
  82021. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82022. };
  82023. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82024. if (this._physicsEngine) {
  82025. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82026. }
  82027. return this;
  82028. };
  82029. PhysicsImpostor.prototype.getRadius = function () {
  82030. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82031. };
  82032. /**
  82033. * Sync a bone with this impostor
  82034. * @param bone The bone to sync to the impostor.
  82035. * @param boneMesh The mesh that the bone is influencing.
  82036. * @param jointPivot The pivot of the joint / bone in local space.
  82037. * @param distToJoint Optional distance from the impostor to the joint.
  82038. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82039. */
  82040. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82041. var tempVec = PhysicsImpostor._tmpVecs[0];
  82042. var mesh = this.object;
  82043. if (mesh.rotationQuaternion) {
  82044. if (adjustRotation) {
  82045. var tempQuat = PhysicsImpostor._tmpQuat;
  82046. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82047. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82048. }
  82049. else {
  82050. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82051. }
  82052. }
  82053. tempVec.x = 0;
  82054. tempVec.y = 0;
  82055. tempVec.z = 0;
  82056. if (jointPivot) {
  82057. tempVec.x = jointPivot.x;
  82058. tempVec.y = jointPivot.y;
  82059. tempVec.z = jointPivot.z;
  82060. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82061. if (distToJoint === undefined || distToJoint === null) {
  82062. distToJoint = jointPivot.length();
  82063. }
  82064. tempVec.x *= distToJoint;
  82065. tempVec.y *= distToJoint;
  82066. tempVec.z *= distToJoint;
  82067. }
  82068. if (bone.getParent()) {
  82069. tempVec.addInPlace(mesh.getAbsolutePosition());
  82070. bone.setAbsolutePosition(tempVec, boneMesh);
  82071. }
  82072. else {
  82073. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82074. boneMesh.position.x -= tempVec.x;
  82075. boneMesh.position.y -= tempVec.y;
  82076. boneMesh.position.z -= tempVec.z;
  82077. }
  82078. };
  82079. /**
  82080. * Sync impostor to a bone
  82081. * @param bone The bone that the impostor will be synced to.
  82082. * @param boneMesh The mesh that the bone is influencing.
  82083. * @param jointPivot The pivot of the joint / bone in local space.
  82084. * @param distToJoint Optional distance from the impostor to the joint.
  82085. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82086. * @param boneAxis Optional vector3 axis the bone is aligned with
  82087. */
  82088. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82089. var mesh = this.object;
  82090. if (mesh.rotationQuaternion) {
  82091. if (adjustRotation) {
  82092. var tempQuat = PhysicsImpostor._tmpQuat;
  82093. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82094. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82095. }
  82096. else {
  82097. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82098. }
  82099. }
  82100. var pos = PhysicsImpostor._tmpVecs[0];
  82101. var boneDir = PhysicsImpostor._tmpVecs[1];
  82102. if (!boneAxis) {
  82103. boneAxis = PhysicsImpostor._tmpVecs[2];
  82104. boneAxis.x = 0;
  82105. boneAxis.y = 1;
  82106. boneAxis.z = 0;
  82107. }
  82108. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82109. bone.getAbsolutePositionToRef(boneMesh, pos);
  82110. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82111. distToJoint = jointPivot.length();
  82112. }
  82113. if (distToJoint !== undefined && distToJoint !== null) {
  82114. pos.x += boneDir.x * distToJoint;
  82115. pos.y += boneDir.y * distToJoint;
  82116. pos.z += boneDir.z * distToJoint;
  82117. }
  82118. mesh.setAbsolutePosition(pos);
  82119. };
  82120. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82121. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82122. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82123. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82124. //Impostor types
  82125. PhysicsImpostor.NoImpostor = 0;
  82126. PhysicsImpostor.SphereImpostor = 1;
  82127. PhysicsImpostor.BoxImpostor = 2;
  82128. PhysicsImpostor.PlaneImpostor = 3;
  82129. PhysicsImpostor.MeshImpostor = 4;
  82130. PhysicsImpostor.CylinderImpostor = 7;
  82131. PhysicsImpostor.ParticleImpostor = 8;
  82132. PhysicsImpostor.HeightmapImpostor = 9;
  82133. return PhysicsImpostor;
  82134. }());
  82135. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82136. })(BABYLON || (BABYLON = {}));
  82137. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82138. var BABYLON;
  82139. (function (BABYLON) {
  82140. var PhysicsEngine = /** @class */ (function () {
  82141. function PhysicsEngine(gravity, _physicsPlugin) {
  82142. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82143. this._physicsPlugin = _physicsPlugin;
  82144. //new methods and parameters
  82145. this._impostors = [];
  82146. this._joints = [];
  82147. if (!this._physicsPlugin.isSupported()) {
  82148. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82149. + "Please make sure it is included.");
  82150. }
  82151. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82152. this.setGravity(gravity);
  82153. this.setTimeStep();
  82154. }
  82155. PhysicsEngine.prototype.setGravity = function (gravity) {
  82156. this.gravity = gravity;
  82157. this._physicsPlugin.setGravity(this.gravity);
  82158. };
  82159. /**
  82160. * Set the time step of the physics engine.
  82161. * default is 1/60.
  82162. * To slow it down, enter 1/600 for example.
  82163. * To speed it up, 1/30
  82164. * @param {number} newTimeStep the new timestep to apply to this world.
  82165. */
  82166. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82167. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82168. this._physicsPlugin.setTimeStep(newTimeStep);
  82169. };
  82170. /**
  82171. * Get the time step of the physics engine.
  82172. */
  82173. PhysicsEngine.prototype.getTimeStep = function () {
  82174. return this._physicsPlugin.getTimeStep();
  82175. };
  82176. PhysicsEngine.prototype.dispose = function () {
  82177. this._impostors.forEach(function (impostor) {
  82178. impostor.dispose();
  82179. });
  82180. this._physicsPlugin.dispose();
  82181. };
  82182. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82183. return this._physicsPlugin.name;
  82184. };
  82185. /**
  82186. * Adding a new impostor for the impostor tracking.
  82187. * This will be done by the impostor itself.
  82188. * @param {PhysicsImpostor} impostor the impostor to add
  82189. */
  82190. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82191. impostor.uniqueId = this._impostors.push(impostor);
  82192. //if no parent, generate the body
  82193. if (!impostor.parent) {
  82194. this._physicsPlugin.generatePhysicsBody(impostor);
  82195. }
  82196. };
  82197. /**
  82198. * Remove an impostor from the engine.
  82199. * This impostor and its mesh will not longer be updated by the physics engine.
  82200. * @param {PhysicsImpostor} impostor the impostor to remove
  82201. */
  82202. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82203. var index = this._impostors.indexOf(impostor);
  82204. if (index > -1) {
  82205. var removed = this._impostors.splice(index, 1);
  82206. //Is it needed?
  82207. if (removed.length) {
  82208. //this will also remove it from the world.
  82209. removed[0].physicsBody = null;
  82210. }
  82211. }
  82212. };
  82213. /**
  82214. * Add a joint to the physics engine
  82215. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82216. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82217. * @param {PhysicsJoint} the joint that will connect both impostors.
  82218. */
  82219. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82220. var impostorJoint = {
  82221. mainImpostor: mainImpostor,
  82222. connectedImpostor: connectedImpostor,
  82223. joint: joint
  82224. };
  82225. joint.physicsPlugin = this._physicsPlugin;
  82226. this._joints.push(impostorJoint);
  82227. this._physicsPlugin.generateJoint(impostorJoint);
  82228. };
  82229. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82230. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82231. return (impostorJoint.connectedImpostor === connectedImpostor
  82232. && impostorJoint.joint === joint
  82233. && impostorJoint.mainImpostor === mainImpostor);
  82234. });
  82235. if (matchingJoints.length) {
  82236. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82237. //TODO remove it from the list as well
  82238. }
  82239. };
  82240. /**
  82241. * Called by the scene. no need to call it.
  82242. */
  82243. PhysicsEngine.prototype._step = function (delta) {
  82244. var _this = this;
  82245. //check if any mesh has no body / requires an update
  82246. this._impostors.forEach(function (impostor) {
  82247. if (impostor.isBodyInitRequired()) {
  82248. _this._physicsPlugin.generatePhysicsBody(impostor);
  82249. }
  82250. });
  82251. if (delta > 0.1) {
  82252. delta = 0.1;
  82253. }
  82254. else if (delta <= 0) {
  82255. delta = 1.0 / 60.0;
  82256. }
  82257. this._physicsPlugin.executeStep(delta, this._impostors);
  82258. };
  82259. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  82260. return this._physicsPlugin;
  82261. };
  82262. PhysicsEngine.prototype.getImpostors = function () {
  82263. return this._impostors;
  82264. };
  82265. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  82266. for (var i = 0; i < this._impostors.length; ++i) {
  82267. if (this._impostors[i].object === object) {
  82268. return this._impostors[i];
  82269. }
  82270. }
  82271. return null;
  82272. };
  82273. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  82274. for (var i = 0; i < this._impostors.length; ++i) {
  82275. if (this._impostors[i].physicsBody === body) {
  82276. return this._impostors[i];
  82277. }
  82278. }
  82279. return null;
  82280. };
  82281. // Statics
  82282. PhysicsEngine.Epsilon = 0.001;
  82283. return PhysicsEngine;
  82284. }());
  82285. BABYLON.PhysicsEngine = PhysicsEngine;
  82286. })(BABYLON || (BABYLON = {}));
  82287. //# sourceMappingURL=babylon.physicsEngine.js.map
  82288. var BABYLON;
  82289. (function (BABYLON) {
  82290. var PhysicsHelper = /** @class */ (function () {
  82291. function PhysicsHelper(scene) {
  82292. this._scene = scene;
  82293. this._physicsEngine = this._scene.getPhysicsEngine();
  82294. if (!this._physicsEngine) {
  82295. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  82296. }
  82297. }
  82298. /**
  82299. * @param {Vector3} origin the origin of the explosion
  82300. * @param {number} radius the explosion radius
  82301. * @param {number} strength the explosion strength
  82302. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82303. */
  82304. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  82305. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82306. if (!this._physicsEngine) {
  82307. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  82308. return null;
  82309. }
  82310. var impostors = this._physicsEngine.getImpostors();
  82311. if (impostors.length === 0) {
  82312. return null;
  82313. }
  82314. var event = new PhysicsRadialExplosionEvent(this._scene);
  82315. impostors.forEach(function (impostor) {
  82316. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82317. if (!impostorForceAndContactPoint) {
  82318. return;
  82319. }
  82320. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82321. });
  82322. event.dispose(false);
  82323. return event;
  82324. };
  82325. /**
  82326. * @param {Vector3} origin the origin of the explosion
  82327. * @param {number} radius the explosion radius
  82328. * @param {number} strength the explosion strength
  82329. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82330. */
  82331. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  82332. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82333. if (!this._physicsEngine) {
  82334. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82335. return null;
  82336. }
  82337. var impostors = this._physicsEngine.getImpostors();
  82338. if (impostors.length === 0) {
  82339. return null;
  82340. }
  82341. var event = new PhysicsRadialExplosionEvent(this._scene);
  82342. impostors.forEach(function (impostor) {
  82343. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82344. if (!impostorForceAndContactPoint) {
  82345. return;
  82346. }
  82347. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82348. });
  82349. event.dispose(false);
  82350. return event;
  82351. };
  82352. /**
  82353. * @param {Vector3} origin the origin of the explosion
  82354. * @param {number} radius the explosion radius
  82355. * @param {number} strength the explosion strength
  82356. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82357. */
  82358. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82359. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82360. if (!this._physicsEngine) {
  82361. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82362. return null;
  82363. }
  82364. var impostors = this._physicsEngine.getImpostors();
  82365. if (impostors.length === 0) {
  82366. return null;
  82367. }
  82368. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82369. event.dispose(false);
  82370. return event;
  82371. };
  82372. /**
  82373. * @param {Vector3} origin the origin of the updraft
  82374. * @param {number} radius the radius of the updraft
  82375. * @param {number} strength the strength of the updraft
  82376. * @param {number} height the height of the updraft
  82377. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  82378. */
  82379. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  82380. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  82381. if (!this._physicsEngine) {
  82382. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82383. return null;
  82384. }
  82385. if (this._physicsEngine.getImpostors().length === 0) {
  82386. return null;
  82387. }
  82388. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  82389. event.dispose(false);
  82390. return event;
  82391. };
  82392. /**
  82393. * @param {Vector3} origin the of the vortex
  82394. * @param {number} radius the radius of the vortex
  82395. * @param {number} strength the strength of the vortex
  82396. * @param {number} height the height of the vortex
  82397. */
  82398. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  82399. if (!this._physicsEngine) {
  82400. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82401. return null;
  82402. }
  82403. if (this._physicsEngine.getImpostors().length === 0) {
  82404. return null;
  82405. }
  82406. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  82407. event.dispose(false);
  82408. return event;
  82409. };
  82410. return PhysicsHelper;
  82411. }());
  82412. BABYLON.PhysicsHelper = PhysicsHelper;
  82413. /***** Radial explosion *****/
  82414. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  82415. function PhysicsRadialExplosionEvent(scene) {
  82416. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  82417. this._rays = [];
  82418. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  82419. this._scene = scene;
  82420. }
  82421. /**
  82422. * Returns the data related to the radial explosion event (sphere & rays).
  82423. * @returns {PhysicsRadialExplosionEventData}
  82424. */
  82425. PhysicsRadialExplosionEvent.prototype.getData = function () {
  82426. this._dataFetched = true;
  82427. return {
  82428. sphere: this._sphere,
  82429. rays: this._rays,
  82430. };
  82431. };
  82432. /**
  82433. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  82434. * @param impostor
  82435. * @param {Vector3} origin the origin of the explosion
  82436. * @param {number} radius the explosion radius
  82437. * @param {number} strength the explosion strength
  82438. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  82439. * @returns {Nullable<PhysicsForceAndContactPoint>}
  82440. */
  82441. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  82442. if (impostor.mass === 0) {
  82443. return null;
  82444. }
  82445. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  82446. return null;
  82447. }
  82448. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82449. return null;
  82450. }
  82451. var impostorObjectCenter = impostor.getObjectCenter();
  82452. var direction = impostorObjectCenter.subtract(origin);
  82453. var ray = new BABYLON.Ray(origin, direction, radius);
  82454. this._rays.push(ray);
  82455. var hit = ray.intersectsMesh(impostor.object);
  82456. var contactPoint = hit.pickedPoint;
  82457. if (!contactPoint) {
  82458. return null;
  82459. }
  82460. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  82461. if (distanceFromOrigin > radius) {
  82462. return null;
  82463. }
  82464. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  82465. ? strength
  82466. : strength * (1 - (distanceFromOrigin / radius));
  82467. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82468. return { force: force, contactPoint: contactPoint };
  82469. };
  82470. /**
  82471. * Disposes the sphere.
  82472. * @param {bolean} force
  82473. */
  82474. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82475. var _this = this;
  82476. if (force === void 0) { force = true; }
  82477. if (force) {
  82478. this._sphere.dispose();
  82479. }
  82480. else {
  82481. setTimeout(function () {
  82482. if (!_this._dataFetched) {
  82483. _this._sphere.dispose();
  82484. }
  82485. }, 0);
  82486. }
  82487. };
  82488. /*** Helpers ***/
  82489. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82490. if (!this._sphere) {
  82491. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82492. this._sphere.isVisible = false;
  82493. }
  82494. };
  82495. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82496. var impostorObject = impostor.object;
  82497. this._prepareSphere();
  82498. this._sphere.position = origin;
  82499. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82500. this._sphere._updateBoundingInfo();
  82501. this._sphere.computeWorldMatrix(true);
  82502. return this._sphere.intersectsMesh(impostorObject, true);
  82503. };
  82504. return PhysicsRadialExplosionEvent;
  82505. }());
  82506. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82507. /***** Gravitational Field *****/
  82508. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82509. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82510. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82511. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82512. this._physicsHelper = physicsHelper;
  82513. this._scene = scene;
  82514. this._origin = origin;
  82515. this._radius = radius;
  82516. this._strength = strength;
  82517. this._falloff = falloff;
  82518. this._tickCallback = this._tick.bind(this);
  82519. }
  82520. /**
  82521. * Returns the data related to the gravitational field event (sphere).
  82522. * @returns {PhysicsGravitationalFieldEventData}
  82523. */
  82524. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82525. this._dataFetched = true;
  82526. return {
  82527. sphere: this._sphere,
  82528. };
  82529. };
  82530. /**
  82531. * Enables the gravitational field.
  82532. */
  82533. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82534. this._tickCallback.call(this);
  82535. this._scene.registerBeforeRender(this._tickCallback);
  82536. };
  82537. /**
  82538. * Disables the gravitational field.
  82539. */
  82540. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82541. this._scene.unregisterBeforeRender(this._tickCallback);
  82542. };
  82543. /**
  82544. * Disposes the sphere.
  82545. * @param {bolean} force
  82546. */
  82547. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82548. var _this = this;
  82549. if (force === void 0) { force = true; }
  82550. if (force) {
  82551. this._sphere.dispose();
  82552. }
  82553. else {
  82554. setTimeout(function () {
  82555. if (!_this._dataFetched) {
  82556. _this._sphere.dispose();
  82557. }
  82558. }, 0);
  82559. }
  82560. };
  82561. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82562. // Since the params won't change, we fetch the event only once
  82563. if (this._sphere) {
  82564. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82565. }
  82566. else {
  82567. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82568. if (radialExplosionEvent) {
  82569. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82570. }
  82571. }
  82572. };
  82573. return PhysicsGravitationalFieldEvent;
  82574. }());
  82575. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  82576. /***** Updraft *****/
  82577. var PhysicsUpdraftEvent = /** @class */ (function () {
  82578. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  82579. this._scene = _scene;
  82580. this._origin = _origin;
  82581. this._radius = _radius;
  82582. this._strength = _strength;
  82583. this._height = _height;
  82584. this._updraftMode = _updraftMode;
  82585. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82586. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  82587. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82588. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82589. this._physicsEngine = this._scene.getPhysicsEngine();
  82590. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82591. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82592. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82593. this._originDirection = this._origin.subtract(this._originTop).normalize();
  82594. }
  82595. this._tickCallback = this._tick.bind(this);
  82596. }
  82597. /**
  82598. * Returns the data related to the updraft event (cylinder).
  82599. * @returns {PhysicsUpdraftEventData}
  82600. */
  82601. PhysicsUpdraftEvent.prototype.getData = function () {
  82602. this._dataFetched = true;
  82603. return {
  82604. cylinder: this._cylinder,
  82605. };
  82606. };
  82607. /**
  82608. * Enables the updraft.
  82609. */
  82610. PhysicsUpdraftEvent.prototype.enable = function () {
  82611. this._tickCallback.call(this);
  82612. this._scene.registerBeforeRender(this._tickCallback);
  82613. };
  82614. /**
  82615. * Disables the cortex.
  82616. */
  82617. PhysicsUpdraftEvent.prototype.disable = function () {
  82618. this._scene.unregisterBeforeRender(this._tickCallback);
  82619. };
  82620. /**
  82621. * Disposes the sphere.
  82622. * @param {bolean} force
  82623. */
  82624. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  82625. var _this = this;
  82626. if (force === void 0) { force = true; }
  82627. if (force) {
  82628. this._cylinder.dispose();
  82629. }
  82630. else {
  82631. setTimeout(function () {
  82632. if (!_this._dataFetched) {
  82633. _this._cylinder.dispose();
  82634. }
  82635. }, 0);
  82636. }
  82637. };
  82638. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82639. if (impostor.mass === 0) {
  82640. return null;
  82641. }
  82642. if (!this._intersectsWithCylinder(impostor)) {
  82643. return null;
  82644. }
  82645. var impostorObjectCenter = impostor.getObjectCenter();
  82646. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82647. var direction = this._originDirection;
  82648. }
  82649. else {
  82650. var direction = impostorObjectCenter.subtract(this._originTop);
  82651. }
  82652. var multiplier = this._strength * -1;
  82653. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82654. return { force: force, contactPoint: impostorObjectCenter };
  82655. };
  82656. PhysicsUpdraftEvent.prototype._tick = function () {
  82657. var _this = this;
  82658. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82659. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82660. if (!impostorForceAndContactPoint) {
  82661. return;
  82662. }
  82663. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82664. });
  82665. };
  82666. /*** Helpers ***/
  82667. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  82668. if (!this._cylinder) {
  82669. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  82670. height: this._height,
  82671. diameter: this._radius * 2,
  82672. }, this._scene);
  82673. this._cylinder.isVisible = false;
  82674. }
  82675. };
  82676. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  82677. var impostorObject = impostor.object;
  82678. this._prepareCylinder();
  82679. this._cylinder.position = this._cylinderPosition;
  82680. return this._cylinder.intersectsMesh(impostorObject, true);
  82681. };
  82682. return PhysicsUpdraftEvent;
  82683. }());
  82684. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  82685. /***** Vortex *****/
  82686. var PhysicsVortexEvent = /** @class */ (function () {
  82687. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  82688. this._scene = _scene;
  82689. this._origin = _origin;
  82690. this._radius = _radius;
  82691. this._strength = _strength;
  82692. this._height = _height;
  82693. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82694. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  82695. this._updraftMultiplier = 0.02;
  82696. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82697. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82698. this._physicsEngine = this._scene.getPhysicsEngine();
  82699. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82700. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82701. this._tickCallback = this._tick.bind(this);
  82702. }
  82703. /**
  82704. * Returns the data related to the vortex event (cylinder).
  82705. * @returns {PhysicsVortexEventData}
  82706. */
  82707. PhysicsVortexEvent.prototype.getData = function () {
  82708. this._dataFetched = true;
  82709. return {
  82710. cylinder: this._cylinder,
  82711. };
  82712. };
  82713. /**
  82714. * Enables the vortex.
  82715. */
  82716. PhysicsVortexEvent.prototype.enable = function () {
  82717. this._tickCallback.call(this);
  82718. this._scene.registerBeforeRender(this._tickCallback);
  82719. };
  82720. /**
  82721. * Disables the cortex.
  82722. */
  82723. PhysicsVortexEvent.prototype.disable = function () {
  82724. this._scene.unregisterBeforeRender(this._tickCallback);
  82725. };
  82726. /**
  82727. * Disposes the sphere.
  82728. * @param {bolean} force
  82729. */
  82730. PhysicsVortexEvent.prototype.dispose = function (force) {
  82731. var _this = this;
  82732. if (force === void 0) { force = true; }
  82733. if (force) {
  82734. this._cylinder.dispose();
  82735. }
  82736. else {
  82737. setTimeout(function () {
  82738. if (!_this._dataFetched) {
  82739. _this._cylinder.dispose();
  82740. }
  82741. }, 0);
  82742. }
  82743. };
  82744. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82745. if (impostor.mass === 0) {
  82746. return null;
  82747. }
  82748. if (!this._intersectsWithCylinder(impostor)) {
  82749. return null;
  82750. }
  82751. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82752. return null;
  82753. }
  82754. var impostorObjectCenter = impostor.getObjectCenter();
  82755. 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)
  82756. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  82757. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  82758. var hit = ray.intersectsMesh(impostor.object);
  82759. var contactPoint = hit.pickedPoint;
  82760. if (!contactPoint) {
  82761. return null;
  82762. }
  82763. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  82764. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  82765. var directionToOrigin = contactPoint.normalize();
  82766. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82767. directionToOrigin = directionToOrigin.negate();
  82768. }
  82769. // TODO: find a more physically based solution
  82770. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82771. var forceX = directionToOrigin.x * this._strength / 8;
  82772. var forceY = directionToOrigin.y * this._updraftMultiplier;
  82773. var forceZ = directionToOrigin.z * this._strength / 8;
  82774. }
  82775. else {
  82776. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  82777. var forceY = this._originTop.y * this._updraftMultiplier;
  82778. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  82779. }
  82780. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  82781. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  82782. return { force: force, contactPoint: impostorObjectCenter };
  82783. };
  82784. PhysicsVortexEvent.prototype._tick = function () {
  82785. var _this = this;
  82786. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82787. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82788. if (!impostorForceAndContactPoint) {
  82789. return;
  82790. }
  82791. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82792. });
  82793. };
  82794. /*** Helpers ***/
  82795. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  82796. if (!this._cylinder) {
  82797. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  82798. height: this._height,
  82799. diameter: this._radius * 2,
  82800. }, this._scene);
  82801. this._cylinder.isVisible = false;
  82802. }
  82803. };
  82804. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  82805. var impostorObject = impostor.object;
  82806. this._prepareCylinder();
  82807. this._cylinder.position = this._cylinderPosition;
  82808. return this._cylinder.intersectsMesh(impostorObject, true);
  82809. };
  82810. return PhysicsVortexEvent;
  82811. }());
  82812. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  82813. /***** Enums *****/
  82814. /**
  82815. * The strenght of the force in correspondence to the distance of the affected object
  82816. */
  82817. var PhysicsRadialImpulseFalloff;
  82818. (function (PhysicsRadialImpulseFalloff) {
  82819. /** Defines that impulse is constant in strength across it's whole radius */
  82820. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  82821. /** DEfines that impulse gets weaker if it's further from the origin */
  82822. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  82823. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  82824. /**
  82825. * The strenght of the force in correspondence to the distance of the affected object
  82826. */
  82827. var PhysicsUpdraftMode;
  82828. (function (PhysicsUpdraftMode) {
  82829. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  82830. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  82831. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  82832. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  82833. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  82834. })(BABYLON || (BABYLON = {}));
  82835. //# sourceMappingURL=babylon.physicsHelper.js.map
  82836. var BABYLON;
  82837. (function (BABYLON) {
  82838. var CannonJSPlugin = /** @class */ (function () {
  82839. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  82840. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  82841. if (iterations === void 0) { iterations = 10; }
  82842. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  82843. this.name = "CannonJSPlugin";
  82844. this._physicsMaterials = new Array();
  82845. this._fixedTimeStep = 1 / 60;
  82846. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  82847. this.BJSCANNON = CANNON;
  82848. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  82849. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  82850. this._tmpPosition = BABYLON.Vector3.Zero();
  82851. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  82852. this._tmpUnityRotation = new BABYLON.Quaternion();
  82853. if (!this.isSupported()) {
  82854. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  82855. return;
  82856. }
  82857. this._extendNamespace();
  82858. this.world = new this.BJSCANNON.World();
  82859. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  82860. this.world.solver.iterations = iterations;
  82861. }
  82862. CannonJSPlugin.prototype.setGravity = function (gravity) {
  82863. this.world.gravity.copy(gravity);
  82864. };
  82865. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  82866. this._fixedTimeStep = timeStep;
  82867. };
  82868. CannonJSPlugin.prototype.getTimeStep = function () {
  82869. return this._fixedTimeStep;
  82870. };
  82871. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  82872. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  82873. };
  82874. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  82875. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82876. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82877. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  82878. };
  82879. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  82880. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  82881. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  82882. impostor.physicsBody.applyForce(impulse, worldPoint);
  82883. };
  82884. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  82885. //parent-child relationship. Does this impostor has a parent impostor?
  82886. if (impostor.parent) {
  82887. if (impostor.physicsBody) {
  82888. this.removePhysicsBody(impostor);
  82889. //TODO is that needed?
  82890. impostor.forceUpdate();
  82891. }
  82892. return;
  82893. }
  82894. //should a new body be created for this impostor?
  82895. if (impostor.isBodyInitRequired()) {
  82896. var shape = this._createShape(impostor);
  82897. //unregister events, if body is being changed
  82898. var oldBody = impostor.physicsBody;
  82899. if (oldBody) {
  82900. this.removePhysicsBody(impostor);
  82901. }
  82902. //create the body and material
  82903. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  82904. var bodyCreationObject = {
  82905. mass: impostor.getParam("mass"),
  82906. material: material
  82907. };
  82908. // A simple extend, in case native options were used.
  82909. var nativeOptions = impostor.getParam("nativeOptions");
  82910. for (var key in nativeOptions) {
  82911. if (nativeOptions.hasOwnProperty(key)) {
  82912. bodyCreationObject[key] = nativeOptions[key];
  82913. }
  82914. }
  82915. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  82916. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  82917. this.world.addEventListener("preStep", impostor.beforeStep);
  82918. this.world.addEventListener("postStep", impostor.afterStep);
  82919. impostor.physicsBody.addShape(shape);
  82920. this.world.add(impostor.physicsBody);
  82921. //try to keep the body moving in the right direction by taking old properties.
  82922. //Should be tested!
  82923. if (oldBody) {
  82924. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  82925. impostor.physicsBody[param].copy(oldBody[param]);
  82926. });
  82927. }
  82928. this._processChildMeshes(impostor);
  82929. }
  82930. //now update the body's transformation
  82931. this._updatePhysicsBodyTransformation(impostor);
  82932. };
  82933. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  82934. var _this = this;
  82935. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  82936. var currentRotation = mainImpostor.object.rotationQuaternion;
  82937. if (meshChildren.length) {
  82938. var processMesh = function (localPosition, mesh) {
  82939. if (!currentRotation || !mesh.rotationQuaternion) {
  82940. return;
  82941. }
  82942. var childImpostor = mesh.getPhysicsImpostor();
  82943. if (childImpostor) {
  82944. var parent = childImpostor.parent;
  82945. if (parent !== mainImpostor) {
  82946. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  82947. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  82948. if (childImpostor.physicsBody) {
  82949. _this.removePhysicsBody(childImpostor);
  82950. childImpostor.physicsBody = null;
  82951. }
  82952. childImpostor.parent = mainImpostor;
  82953. childImpostor.resetUpdateFlags();
  82954. 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));
  82955. //Add the mass of the children.
  82956. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  82957. }
  82958. }
  82959. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  82960. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  82961. };
  82962. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  82963. }
  82964. };
  82965. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  82966. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  82967. this.world.removeEventListener("preStep", impostor.beforeStep);
  82968. this.world.removeEventListener("postStep", impostor.afterStep);
  82969. this.world.remove(impostor.physicsBody);
  82970. };
  82971. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  82972. var mainBody = impostorJoint.mainImpostor.physicsBody;
  82973. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  82974. if (!mainBody || !connectedBody) {
  82975. return;
  82976. }
  82977. var constraint;
  82978. var jointData = impostorJoint.joint.jointData;
  82979. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  82980. var constraintData = {
  82981. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  82982. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  82983. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  82984. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  82985. maxForce: jointData.nativeParams.maxForce,
  82986. collideConnected: !!jointData.collision
  82987. };
  82988. switch (impostorJoint.joint.type) {
  82989. case BABYLON.PhysicsJoint.HingeJoint:
  82990. case BABYLON.PhysicsJoint.Hinge2Joint:
  82991. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  82992. break;
  82993. case BABYLON.PhysicsJoint.DistanceJoint:
  82994. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  82995. break;
  82996. case BABYLON.PhysicsJoint.SpringJoint:
  82997. var springData = jointData;
  82998. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  82999. restLength: springData.length,
  83000. stiffness: springData.stiffness,
  83001. damping: springData.damping,
  83002. localAnchorA: constraintData.pivotA,
  83003. localAnchorB: constraintData.pivotB
  83004. });
  83005. break;
  83006. case BABYLON.PhysicsJoint.LockJoint:
  83007. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83008. break;
  83009. case BABYLON.PhysicsJoint.PointToPointJoint:
  83010. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83011. default:
  83012. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83013. break;
  83014. }
  83015. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83016. constraint.collideConnected = !!jointData.collision;
  83017. impostorJoint.joint.physicsJoint = constraint;
  83018. //don't add spring as constraint, as it is not one.
  83019. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83020. this.world.addConstraint(constraint);
  83021. }
  83022. else {
  83023. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83024. constraint.applyForce();
  83025. });
  83026. }
  83027. };
  83028. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83029. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83030. };
  83031. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83032. var index;
  83033. var mat;
  83034. for (index = 0; index < this._physicsMaterials.length; index++) {
  83035. mat = this._physicsMaterials[index];
  83036. if (mat.friction === friction && mat.restitution === restitution) {
  83037. return mat;
  83038. }
  83039. }
  83040. var currentMat = new this.BJSCANNON.Material(name);
  83041. currentMat.friction = friction;
  83042. currentMat.restitution = restitution;
  83043. this._physicsMaterials.push(currentMat);
  83044. return currentMat;
  83045. };
  83046. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83047. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83048. };
  83049. CannonJSPlugin.prototype._createShape = function (impostor) {
  83050. var object = impostor.object;
  83051. var returnValue;
  83052. var extendSize = impostor.getObjectExtendSize();
  83053. switch (impostor.type) {
  83054. case BABYLON.PhysicsImpostor.SphereImpostor:
  83055. var radiusX = extendSize.x;
  83056. var radiusY = extendSize.y;
  83057. var radiusZ = extendSize.z;
  83058. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83059. break;
  83060. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83061. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83062. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83063. break;
  83064. case BABYLON.PhysicsImpostor.BoxImpostor:
  83065. var box = extendSize.scale(0.5);
  83066. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83067. break;
  83068. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83069. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83070. returnValue = new this.BJSCANNON.Plane();
  83071. break;
  83072. case BABYLON.PhysicsImpostor.MeshImpostor:
  83073. // should transform the vertex data to world coordinates!!
  83074. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83075. var rawFaces = object.getIndices ? object.getIndices() : [];
  83076. if (!rawVerts)
  83077. return;
  83078. // get only scale! so the object could transform correctly.
  83079. var oldPosition = object.position.clone();
  83080. var oldRotation = object.rotation && object.rotation.clone();
  83081. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83082. object.position.copyFromFloats(0, 0, 0);
  83083. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83084. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83085. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83086. var transform = object.computeWorldMatrix(true);
  83087. // convert rawVerts to object space
  83088. var temp = new Array();
  83089. var index;
  83090. for (index = 0; index < rawVerts.length; index += 3) {
  83091. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83092. }
  83093. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83094. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83095. //now set back the transformation!
  83096. object.position.copyFrom(oldPosition);
  83097. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83098. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83099. break;
  83100. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83101. var oldPosition2 = object.position.clone();
  83102. var oldRotation2 = object.rotation && object.rotation.clone();
  83103. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83104. object.position.copyFromFloats(0, 0, 0);
  83105. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83106. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83107. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83108. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83109. returnValue = this._createHeightmap(object);
  83110. object.position.copyFrom(oldPosition2);
  83111. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83112. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83113. object.computeWorldMatrix(true);
  83114. break;
  83115. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83116. returnValue = new this.BJSCANNON.Particle();
  83117. break;
  83118. }
  83119. return returnValue;
  83120. };
  83121. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83122. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83123. var transform = object.computeWorldMatrix(true);
  83124. // convert rawVerts to object space
  83125. var temp = new Array();
  83126. var index;
  83127. for (index = 0; index < pos.length; index += 3) {
  83128. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83129. }
  83130. pos = temp;
  83131. var matrix = new Array();
  83132. //For now pointDepth will not be used and will be automatically calculated.
  83133. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83134. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83135. var boundingInfo = object.getBoundingInfo();
  83136. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83137. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83138. var elementSize = dim * 2 / arraySize;
  83139. for (var i = 0; i < pos.length; i = i + 3) {
  83140. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83141. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83142. var y = -pos[i + 2] + minY;
  83143. if (!matrix[x]) {
  83144. matrix[x] = [];
  83145. }
  83146. if (!matrix[x][z]) {
  83147. matrix[x][z] = y;
  83148. }
  83149. matrix[x][z] = Math.max(y, matrix[x][z]);
  83150. }
  83151. for (var x = 0; x <= arraySize; ++x) {
  83152. if (!matrix[x]) {
  83153. var loc = 1;
  83154. while (!matrix[(x + loc) % arraySize]) {
  83155. loc++;
  83156. }
  83157. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83158. //console.log("missing x", x);
  83159. }
  83160. for (var z = 0; z <= arraySize; ++z) {
  83161. if (!matrix[x][z]) {
  83162. var loc = 1;
  83163. var newValue;
  83164. while (newValue === undefined) {
  83165. newValue = matrix[x][(z + loc++) % arraySize];
  83166. }
  83167. matrix[x][z] = newValue;
  83168. }
  83169. }
  83170. }
  83171. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83172. elementSize: elementSize
  83173. });
  83174. //For future reference, needed for body transformation
  83175. shape.minY = minY;
  83176. return shape;
  83177. };
  83178. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83179. var object = impostor.object;
  83180. //make sure it is updated...
  83181. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83182. // The delta between the mesh position and the mesh bounding box center
  83183. var bInfo = object.getBoundingInfo();
  83184. if (!bInfo)
  83185. return;
  83186. var center = impostor.getObjectCenter();
  83187. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83188. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83189. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83190. this._tmpPosition.copyFrom(center);
  83191. var quaternion = object.rotationQuaternion;
  83192. if (!quaternion) {
  83193. return;
  83194. }
  83195. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83196. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83197. //-90 DEG in X, precalculated
  83198. quaternion = quaternion.multiply(this._minus90X);
  83199. //Invert! (Precalculated, 90 deg in X)
  83200. //No need to clone. this will never change.
  83201. impostor.setDeltaRotation(this._plus90X);
  83202. }
  83203. //If it is a heightfield, if should be centered.
  83204. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83205. var mesh = object;
  83206. var boundingInfo = mesh.getBoundingInfo();
  83207. //calculate the correct body position:
  83208. var rotationQuaternion = mesh.rotationQuaternion;
  83209. mesh.rotationQuaternion = this._tmpUnityRotation;
  83210. mesh.computeWorldMatrix(true);
  83211. //get original center with no rotation
  83212. var c = center.clone();
  83213. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83214. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83215. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83216. mesh.setPreTransformMatrix(p);
  83217. mesh.computeWorldMatrix(true);
  83218. //calculate the translation
  83219. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83220. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83221. //add it inverted to the delta
  83222. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83223. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83224. //rotation is back
  83225. mesh.rotationQuaternion = rotationQuaternion;
  83226. mesh.setPreTransformMatrix(oldPivot);
  83227. mesh.computeWorldMatrix(true);
  83228. }
  83229. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83230. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83231. //this._tmpPosition.copyFrom(object.position);
  83232. }
  83233. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83234. //Now update the impostor object
  83235. impostor.physicsBody.position.copy(this._tmpPosition);
  83236. impostor.physicsBody.quaternion.copy(quaternion);
  83237. };
  83238. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83239. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83240. if (impostor.object.rotationQuaternion) {
  83241. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83242. }
  83243. };
  83244. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83245. impostor.physicsBody.position.copy(newPosition);
  83246. impostor.physicsBody.quaternion.copy(newRotation);
  83247. };
  83248. CannonJSPlugin.prototype.isSupported = function () {
  83249. return this.BJSCANNON !== undefined;
  83250. };
  83251. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83252. impostor.physicsBody.velocity.copy(velocity);
  83253. };
  83254. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83255. impostor.physicsBody.angularVelocity.copy(velocity);
  83256. };
  83257. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83258. var v = impostor.physicsBody.velocity;
  83259. if (!v) {
  83260. return null;
  83261. }
  83262. return new BABYLON.Vector3(v.x, v.y, v.z);
  83263. };
  83264. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83265. var v = impostor.physicsBody.angularVelocity;
  83266. if (!v) {
  83267. return null;
  83268. }
  83269. return new BABYLON.Vector3(v.x, v.y, v.z);
  83270. };
  83271. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83272. impostor.physicsBody.mass = mass;
  83273. impostor.physicsBody.updateMassProperties();
  83274. };
  83275. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  83276. return impostor.physicsBody.mass;
  83277. };
  83278. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  83279. return impostor.physicsBody.material.friction;
  83280. };
  83281. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83282. impostor.physicsBody.material.friction = friction;
  83283. };
  83284. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83285. return impostor.physicsBody.material.restitution;
  83286. };
  83287. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83288. impostor.physicsBody.material.restitution = restitution;
  83289. };
  83290. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  83291. impostor.physicsBody.sleep();
  83292. };
  83293. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  83294. impostor.physicsBody.wakeUp();
  83295. };
  83296. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83297. joint.physicsJoint.distance = maxDistance;
  83298. };
  83299. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83300. // if (!motorIndex) {
  83301. // joint.physicsJoint.enableMotor();
  83302. // }
  83303. // }
  83304. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83305. // if (!motorIndex) {
  83306. // joint.physicsJoint.disableMotor();
  83307. // }
  83308. // }
  83309. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83310. if (!motorIndex) {
  83311. joint.physicsJoint.enableMotor();
  83312. joint.physicsJoint.setMotorSpeed(speed);
  83313. if (maxForce) {
  83314. this.setLimit(joint, maxForce);
  83315. }
  83316. }
  83317. };
  83318. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  83319. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  83320. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  83321. };
  83322. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83323. var body = impostor.physicsBody;
  83324. mesh.position.x = body.position.x;
  83325. mesh.position.y = body.position.y;
  83326. mesh.position.z = body.position.z;
  83327. if (mesh.rotationQuaternion) {
  83328. mesh.rotationQuaternion.x = body.quaternion.x;
  83329. mesh.rotationQuaternion.y = body.quaternion.y;
  83330. mesh.rotationQuaternion.z = body.quaternion.z;
  83331. mesh.rotationQuaternion.w = body.quaternion.w;
  83332. }
  83333. };
  83334. CannonJSPlugin.prototype.getRadius = function (impostor) {
  83335. var shape = impostor.physicsBody.shapes[0];
  83336. return shape.boundingSphereRadius;
  83337. };
  83338. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83339. var shape = impostor.physicsBody.shapes[0];
  83340. result.x = shape.halfExtents.x * 2;
  83341. result.y = shape.halfExtents.y * 2;
  83342. result.z = shape.halfExtents.z * 2;
  83343. };
  83344. CannonJSPlugin.prototype.dispose = function () {
  83345. };
  83346. CannonJSPlugin.prototype._extendNamespace = function () {
  83347. //this will force cannon to execute at least one step when using interpolation
  83348. var step_tmp1 = new this.BJSCANNON.Vec3();
  83349. var Engine = this.BJSCANNON;
  83350. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83351. maxSubSteps = maxSubSteps || 10;
  83352. timeSinceLastCalled = timeSinceLastCalled || 0;
  83353. if (timeSinceLastCalled === 0) {
  83354. this.internalStep(dt);
  83355. this.time += dt;
  83356. }
  83357. else {
  83358. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83359. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83360. var t0 = performance.now();
  83361. for (var i = 0; i !== internalSteps; i++) {
  83362. this.internalStep(dt);
  83363. if (performance.now() - t0 > dt * 1000) {
  83364. break;
  83365. }
  83366. }
  83367. this.time += timeSinceLastCalled;
  83368. var h = this.time % dt;
  83369. var h_div_dt = h / dt;
  83370. var interpvelo = step_tmp1;
  83371. var bodies = this.bodies;
  83372. for (var j = 0; j !== bodies.length; j++) {
  83373. var b = bodies[j];
  83374. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  83375. b.position.vsub(b.previousPosition, interpvelo);
  83376. interpvelo.scale(h_div_dt, interpvelo);
  83377. b.position.vadd(interpvelo, b.interpolatedPosition);
  83378. }
  83379. else {
  83380. b.interpolatedPosition.copy(b.position);
  83381. b.interpolatedQuaternion.copy(b.quaternion);
  83382. }
  83383. }
  83384. }
  83385. };
  83386. };
  83387. return CannonJSPlugin;
  83388. }());
  83389. BABYLON.CannonJSPlugin = CannonJSPlugin;
  83390. })(BABYLON || (BABYLON = {}));
  83391. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  83392. var BABYLON;
  83393. (function (BABYLON) {
  83394. var OimoJSPlugin = /** @class */ (function () {
  83395. function OimoJSPlugin(iterations) {
  83396. this.name = "OimoJSPlugin";
  83397. this._tmpImpostorsArray = [];
  83398. this._tmpPositionVector = BABYLON.Vector3.Zero();
  83399. this.BJSOIMO = OIMO;
  83400. this.world = new this.BJSOIMO.World({
  83401. iterations: iterations
  83402. });
  83403. this.world.clear();
  83404. }
  83405. OimoJSPlugin.prototype.setGravity = function (gravity) {
  83406. this.world.gravity.copy(gravity);
  83407. };
  83408. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  83409. this.world.timeStep = timeStep;
  83410. };
  83411. OimoJSPlugin.prototype.getTimeStep = function () {
  83412. return this.world.timeStep;
  83413. };
  83414. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  83415. var _this = this;
  83416. impostors.forEach(function (impostor) {
  83417. impostor.beforeStep();
  83418. });
  83419. this.world.step();
  83420. impostors.forEach(function (impostor) {
  83421. impostor.afterStep();
  83422. //update the ordered impostors array
  83423. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  83424. });
  83425. //check for collisions
  83426. var contact = this.world.contacts;
  83427. while (contact !== null) {
  83428. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  83429. contact = contact.next;
  83430. continue;
  83431. }
  83432. //is this body colliding with any other? get the impostor
  83433. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  83434. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  83435. if (!mainImpostor || !collidingImpostor) {
  83436. contact = contact.next;
  83437. continue;
  83438. }
  83439. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  83440. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  83441. contact = contact.next;
  83442. }
  83443. };
  83444. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83445. var mass = impostor.physicsBody.mass;
  83446. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  83447. };
  83448. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83449. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  83450. this.applyImpulse(impostor, force, contactPoint);
  83451. };
  83452. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83453. var _this = this;
  83454. //parent-child relationship. Does this impostor has a parent impostor?
  83455. if (impostor.parent) {
  83456. if (impostor.physicsBody) {
  83457. this.removePhysicsBody(impostor);
  83458. //TODO is that needed?
  83459. impostor.forceUpdate();
  83460. }
  83461. return;
  83462. }
  83463. if (impostor.isBodyInitRequired()) {
  83464. var bodyConfig = {
  83465. name: impostor.uniqueId,
  83466. //Oimo must have mass, also for static objects.
  83467. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  83468. size: [],
  83469. type: [],
  83470. pos: [],
  83471. posShape: [],
  83472. rot: [],
  83473. rotShape: [],
  83474. move: impostor.getParam("mass") !== 0,
  83475. density: impostor.getParam("mass"),
  83476. friction: impostor.getParam("friction"),
  83477. restitution: impostor.getParam("restitution"),
  83478. //Supporting older versions of Oimo
  83479. world: this.world
  83480. };
  83481. var impostors = [impostor];
  83482. var addToArray = function (parent) {
  83483. if (!parent.getChildMeshes)
  83484. return;
  83485. parent.getChildMeshes().forEach(function (m) {
  83486. if (m.physicsImpostor) {
  83487. impostors.push(m.physicsImpostor);
  83488. //m.physicsImpostor._init();
  83489. }
  83490. });
  83491. };
  83492. addToArray(impostor.object);
  83493. var checkWithEpsilon_1 = function (value) {
  83494. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83495. };
  83496. impostors.forEach(function (i) {
  83497. if (!i.object.rotationQuaternion) {
  83498. return;
  83499. }
  83500. //get the correct bounding box
  83501. var oldQuaternion = i.object.rotationQuaternion;
  83502. var rot = oldQuaternion.toEulerAngles();
  83503. var extendSize = i.getObjectExtendSize();
  83504. var radToDeg = 57.295779513082320876;
  83505. if (i === impostor) {
  83506. var center = impostor.getObjectCenter();
  83507. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83508. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83509. //Can also use Array.prototype.push.apply
  83510. bodyConfig.pos.push(center.x);
  83511. bodyConfig.pos.push(center.y);
  83512. bodyConfig.pos.push(center.z);
  83513. bodyConfig.posShape.push(0, 0, 0);
  83514. //tmp solution
  83515. bodyConfig.rot.push(rot.x * radToDeg);
  83516. bodyConfig.rot.push(rot.y * radToDeg);
  83517. bodyConfig.rot.push(rot.z * radToDeg);
  83518. bodyConfig.rotShape.push(0, 0, 0);
  83519. }
  83520. else {
  83521. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83522. bodyConfig.posShape.push(localPosition.x);
  83523. bodyConfig.posShape.push(localPosition.y);
  83524. bodyConfig.posShape.push(localPosition.z);
  83525. bodyConfig.pos.push(0, 0, 0);
  83526. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83527. bodyConfig.rot.push(0);
  83528. bodyConfig.rot.push(0);
  83529. bodyConfig.rot.push(0);
  83530. bodyConfig.rotShape.push(rot.x * radToDeg);
  83531. bodyConfig.rotShape.push(rot.y * radToDeg);
  83532. bodyConfig.rotShape.push(rot.z * radToDeg);
  83533. }
  83534. // register mesh
  83535. switch (i.type) {
  83536. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83537. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83538. case BABYLON.PhysicsImpostor.SphereImpostor:
  83539. var radiusX = extendSize.x;
  83540. var radiusY = extendSize.y;
  83541. var radiusZ = extendSize.z;
  83542. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83543. bodyConfig.type.push('sphere');
  83544. //due to the way oimo works with compounds, add 3 times
  83545. bodyConfig.size.push(size);
  83546. bodyConfig.size.push(size);
  83547. bodyConfig.size.push(size);
  83548. break;
  83549. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83550. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83551. var sizeY = checkWithEpsilon_1(extendSize.y);
  83552. bodyConfig.type.push('cylinder');
  83553. bodyConfig.size.push(sizeX);
  83554. bodyConfig.size.push(sizeY);
  83555. //due to the way oimo works with compounds, add one more value.
  83556. bodyConfig.size.push(sizeY);
  83557. break;
  83558. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83559. case BABYLON.PhysicsImpostor.BoxImpostor:
  83560. default:
  83561. var sizeX = checkWithEpsilon_1(extendSize.x);
  83562. var sizeY = checkWithEpsilon_1(extendSize.y);
  83563. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83564. bodyConfig.type.push('box');
  83565. //if (i === impostor) {
  83566. bodyConfig.size.push(sizeX);
  83567. bodyConfig.size.push(sizeY);
  83568. bodyConfig.size.push(sizeZ);
  83569. //} else {
  83570. // bodyConfig.size.push(0,0,0);
  83571. //}
  83572. break;
  83573. }
  83574. //actually not needed, but hey...
  83575. i.object.rotationQuaternion = oldQuaternion;
  83576. });
  83577. impostor.physicsBody = this.world.add(bodyConfig);
  83578. }
  83579. else {
  83580. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  83581. }
  83582. impostor.setDeltaPosition(this._tmpPositionVector);
  83583. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  83584. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  83585. };
  83586. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83587. //impostor.physicsBody.dispose();
  83588. //Same as : (older oimo versions)
  83589. this.world.removeRigidBody(impostor.physicsBody);
  83590. };
  83591. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83592. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83593. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83594. if (!mainBody || !connectedBody) {
  83595. return;
  83596. }
  83597. var jointData = impostorJoint.joint.jointData;
  83598. var options = jointData.nativeParams || {};
  83599. var type;
  83600. var nativeJointData = {
  83601. body1: mainBody,
  83602. body2: connectedBody,
  83603. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  83604. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  83605. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  83606. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  83607. min: options.min,
  83608. max: options.max,
  83609. collision: options.collision || jointData.collision,
  83610. spring: options.spring,
  83611. //supporting older version of Oimo
  83612. world: this.world
  83613. };
  83614. switch (impostorJoint.joint.type) {
  83615. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83616. type = "jointBall";
  83617. break;
  83618. case BABYLON.PhysicsJoint.SpringJoint:
  83619. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  83620. var springData = jointData;
  83621. nativeJointData.min = springData.length || nativeJointData.min;
  83622. //Max should also be set, just make sure it is at least min
  83623. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  83624. case BABYLON.PhysicsJoint.DistanceJoint:
  83625. type = "jointDistance";
  83626. nativeJointData.max = jointData.maxDistance;
  83627. break;
  83628. case BABYLON.PhysicsJoint.PrismaticJoint:
  83629. type = "jointPrisme";
  83630. break;
  83631. case BABYLON.PhysicsJoint.SliderJoint:
  83632. type = "jointSlide";
  83633. break;
  83634. case BABYLON.PhysicsJoint.WheelJoint:
  83635. type = "jointWheel";
  83636. break;
  83637. case BABYLON.PhysicsJoint.HingeJoint:
  83638. default:
  83639. type = "jointHinge";
  83640. break;
  83641. }
  83642. nativeJointData.type = type;
  83643. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  83644. };
  83645. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83646. //Bug in Oimo prevents us from disposing a joint in the playground
  83647. //joint.joint.physicsJoint.dispose();
  83648. //So we will bruteforce it!
  83649. try {
  83650. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  83651. }
  83652. catch (e) {
  83653. BABYLON.Tools.Warn(e);
  83654. }
  83655. };
  83656. OimoJSPlugin.prototype.isSupported = function () {
  83657. return this.BJSOIMO !== undefined;
  83658. };
  83659. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83660. if (!impostor.physicsBody.sleeping) {
  83661. //TODO check that
  83662. /*if (impostor.physicsBody.shapes.next) {
  83663. var parentShape = this._getLastShape(impostor.physicsBody);
  83664. impostor.object.position.copyFrom(parentShape.position);
  83665. console.log(parentShape.position);
  83666. } else {*/
  83667. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  83668. //}
  83669. if (impostor.object.rotationQuaternion) {
  83670. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  83671. }
  83672. }
  83673. };
  83674. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83675. var body = impostor.physicsBody;
  83676. body.position.copy(newPosition);
  83677. body.orientation.copy(newRotation);
  83678. body.syncShapes();
  83679. body.awake();
  83680. };
  83681. /*private _getLastShape(body: any): any {
  83682. var lastShape = body.shapes;
  83683. while (lastShape.next) {
  83684. lastShape = lastShape.next;
  83685. }
  83686. return lastShape;
  83687. }*/
  83688. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83689. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  83690. };
  83691. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83692. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  83693. };
  83694. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83695. var v = impostor.physicsBody.linearVelocity;
  83696. if (!v) {
  83697. return null;
  83698. }
  83699. return new BABYLON.Vector3(v.x, v.y, v.z);
  83700. };
  83701. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83702. var v = impostor.physicsBody.angularVelocity;
  83703. if (!v) {
  83704. return null;
  83705. }
  83706. return new BABYLON.Vector3(v.x, v.y, v.z);
  83707. };
  83708. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83709. var staticBody = mass === 0;
  83710. //this will actually set the body's density and not its mass.
  83711. //But this is how oimo treats the mass variable.
  83712. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  83713. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  83714. };
  83715. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  83716. return impostor.physicsBody.shapes.density;
  83717. };
  83718. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  83719. return impostor.physicsBody.shapes.friction;
  83720. };
  83721. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83722. impostor.physicsBody.shapes.friction = friction;
  83723. };
  83724. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83725. return impostor.physicsBody.shapes.restitution;
  83726. };
  83727. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83728. impostor.physicsBody.shapes.restitution = restitution;
  83729. };
  83730. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  83731. impostor.physicsBody.sleep();
  83732. };
  83733. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  83734. impostor.physicsBody.awake();
  83735. };
  83736. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83737. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  83738. if (minDistance !== void 0) {
  83739. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  83740. }
  83741. };
  83742. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83743. //TODO separate rotational and transational motors.
  83744. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83745. if (motor) {
  83746. motor.setMotor(speed, maxForce);
  83747. }
  83748. };
  83749. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  83750. //TODO separate rotational and transational motors.
  83751. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83752. if (motor) {
  83753. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  83754. }
  83755. };
  83756. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83757. var body = impostor.physicsBody;
  83758. mesh.position.x = body.position.x;
  83759. mesh.position.y = body.position.y;
  83760. mesh.position.z = body.position.z;
  83761. if (mesh.rotationQuaternion) {
  83762. mesh.rotationQuaternion.x = body.orientation.x;
  83763. mesh.rotationQuaternion.y = body.orientation.y;
  83764. mesh.rotationQuaternion.z = body.orientation.z;
  83765. mesh.rotationQuaternion.w = body.orientation.s;
  83766. }
  83767. };
  83768. OimoJSPlugin.prototype.getRadius = function (impostor) {
  83769. return impostor.physicsBody.shapes.radius;
  83770. };
  83771. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83772. var shape = impostor.physicsBody.shapes;
  83773. result.x = shape.halfWidth * 2;
  83774. result.y = shape.halfHeight * 2;
  83775. result.z = shape.halfDepth * 2;
  83776. };
  83777. OimoJSPlugin.prototype.dispose = function () {
  83778. this.world.clear();
  83779. };
  83780. return OimoJSPlugin;
  83781. }());
  83782. BABYLON.OimoJSPlugin = OimoJSPlugin;
  83783. })(BABYLON || (BABYLON = {}));
  83784. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  83785. var BABYLON;
  83786. (function (BABYLON) {
  83787. /*
  83788. * Based on jsTGALoader - Javascript loader for TGA file
  83789. * By Vincent Thibault
  83790. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  83791. */
  83792. var TGATools = /** @class */ (function () {
  83793. function TGATools() {
  83794. }
  83795. TGATools.GetTGAHeader = function (data) {
  83796. var offset = 0;
  83797. var header = {
  83798. id_length: data[offset++],
  83799. colormap_type: data[offset++],
  83800. image_type: data[offset++],
  83801. colormap_index: data[offset++] | data[offset++] << 8,
  83802. colormap_length: data[offset++] | data[offset++] << 8,
  83803. colormap_size: data[offset++],
  83804. origin: [
  83805. data[offset++] | data[offset++] << 8,
  83806. data[offset++] | data[offset++] << 8
  83807. ],
  83808. width: data[offset++] | data[offset++] << 8,
  83809. height: data[offset++] | data[offset++] << 8,
  83810. pixel_size: data[offset++],
  83811. flags: data[offset++]
  83812. };
  83813. return header;
  83814. };
  83815. TGATools.UploadContent = function (gl, data) {
  83816. // Not enough data to contain header ?
  83817. if (data.length < 19) {
  83818. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  83819. return;
  83820. }
  83821. // Read Header
  83822. var offset = 18;
  83823. var header = TGATools.GetTGAHeader(data);
  83824. // Assume it's a valid Targa file.
  83825. if (header.id_length + offset > data.length) {
  83826. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  83827. return;
  83828. }
  83829. // Skip not needed data
  83830. offset += header.id_length;
  83831. var use_rle = false;
  83832. var use_pal = false;
  83833. var use_grey = false;
  83834. // Get some informations.
  83835. switch (header.image_type) {
  83836. case TGATools._TYPE_RLE_INDEXED:
  83837. use_rle = true;
  83838. case TGATools._TYPE_INDEXED:
  83839. use_pal = true;
  83840. break;
  83841. case TGATools._TYPE_RLE_RGB:
  83842. use_rle = true;
  83843. case TGATools._TYPE_RGB:
  83844. // use_rgb = true;
  83845. break;
  83846. case TGATools._TYPE_RLE_GREY:
  83847. use_rle = true;
  83848. case TGATools._TYPE_GREY:
  83849. use_grey = true;
  83850. break;
  83851. }
  83852. var pixel_data;
  83853. // var numAlphaBits = header.flags & 0xf;
  83854. var pixel_size = header.pixel_size >> 3;
  83855. var pixel_total = header.width * header.height * pixel_size;
  83856. // Read palettes
  83857. var palettes;
  83858. if (use_pal) {
  83859. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  83860. }
  83861. // Read LRE
  83862. if (use_rle) {
  83863. pixel_data = new Uint8Array(pixel_total);
  83864. var c, count, i;
  83865. var localOffset = 0;
  83866. var pixels = new Uint8Array(pixel_size);
  83867. while (offset < pixel_total && localOffset < pixel_total) {
  83868. c = data[offset++];
  83869. count = (c & 0x7f) + 1;
  83870. // RLE pixels
  83871. if (c & 0x80) {
  83872. // Bind pixel tmp array
  83873. for (i = 0; i < pixel_size; ++i) {
  83874. pixels[i] = data[offset++];
  83875. }
  83876. // Copy pixel array
  83877. for (i = 0; i < count; ++i) {
  83878. pixel_data.set(pixels, localOffset + i * pixel_size);
  83879. }
  83880. localOffset += pixel_size * count;
  83881. }
  83882. // Raw pixels
  83883. else {
  83884. count *= pixel_size;
  83885. for (i = 0; i < count; ++i) {
  83886. pixel_data[localOffset + i] = data[offset++];
  83887. }
  83888. localOffset += count;
  83889. }
  83890. }
  83891. }
  83892. // RAW Pixels
  83893. else {
  83894. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  83895. }
  83896. // Load to texture
  83897. var x_start, y_start, x_step, y_step, y_end, x_end;
  83898. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  83899. default:
  83900. case TGATools._ORIGIN_UL:
  83901. x_start = 0;
  83902. x_step = 1;
  83903. x_end = header.width;
  83904. y_start = 0;
  83905. y_step = 1;
  83906. y_end = header.height;
  83907. break;
  83908. case TGATools._ORIGIN_BL:
  83909. x_start = 0;
  83910. x_step = 1;
  83911. x_end = header.width;
  83912. y_start = header.height - 1;
  83913. y_step = -1;
  83914. y_end = -1;
  83915. break;
  83916. case TGATools._ORIGIN_UR:
  83917. x_start = header.width - 1;
  83918. x_step = -1;
  83919. x_end = -1;
  83920. y_start = 0;
  83921. y_step = 1;
  83922. y_end = header.height;
  83923. break;
  83924. case TGATools._ORIGIN_BR:
  83925. x_start = header.width - 1;
  83926. x_step = -1;
  83927. x_end = -1;
  83928. y_start = header.height - 1;
  83929. y_step = -1;
  83930. y_end = -1;
  83931. break;
  83932. }
  83933. // Load the specify method
  83934. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  83935. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  83936. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  83937. };
  83938. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83939. var image = pixel_data, colormap = palettes;
  83940. var width = header.width, height = header.height;
  83941. var color, i = 0, x, y;
  83942. var imageData = new Uint8Array(width * height * 4);
  83943. for (y = y_start; y !== y_end; y += y_step) {
  83944. for (x = x_start; x !== x_end; x += x_step, i++) {
  83945. color = image[i];
  83946. imageData[(x + width * y) * 4 + 3] = 255;
  83947. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  83948. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  83949. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  83950. }
  83951. }
  83952. return imageData;
  83953. };
  83954. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83955. var image = pixel_data;
  83956. var width = header.width, height = header.height;
  83957. var color, i = 0, x, y;
  83958. var imageData = new Uint8Array(width * height * 4);
  83959. for (y = y_start; y !== y_end; y += y_step) {
  83960. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  83961. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  83962. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  83963. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  83964. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  83965. imageData[(x + width * y) * 4 + 0] = r;
  83966. imageData[(x + width * y) * 4 + 1] = g;
  83967. imageData[(x + width * y) * 4 + 2] = b;
  83968. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  83969. }
  83970. }
  83971. return imageData;
  83972. };
  83973. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83974. var image = pixel_data;
  83975. var width = header.width, height = header.height;
  83976. var i = 0, x, y;
  83977. var imageData = new Uint8Array(width * height * 4);
  83978. for (y = y_start; y !== y_end; y += y_step) {
  83979. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  83980. imageData[(x + width * y) * 4 + 3] = 255;
  83981. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  83982. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  83983. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  83984. }
  83985. }
  83986. return imageData;
  83987. };
  83988. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  83989. var image = pixel_data;
  83990. var width = header.width, height = header.height;
  83991. var i = 0, x, y;
  83992. var imageData = new Uint8Array(width * height * 4);
  83993. for (y = y_start; y !== y_end; y += y_step) {
  83994. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  83995. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  83996. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  83997. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  83998. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  83999. }
  84000. }
  84001. return imageData;
  84002. };
  84003. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84004. var image = pixel_data;
  84005. var width = header.width, height = header.height;
  84006. var color, i = 0, x, y;
  84007. var imageData = new Uint8Array(width * height * 4);
  84008. for (y = y_start; y !== y_end; y += y_step) {
  84009. for (x = x_start; x !== x_end; x += x_step, i++) {
  84010. color = image[i];
  84011. imageData[(x + width * y) * 4 + 0] = color;
  84012. imageData[(x + width * y) * 4 + 1] = color;
  84013. imageData[(x + width * y) * 4 + 2] = color;
  84014. imageData[(x + width * y) * 4 + 3] = 255;
  84015. }
  84016. }
  84017. return imageData;
  84018. };
  84019. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84020. var image = pixel_data;
  84021. var width = header.width, height = header.height;
  84022. var i = 0, x, y;
  84023. var imageData = new Uint8Array(width * height * 4);
  84024. for (y = y_start; y !== y_end; y += y_step) {
  84025. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84026. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84027. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84028. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84029. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84030. }
  84031. }
  84032. return imageData;
  84033. };
  84034. //private static _TYPE_NO_DATA = 0;
  84035. TGATools._TYPE_INDEXED = 1;
  84036. TGATools._TYPE_RGB = 2;
  84037. TGATools._TYPE_GREY = 3;
  84038. TGATools._TYPE_RLE_INDEXED = 9;
  84039. TGATools._TYPE_RLE_RGB = 10;
  84040. TGATools._TYPE_RLE_GREY = 11;
  84041. TGATools._ORIGIN_MASK = 0x30;
  84042. TGATools._ORIGIN_SHIFT = 0x04;
  84043. TGATools._ORIGIN_BL = 0x00;
  84044. TGATools._ORIGIN_BR = 0x01;
  84045. TGATools._ORIGIN_UL = 0x02;
  84046. TGATools._ORIGIN_UR = 0x03;
  84047. return TGATools;
  84048. }());
  84049. BABYLON.TGATools = TGATools;
  84050. })(BABYLON || (BABYLON = {}));
  84051. //# sourceMappingURL=babylon.tga.js.map
  84052. var BABYLON;
  84053. (function (BABYLON) {
  84054. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84055. // All values and structures referenced from:
  84056. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84057. var DDS_MAGIC = 0x20534444;
  84058. var
  84059. //DDSD_CAPS = 0x1,
  84060. //DDSD_HEIGHT = 0x2,
  84061. //DDSD_WIDTH = 0x4,
  84062. //DDSD_PITCH = 0x8,
  84063. //DDSD_PIXELFORMAT = 0x1000,
  84064. DDSD_MIPMAPCOUNT = 0x20000;
  84065. //DDSD_LINEARSIZE = 0x80000,
  84066. //DDSD_DEPTH = 0x800000;
  84067. // var DDSCAPS_COMPLEX = 0x8,
  84068. // DDSCAPS_MIPMAP = 0x400000,
  84069. // DDSCAPS_TEXTURE = 0x1000;
  84070. var DDSCAPS2_CUBEMAP = 0x200;
  84071. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84072. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84073. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84074. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84075. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84076. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84077. // DDSCAPS2_VOLUME = 0x200000;
  84078. var
  84079. //DDPF_ALPHAPIXELS = 0x1,
  84080. //DDPF_ALPHA = 0x2,
  84081. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84082. //DDPF_YUV = 0x200,
  84083. DDPF_LUMINANCE = 0x20000;
  84084. function FourCCToInt32(value) {
  84085. return value.charCodeAt(0) +
  84086. (value.charCodeAt(1) << 8) +
  84087. (value.charCodeAt(2) << 16) +
  84088. (value.charCodeAt(3) << 24);
  84089. }
  84090. function Int32ToFourCC(value) {
  84091. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84092. }
  84093. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84094. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84095. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84096. var FOURCC_DX10 = FourCCToInt32("DX10");
  84097. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84098. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84099. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84100. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84101. var headerLengthInt = 31; // The header length in 32 bit ints
  84102. // Offsets into the header array
  84103. var off_magic = 0;
  84104. var off_size = 1;
  84105. var off_flags = 2;
  84106. var off_height = 3;
  84107. var off_width = 4;
  84108. var off_mipmapCount = 7;
  84109. var off_pfFlags = 20;
  84110. var off_pfFourCC = 21;
  84111. var off_RGBbpp = 22;
  84112. var off_RMask = 23;
  84113. var off_GMask = 24;
  84114. var off_BMask = 25;
  84115. var off_AMask = 26;
  84116. // var off_caps1 = 27;
  84117. var off_caps2 = 28;
  84118. // var off_caps3 = 29;
  84119. // var off_caps4 = 30;
  84120. var off_dxgiFormat = 32;
  84121. ;
  84122. var DDSTools = /** @class */ (function () {
  84123. function DDSTools() {
  84124. }
  84125. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84126. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84127. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84128. var mipmapCount = 1;
  84129. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84130. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84131. }
  84132. var fourCC = header[off_pfFourCC];
  84133. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84134. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84135. switch (fourCC) {
  84136. case FOURCC_D3DFMT_R16G16B16A16F:
  84137. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84138. break;
  84139. case FOURCC_D3DFMT_R32G32B32A32F:
  84140. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84141. break;
  84142. case FOURCC_DX10:
  84143. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84144. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84145. break;
  84146. }
  84147. }
  84148. return {
  84149. width: header[off_width],
  84150. height: header[off_height],
  84151. mipmapCount: mipmapCount,
  84152. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84153. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84154. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84155. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84156. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84157. dxgiFormat: dxgiFormat,
  84158. textureType: textureType
  84159. };
  84160. };
  84161. DDSTools._ToHalfFloat = function (value) {
  84162. if (!DDSTools._FloatView) {
  84163. DDSTools._FloatView = new Float32Array(1);
  84164. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84165. }
  84166. DDSTools._FloatView[0] = value;
  84167. var x = DDSTools._Int32View[0];
  84168. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84169. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84170. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84171. /* If zero, or denormal, or exponent underflows too much for a denormal
  84172. * half, return signed zero. */
  84173. if (e < 103) {
  84174. return bits;
  84175. }
  84176. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84177. if (e > 142) {
  84178. bits |= 0x7c00;
  84179. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84180. * not Inf, so make sure we set one mantissa bit too. */
  84181. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84182. return bits;
  84183. }
  84184. /* If exponent underflows but not too much, return a denormal */
  84185. if (e < 113) {
  84186. m |= 0x0800;
  84187. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84188. * to 1, which is OK. */
  84189. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84190. return bits;
  84191. }
  84192. bits |= ((e - 112) << 10) | (m >> 1);
  84193. bits += m & 1;
  84194. return bits;
  84195. };
  84196. DDSTools._FromHalfFloat = function (value) {
  84197. var s = (value & 0x8000) >> 15;
  84198. var e = (value & 0x7C00) >> 10;
  84199. var f = value & 0x03FF;
  84200. if (e === 0) {
  84201. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84202. }
  84203. else if (e == 0x1F) {
  84204. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84205. }
  84206. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84207. };
  84208. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84209. var destArray = new Float32Array(dataLength);
  84210. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84211. var index = 0;
  84212. for (var y = 0; y < height; y++) {
  84213. for (var x = 0; x < width; x++) {
  84214. var srcPos = (x + y * width) * 4;
  84215. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84216. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84217. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84218. if (DDSTools.StoreLODInAlphaChannel) {
  84219. destArray[index + 3] = lod;
  84220. }
  84221. else {
  84222. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84223. }
  84224. index += 4;
  84225. }
  84226. }
  84227. return destArray;
  84228. };
  84229. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84230. if (DDSTools.StoreLODInAlphaChannel) {
  84231. var destArray = new Uint16Array(dataLength);
  84232. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84233. var index = 0;
  84234. for (var y = 0; y < height; y++) {
  84235. for (var x = 0; x < width; x++) {
  84236. var srcPos = (x + y * width) * 4;
  84237. destArray[index] = srcData[srcPos];
  84238. destArray[index + 1] = srcData[srcPos + 1];
  84239. destArray[index + 2] = srcData[srcPos + 2];
  84240. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84241. index += 4;
  84242. }
  84243. }
  84244. return destArray;
  84245. }
  84246. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84247. };
  84248. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84249. if (DDSTools.StoreLODInAlphaChannel) {
  84250. var destArray = new Float32Array(dataLength);
  84251. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84252. var index = 0;
  84253. for (var y = 0; y < height; y++) {
  84254. for (var x = 0; x < width; x++) {
  84255. var srcPos = (x + y * width) * 4;
  84256. destArray[index] = srcData[srcPos];
  84257. destArray[index + 1] = srcData[srcPos + 1];
  84258. destArray[index + 2] = srcData[srcPos + 2];
  84259. destArray[index + 3] = lod;
  84260. index += 4;
  84261. }
  84262. }
  84263. return destArray;
  84264. }
  84265. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  84266. };
  84267. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84268. var destArray = new Uint8Array(dataLength);
  84269. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84270. var index = 0;
  84271. for (var y = 0; y < height; y++) {
  84272. for (var x = 0; x < width; x++) {
  84273. var srcPos = (x + y * width) * 4;
  84274. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  84275. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  84276. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  84277. if (DDSTools.StoreLODInAlphaChannel) {
  84278. destArray[index + 3] = lod;
  84279. }
  84280. else {
  84281. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  84282. }
  84283. index += 4;
  84284. }
  84285. }
  84286. return destArray;
  84287. };
  84288. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84289. var destArray = new Uint8Array(dataLength);
  84290. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84291. var index = 0;
  84292. for (var y = 0; y < height; y++) {
  84293. for (var x = 0; x < width; x++) {
  84294. var srcPos = (x + y * width) * 4;
  84295. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  84296. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  84297. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  84298. if (DDSTools.StoreLODInAlphaChannel) {
  84299. destArray[index + 3] = lod;
  84300. }
  84301. else {
  84302. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  84303. }
  84304. index += 4;
  84305. }
  84306. }
  84307. return destArray;
  84308. };
  84309. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  84310. var byteArray = new Uint8Array(dataLength);
  84311. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84312. var index = 0;
  84313. for (var y = 0; y < height; y++) {
  84314. for (var x = 0; x < width; x++) {
  84315. var srcPos = (x + y * width) * 4;
  84316. byteArray[index] = srcData[srcPos + rOffset];
  84317. byteArray[index + 1] = srcData[srcPos + gOffset];
  84318. byteArray[index + 2] = srcData[srcPos + bOffset];
  84319. byteArray[index + 3] = srcData[srcPos + aOffset];
  84320. index += 4;
  84321. }
  84322. }
  84323. return byteArray;
  84324. };
  84325. DDSTools._ExtractLongWordOrder = function (value) {
  84326. if (value === 0 || value === 255 || value === -16777216) {
  84327. return 0;
  84328. }
  84329. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  84330. };
  84331. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  84332. var byteArray = new Uint8Array(dataLength);
  84333. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84334. var index = 0;
  84335. for (var y = 0; y < height; y++) {
  84336. for (var x = 0; x < width; x++) {
  84337. var srcPos = (x + y * width) * 3;
  84338. byteArray[index] = srcData[srcPos + rOffset];
  84339. byteArray[index + 1] = srcData[srcPos + gOffset];
  84340. byteArray[index + 2] = srcData[srcPos + bOffset];
  84341. index += 3;
  84342. }
  84343. }
  84344. return byteArray;
  84345. };
  84346. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  84347. var byteArray = new Uint8Array(dataLength);
  84348. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84349. var index = 0;
  84350. for (var y = 0; y < height; y++) {
  84351. for (var x = 0; x < width; x++) {
  84352. var srcPos = (x + y * width);
  84353. byteArray[index] = srcData[srcPos];
  84354. index++;
  84355. }
  84356. }
  84357. return byteArray;
  84358. };
  84359. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84360. if (lodIndex === void 0) { lodIndex = -1; }
  84361. var sphericalPolynomialFaces = null;
  84362. if (info.sphericalPolynomial) {
  84363. sphericalPolynomialFaces = new Array();
  84364. }
  84365. var ext = engine.getCaps().s3tc;
  84366. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84367. var fourCC, width, height, dataLength = 0, dataOffset;
  84368. var byteArray, mipmapCount, mip;
  84369. var internalFormat = 0;
  84370. var format = 0;
  84371. var blockBytes = 1;
  84372. if (header[off_magic] !== DDS_MAGIC) {
  84373. BABYLON.Tools.Error("Invalid magic number in DDS header");
  84374. return;
  84375. }
  84376. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  84377. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  84378. return;
  84379. }
  84380. if (info.isCompressed && !ext) {
  84381. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  84382. return;
  84383. }
  84384. var bpp = header[off_RGBbpp];
  84385. dataOffset = header[off_size] + 4;
  84386. var computeFormats = false;
  84387. if (info.isFourCC) {
  84388. fourCC = header[off_pfFourCC];
  84389. switch (fourCC) {
  84390. case FOURCC_DXT1:
  84391. blockBytes = 8;
  84392. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  84393. break;
  84394. case FOURCC_DXT3:
  84395. blockBytes = 16;
  84396. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  84397. break;
  84398. case FOURCC_DXT5:
  84399. blockBytes = 16;
  84400. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  84401. break;
  84402. case FOURCC_D3DFMT_R16G16B16A16F:
  84403. computeFormats = true;
  84404. break;
  84405. case FOURCC_D3DFMT_R32G32B32A32F:
  84406. computeFormats = true;
  84407. break;
  84408. case FOURCC_DX10:
  84409. // There is an additionnal header so dataOffset need to be changed
  84410. dataOffset += 5 * 4; // 5 uints
  84411. var supported = false;
  84412. switch (info.dxgiFormat) {
  84413. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  84414. computeFormats = true;
  84415. supported = true;
  84416. break;
  84417. case DXGI_FORMAT_B8G8R8X8_UNORM:
  84418. info.isRGB = true;
  84419. info.isFourCC = false;
  84420. bpp = 32;
  84421. supported = true;
  84422. break;
  84423. }
  84424. if (supported) {
  84425. break;
  84426. }
  84427. default:
  84428. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  84429. return;
  84430. }
  84431. }
  84432. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  84433. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  84434. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  84435. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  84436. if (computeFormats) {
  84437. format = engine._getWebGLTextureType(info.textureType);
  84438. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84439. }
  84440. mipmapCount = 1;
  84441. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  84442. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84443. }
  84444. for (var face = 0; face < faces; face++) {
  84445. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  84446. width = header[off_width];
  84447. height = header[off_height];
  84448. for (mip = 0; mip < mipmapCount; ++mip) {
  84449. if (lodIndex === -1 || lodIndex === mip) {
  84450. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  84451. var i = (lodIndex === -1) ? mip : 0;
  84452. if (!info.isCompressed && info.isFourCC) {
  84453. dataLength = width * height * 4;
  84454. var floatArray = null;
  84455. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  84456. if (bpp === 128) {
  84457. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84458. if (sphericalPolynomialFaces && i == 0) {
  84459. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84460. }
  84461. }
  84462. else if (bpp === 64) {
  84463. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84464. if (sphericalPolynomialFaces && i == 0) {
  84465. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84466. }
  84467. }
  84468. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84469. format = engine._getWebGLTextureType(info.textureType);
  84470. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84471. }
  84472. else {
  84473. if (bpp === 128) {
  84474. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84475. if (sphericalPolynomialFaces && i == 0) {
  84476. sphericalPolynomialFaces.push(floatArray);
  84477. }
  84478. }
  84479. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  84480. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84481. if (sphericalPolynomialFaces && i == 0) {
  84482. sphericalPolynomialFaces.push(floatArray);
  84483. }
  84484. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84485. format = engine._getWebGLTextureType(info.textureType);
  84486. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84487. }
  84488. else { // 64
  84489. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84490. if (sphericalPolynomialFaces && i == 0) {
  84491. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84492. }
  84493. }
  84494. }
  84495. if (floatArray) {
  84496. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84497. }
  84498. }
  84499. else if (info.isRGB) {
  84500. if (bpp === 24) {
  84501. dataLength = width * height * 3;
  84502. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84503. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84504. }
  84505. else { // 32
  84506. dataLength = width * height * 4;
  84507. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84508. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84509. }
  84510. }
  84511. else if (info.isLuminance) {
  84512. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84513. var unpaddedRowSize = width;
  84514. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84515. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84516. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84517. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84518. }
  84519. else {
  84520. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84521. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84522. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84523. }
  84524. }
  84525. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84526. width *= 0.5;
  84527. height *= 0.5;
  84528. width = Math.max(1.0, width);
  84529. height = Math.max(1.0, height);
  84530. }
  84531. if (currentFace !== undefined) {
  84532. // Loading a single face
  84533. break;
  84534. }
  84535. }
  84536. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  84537. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  84538. size: header[off_width],
  84539. right: sphericalPolynomialFaces[0],
  84540. left: sphericalPolynomialFaces[1],
  84541. up: sphericalPolynomialFaces[2],
  84542. down: sphericalPolynomialFaces[3],
  84543. front: sphericalPolynomialFaces[4],
  84544. back: sphericalPolynomialFaces[5],
  84545. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  84546. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84547. gammaSpace: false,
  84548. });
  84549. }
  84550. else {
  84551. info.sphericalPolynomial = undefined;
  84552. }
  84553. };
  84554. DDSTools.StoreLODInAlphaChannel = false;
  84555. return DDSTools;
  84556. }());
  84557. BABYLON.DDSTools = DDSTools;
  84558. })(BABYLON || (BABYLON = {}));
  84559. //# sourceMappingURL=babylon.dds.js.map
  84560. var BABYLON;
  84561. (function (BABYLON) {
  84562. /**
  84563. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84564. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84565. */
  84566. var KhronosTextureContainer = /** @class */ (function () {
  84567. /**
  84568. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84569. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84570. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84571. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84572. */
  84573. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  84574. this.arrayBuffer = arrayBuffer;
  84575. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  84576. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  84577. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  84578. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  84579. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  84580. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  84581. BABYLON.Tools.Error("texture missing KTX identifier");
  84582. return;
  84583. }
  84584. // load the reset of the header in native 32 bit int
  84585. var header = new Int32Array(this.arrayBuffer, 12, 13);
  84586. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  84587. var oppositeEndianess = header[0] === 0x01020304;
  84588. // read all the header elements in order they exist in the file, without modification (sans endainness)
  84589. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  84590. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  84591. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  84592. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  84593. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  84594. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  84595. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  84596. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  84597. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  84598. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  84599. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  84600. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  84601. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  84602. if (this.glType !== 0) {
  84603. BABYLON.Tools.Error("only compressed formats currently supported");
  84604. return;
  84605. }
  84606. else {
  84607. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  84608. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  84609. }
  84610. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  84611. BABYLON.Tools.Error("only 2D textures currently supported");
  84612. return;
  84613. }
  84614. if (this.numberOfArrayElements !== 0) {
  84615. BABYLON.Tools.Error("texture arrays not currently supported");
  84616. return;
  84617. }
  84618. if (this.numberOfFaces !== facesExpected) {
  84619. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  84620. return;
  84621. }
  84622. // we now have a completely validated file, so could use existence of loadType as success
  84623. // would need to make this more elaborate & adjust checks above to support more than one load type
  84624. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  84625. }
  84626. // not as fast hardware based, but will probably never need to use
  84627. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  84628. return ((val & 0xFF) << 24)
  84629. | ((val & 0xFF00) << 8)
  84630. | ((val >> 8) & 0xFF00)
  84631. | ((val >> 24) & 0xFF);
  84632. };
  84633. /**
  84634. * It is assumed that the texture has already been created & is currently bound
  84635. */
  84636. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  84637. switch (this.loadType) {
  84638. case KhronosTextureContainer.COMPRESSED_2D:
  84639. this._upload2DCompressedLevels(gl, loadMipmaps);
  84640. break;
  84641. case KhronosTextureContainer.TEX_2D:
  84642. case KhronosTextureContainer.COMPRESSED_3D:
  84643. case KhronosTextureContainer.TEX_3D:
  84644. }
  84645. };
  84646. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  84647. // initialize width & height for level 1
  84648. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  84649. var width = this.pixelWidth;
  84650. var height = this.pixelHeight;
  84651. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  84652. for (var level = 0; level < mipmapCount; level++) {
  84653. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  84654. for (var face = 0; face < this.numberOfFaces; face++) {
  84655. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  84656. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  84657. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  84658. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  84659. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  84660. }
  84661. width = Math.max(1.0, width * 0.5);
  84662. height = Math.max(1.0, height * 0.5);
  84663. }
  84664. };
  84665. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  84666. // load types
  84667. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  84668. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  84669. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  84670. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  84671. return KhronosTextureContainer;
  84672. }());
  84673. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  84674. })(BABYLON || (BABYLON = {}));
  84675. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  84676. var BABYLON;
  84677. (function (BABYLON) {
  84678. var Debug;
  84679. (function (Debug) {
  84680. /**
  84681. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  84682. */
  84683. var SkeletonViewer = /** @class */ (function () {
  84684. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  84685. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  84686. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  84687. this.skeleton = skeleton;
  84688. this.mesh = mesh;
  84689. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  84690. this.renderingGroupId = renderingGroupId;
  84691. this.color = BABYLON.Color3.White();
  84692. this._debugLines = new Array();
  84693. this._isEnabled = false;
  84694. this._scene = scene;
  84695. this.update();
  84696. this._renderFunction = this.update.bind(this);
  84697. }
  84698. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  84699. get: function () {
  84700. return this._isEnabled;
  84701. },
  84702. set: function (value) {
  84703. if (this._isEnabled === value) {
  84704. return;
  84705. }
  84706. this._isEnabled = value;
  84707. if (value) {
  84708. this._scene.registerBeforeRender(this._renderFunction);
  84709. }
  84710. else {
  84711. this._scene.unregisterBeforeRender(this._renderFunction);
  84712. }
  84713. },
  84714. enumerable: true,
  84715. configurable: true
  84716. });
  84717. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  84718. if (x === void 0) { x = 0; }
  84719. if (y === void 0) { y = 0; }
  84720. if (z === void 0) { z = 0; }
  84721. var tmat = BABYLON.Tmp.Matrix[0];
  84722. var parentBone = bone.getParent();
  84723. tmat.copyFrom(bone.getLocalMatrix());
  84724. if (x !== 0 || y !== 0 || z !== 0) {
  84725. var tmat2 = BABYLON.Tmp.Matrix[1];
  84726. BABYLON.Matrix.IdentityToRef(tmat2);
  84727. tmat2.m[12] = x;
  84728. tmat2.m[13] = y;
  84729. tmat2.m[14] = z;
  84730. tmat2.multiplyToRef(tmat, tmat);
  84731. }
  84732. if (parentBone) {
  84733. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  84734. }
  84735. tmat.multiplyToRef(meshMat, tmat);
  84736. position.x = tmat.m[12];
  84737. position.y = tmat.m[13];
  84738. position.z = tmat.m[14];
  84739. };
  84740. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  84741. var len = bones.length;
  84742. var meshPos = this.mesh.position;
  84743. for (var i = 0; i < len; i++) {
  84744. var bone = bones[i];
  84745. var points = this._debugLines[i];
  84746. if (!points) {
  84747. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84748. this._debugLines[i] = points;
  84749. }
  84750. this._getBonePosition(points[0], bone, meshMat);
  84751. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  84752. points[0].subtractInPlace(meshPos);
  84753. points[1].subtractInPlace(meshPos);
  84754. }
  84755. };
  84756. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  84757. var len = bones.length;
  84758. var boneNum = 0;
  84759. var meshPos = this.mesh.position;
  84760. for (var i = len - 1; i >= 0; i--) {
  84761. var childBone = bones[i];
  84762. var parentBone = childBone.getParent();
  84763. if (!parentBone) {
  84764. continue;
  84765. }
  84766. var points = this._debugLines[boneNum];
  84767. if (!points) {
  84768. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84769. this._debugLines[boneNum] = points;
  84770. }
  84771. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  84772. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  84773. points[0].subtractInPlace(meshPos);
  84774. points[1].subtractInPlace(meshPos);
  84775. boneNum++;
  84776. }
  84777. };
  84778. SkeletonViewer.prototype.update = function () {
  84779. if (this.autoUpdateBonesMatrices) {
  84780. this.skeleton.computeAbsoluteTransforms();
  84781. }
  84782. if (this.skeleton.bones[0].length === undefined) {
  84783. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84784. }
  84785. else {
  84786. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84787. }
  84788. if (!this._debugMesh) {
  84789. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  84790. this._debugMesh.renderingGroupId = this.renderingGroupId;
  84791. }
  84792. else {
  84793. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  84794. }
  84795. this._debugMesh.position.copyFrom(this.mesh.position);
  84796. this._debugMesh.color = this.color;
  84797. };
  84798. SkeletonViewer.prototype.dispose = function () {
  84799. if (this._debugMesh) {
  84800. this.isEnabled = false;
  84801. this._debugMesh.dispose();
  84802. this._debugMesh = null;
  84803. }
  84804. };
  84805. return SkeletonViewer;
  84806. }());
  84807. Debug.SkeletonViewer = SkeletonViewer;
  84808. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84809. })(BABYLON || (BABYLON = {}));
  84810. //# sourceMappingURL=babylon.skeletonViewer.js.map
  84811. /**
  84812. * Module Debug contains the (visual) components to debug a scene correctly
  84813. */
  84814. var BABYLON;
  84815. (function (BABYLON) {
  84816. var Debug;
  84817. (function (Debug) {
  84818. /**
  84819. * The Axes viewer will show 3 axes in a specific point in space
  84820. */
  84821. var AxesViewer = /** @class */ (function () {
  84822. function AxesViewer(scene, scaleLines) {
  84823. if (scaleLines === void 0) { scaleLines = 1; }
  84824. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84825. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84826. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84827. this.scaleLines = 1;
  84828. this.scaleLines = scaleLines;
  84829. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  84830. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  84831. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  84832. this._xmesh.renderingGroupId = 2;
  84833. this._ymesh.renderingGroupId = 2;
  84834. this._zmesh.renderingGroupId = 2;
  84835. this._xmesh.material.checkReadyOnlyOnce = true;
  84836. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  84837. this._ymesh.material.checkReadyOnlyOnce = true;
  84838. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  84839. this._zmesh.material.checkReadyOnlyOnce = true;
  84840. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  84841. this.scene = scene;
  84842. }
  84843. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  84844. var scaleLines = this.scaleLines;
  84845. if (this._xmesh) {
  84846. this._xmesh.position.copyFrom(position);
  84847. }
  84848. if (this._ymesh) {
  84849. this._ymesh.position.copyFrom(position);
  84850. }
  84851. if (this._zmesh) {
  84852. this._zmesh.position.copyFrom(position);
  84853. }
  84854. var point2 = this._xline[1];
  84855. point2.x = xaxis.x * scaleLines;
  84856. point2.y = xaxis.y * scaleLines;
  84857. point2.z = xaxis.z * scaleLines;
  84858. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  84859. point2 = this._yline[1];
  84860. point2.x = yaxis.x * scaleLines;
  84861. point2.y = yaxis.y * scaleLines;
  84862. point2.z = yaxis.z * scaleLines;
  84863. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  84864. point2 = this._zline[1];
  84865. point2.x = zaxis.x * scaleLines;
  84866. point2.y = zaxis.y * scaleLines;
  84867. point2.z = zaxis.z * scaleLines;
  84868. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  84869. };
  84870. AxesViewer.prototype.dispose = function () {
  84871. if (this._xmesh) {
  84872. this._xmesh.dispose();
  84873. }
  84874. if (this._ymesh) {
  84875. this._ymesh.dispose();
  84876. }
  84877. if (this._zmesh) {
  84878. this._zmesh.dispose();
  84879. }
  84880. this._xmesh = null;
  84881. this._ymesh = null;
  84882. this._zmesh = null;
  84883. this.scene = null;
  84884. };
  84885. return AxesViewer;
  84886. }());
  84887. Debug.AxesViewer = AxesViewer;
  84888. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84889. })(BABYLON || (BABYLON = {}));
  84890. //# sourceMappingURL=babylon.axesViewer.js.map
  84891. var BABYLON;
  84892. (function (BABYLON) {
  84893. var Debug;
  84894. (function (Debug) {
  84895. /**
  84896. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  84897. */
  84898. var BoneAxesViewer = /** @class */ (function (_super) {
  84899. __extends(BoneAxesViewer, _super);
  84900. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  84901. if (scaleLines === void 0) { scaleLines = 1; }
  84902. var _this = _super.call(this, scene, scaleLines) || this;
  84903. _this.pos = BABYLON.Vector3.Zero();
  84904. _this.xaxis = BABYLON.Vector3.Zero();
  84905. _this.yaxis = BABYLON.Vector3.Zero();
  84906. _this.zaxis = BABYLON.Vector3.Zero();
  84907. _this.mesh = mesh;
  84908. _this.bone = bone;
  84909. return _this;
  84910. }
  84911. BoneAxesViewer.prototype.update = function () {
  84912. if (!this.mesh || !this.bone) {
  84913. return;
  84914. }
  84915. var bone = this.bone;
  84916. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  84917. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  84918. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  84919. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  84920. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  84921. };
  84922. BoneAxesViewer.prototype.dispose = function () {
  84923. if (this.mesh) {
  84924. this.mesh = null;
  84925. this.bone = null;
  84926. _super.prototype.dispose.call(this);
  84927. }
  84928. };
  84929. return BoneAxesViewer;
  84930. }(Debug.AxesViewer));
  84931. Debug.BoneAxesViewer = BoneAxesViewer;
  84932. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84933. })(BABYLON || (BABYLON = {}));
  84934. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  84935. var BABYLON;
  84936. (function (BABYLON) {
  84937. var RayHelper = /** @class */ (function () {
  84938. function RayHelper(ray) {
  84939. this.ray = ray;
  84940. }
  84941. RayHelper.CreateAndShow = function (ray, scene, color) {
  84942. var helper = new RayHelper(ray);
  84943. helper.show(scene, color);
  84944. return helper;
  84945. };
  84946. RayHelper.prototype.show = function (scene, color) {
  84947. if (!this._renderFunction && this.ray) {
  84948. var ray = this.ray;
  84949. this._renderFunction = this._render.bind(this);
  84950. this._scene = scene;
  84951. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  84952. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  84953. if (this._renderFunction) {
  84954. this._scene.registerBeforeRender(this._renderFunction);
  84955. }
  84956. }
  84957. if (color && this._renderLine) {
  84958. this._renderLine.color.copyFrom(color);
  84959. }
  84960. };
  84961. RayHelper.prototype.hide = function () {
  84962. if (this._renderFunction && this._scene) {
  84963. this._scene.unregisterBeforeRender(this._renderFunction);
  84964. this._scene = null;
  84965. this._renderFunction = null;
  84966. if (this._renderLine) {
  84967. this._renderLine.dispose();
  84968. this._renderLine = null;
  84969. }
  84970. this._renderPoints = [];
  84971. }
  84972. };
  84973. RayHelper.prototype._render = function () {
  84974. var ray = this.ray;
  84975. if (!ray) {
  84976. return;
  84977. }
  84978. var point = this._renderPoints[1];
  84979. var len = Math.min(ray.length, 1000000);
  84980. point.copyFrom(ray.direction);
  84981. point.scaleInPlace(len);
  84982. point.addInPlace(ray.origin);
  84983. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  84984. };
  84985. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  84986. this._attachedToMesh = mesh;
  84987. var ray = this.ray;
  84988. if (!ray) {
  84989. return;
  84990. }
  84991. if (!ray.direction) {
  84992. ray.direction = BABYLON.Vector3.Zero();
  84993. }
  84994. if (!ray.origin) {
  84995. ray.origin = BABYLON.Vector3.Zero();
  84996. }
  84997. if (length) {
  84998. ray.length = length;
  84999. }
  85000. if (!meshSpaceOrigin) {
  85001. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85002. }
  85003. if (!meshSpaceDirection) {
  85004. // -1 so that this will work with Mesh.lookAt
  85005. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85006. }
  85007. if (!this._meshSpaceDirection) {
  85008. this._meshSpaceDirection = meshSpaceDirection.clone();
  85009. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85010. }
  85011. else {
  85012. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85013. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85014. }
  85015. if (!this._updateToMeshFunction) {
  85016. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85017. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85018. }
  85019. this._updateToMesh();
  85020. };
  85021. RayHelper.prototype.detachFromMesh = function () {
  85022. if (this._attachedToMesh) {
  85023. if (this._updateToMeshFunction) {
  85024. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85025. }
  85026. this._attachedToMesh = null;
  85027. this._updateToMeshFunction = null;
  85028. }
  85029. };
  85030. RayHelper.prototype._updateToMesh = function () {
  85031. var ray = this.ray;
  85032. if (!this._attachedToMesh || !ray) {
  85033. return;
  85034. }
  85035. if (this._attachedToMesh._isDisposed) {
  85036. this.detachFromMesh();
  85037. return;
  85038. }
  85039. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85040. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85041. };
  85042. RayHelper.prototype.dispose = function () {
  85043. this.hide();
  85044. this.detachFromMesh();
  85045. this.ray = null;
  85046. };
  85047. return RayHelper;
  85048. }());
  85049. BABYLON.RayHelper = RayHelper;
  85050. })(BABYLON || (BABYLON = {}));
  85051. //# sourceMappingURL=babylon.rayHelper.js.map
  85052. var BABYLON;
  85053. (function (BABYLON) {
  85054. // load the inspector using require, if not present in the global namespace.
  85055. var DebugLayer = /** @class */ (function () {
  85056. function DebugLayer(scene) {
  85057. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85058. this._scene = scene;
  85059. // load inspector using require, if it doesn't exist on the global namespace.
  85060. }
  85061. /** Creates the inspector window. */
  85062. DebugLayer.prototype._createInspector = function (config) {
  85063. if (config === void 0) { config = {}; }
  85064. var popup = config.popup || false;
  85065. var initialTab = config.initialTab || 0;
  85066. var parentElement = config.parentElement || null;
  85067. if (!this._inspector) {
  85068. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85069. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85070. } // else nothing to do,; instance is already existing
  85071. };
  85072. DebugLayer.prototype.isVisible = function () {
  85073. if (!this._inspector) {
  85074. return false;
  85075. }
  85076. return true;
  85077. };
  85078. DebugLayer.prototype.hide = function () {
  85079. if (this._inspector) {
  85080. try {
  85081. this._inspector.dispose();
  85082. }
  85083. catch (e) {
  85084. // If the inspector has been removed directly from the inspector tool
  85085. }
  85086. this._inspector = null;
  85087. }
  85088. };
  85089. DebugLayer.prototype.show = function (config) {
  85090. if (config === void 0) { config = {}; }
  85091. if (typeof this.BJSINSPECTOR == 'undefined') {
  85092. // Load inspector and add it to the DOM
  85093. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85094. }
  85095. else {
  85096. // Otherwise creates the inspector
  85097. this._createInspector(config);
  85098. }
  85099. };
  85100. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85101. return DebugLayer;
  85102. }());
  85103. BABYLON.DebugLayer = DebugLayer;
  85104. })(BABYLON || (BABYLON = {}));
  85105. //# sourceMappingURL=babylon.debugLayer.js.map
  85106. var BABYLON;
  85107. (function (BABYLON) {
  85108. var Debug;
  85109. (function (Debug) {
  85110. /**
  85111. * Used to show the physics impostor around the specific mesh.
  85112. */
  85113. var PhysicsViewer = /** @class */ (function () {
  85114. function PhysicsViewer(scene) {
  85115. this._impostors = [];
  85116. this._meshes = [];
  85117. this._numMeshes = 0;
  85118. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85119. var physicEngine = this._scene.getPhysicsEngine();
  85120. if (physicEngine) {
  85121. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85122. }
  85123. }
  85124. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85125. var plugin = this._physicsEnginePlugin;
  85126. for (var i = 0; i < this._numMeshes; i++) {
  85127. var impostor = this._impostors[i];
  85128. if (!impostor) {
  85129. continue;
  85130. }
  85131. if (impostor.isDisposed) {
  85132. this.hideImpostor(this._impostors[i--]);
  85133. }
  85134. else {
  85135. var mesh = this._meshes[i];
  85136. if (mesh && plugin) {
  85137. plugin.syncMeshWithImpostor(mesh, impostor);
  85138. }
  85139. }
  85140. }
  85141. };
  85142. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85143. if (!this._scene) {
  85144. return;
  85145. }
  85146. for (var i = 0; i < this._numMeshes; i++) {
  85147. if (this._impostors[i] == impostor) {
  85148. return;
  85149. }
  85150. }
  85151. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85152. if (debugMesh) {
  85153. this._impostors[this._numMeshes] = impostor;
  85154. this._meshes[this._numMeshes] = debugMesh;
  85155. if (this._numMeshes === 0) {
  85156. this._renderFunction = this._updateDebugMeshes.bind(this);
  85157. this._scene.registerBeforeRender(this._renderFunction);
  85158. }
  85159. this._numMeshes++;
  85160. }
  85161. };
  85162. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85163. if (!impostor || !this._scene) {
  85164. return;
  85165. }
  85166. var removed = false;
  85167. for (var i = 0; i < this._numMeshes; i++) {
  85168. if (this._impostors[i] == impostor) {
  85169. var mesh = this._meshes[i];
  85170. if (!mesh) {
  85171. continue;
  85172. }
  85173. this._scene.removeMesh(mesh);
  85174. mesh.dispose();
  85175. this._numMeshes--;
  85176. if (this._numMeshes > 0) {
  85177. this._meshes[i] = this._meshes[this._numMeshes];
  85178. this._impostors[i] = this._impostors[this._numMeshes];
  85179. this._meshes[this._numMeshes] = null;
  85180. this._impostors[this._numMeshes] = null;
  85181. }
  85182. else {
  85183. this._meshes[0] = null;
  85184. this._impostors[0] = null;
  85185. }
  85186. removed = true;
  85187. break;
  85188. }
  85189. }
  85190. if (removed && this._numMeshes === 0) {
  85191. this._scene.unregisterBeforeRender(this._renderFunction);
  85192. }
  85193. };
  85194. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85195. if (!this._debugMaterial) {
  85196. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85197. this._debugMaterial.wireframe = true;
  85198. }
  85199. return this._debugMaterial;
  85200. };
  85201. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85202. if (!this._debugBoxMesh) {
  85203. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85204. this._debugBoxMesh.renderingGroupId = 1;
  85205. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85206. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85207. scene.removeMesh(this._debugBoxMesh);
  85208. }
  85209. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85210. };
  85211. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  85212. if (!this._debugSphereMesh) {
  85213. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  85214. this._debugSphereMesh.renderingGroupId = 1;
  85215. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85216. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  85217. scene.removeMesh(this._debugSphereMesh);
  85218. }
  85219. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  85220. };
  85221. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  85222. var mesh = null;
  85223. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  85224. mesh = this._getDebugBoxMesh(scene);
  85225. impostor.getBoxSizeToRef(mesh.scaling);
  85226. }
  85227. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  85228. mesh = this._getDebugSphereMesh(scene);
  85229. var radius = impostor.getRadius();
  85230. mesh.scaling.x = radius * 2;
  85231. mesh.scaling.y = radius * 2;
  85232. mesh.scaling.z = radius * 2;
  85233. }
  85234. return mesh;
  85235. };
  85236. PhysicsViewer.prototype.dispose = function () {
  85237. for (var i = 0; i < this._numMeshes; i++) {
  85238. this.hideImpostor(this._impostors[i]);
  85239. }
  85240. if (this._debugBoxMesh) {
  85241. this._debugBoxMesh.dispose();
  85242. }
  85243. if (this._debugSphereMesh) {
  85244. this._debugSphereMesh.dispose();
  85245. }
  85246. if (this._debugMaterial) {
  85247. this._debugMaterial.dispose();
  85248. }
  85249. this._impostors.length = 0;
  85250. this._scene = null;
  85251. this._physicsEnginePlugin = null;
  85252. };
  85253. return PhysicsViewer;
  85254. }());
  85255. Debug.PhysicsViewer = PhysicsViewer;
  85256. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85257. })(BABYLON || (BABYLON = {}));
  85258. //# sourceMappingURL=babylon.physicsViewer.js.map
  85259. var BABYLON;
  85260. (function (BABYLON) {
  85261. var BoundingBoxRenderer = /** @class */ (function () {
  85262. function BoundingBoxRenderer(scene) {
  85263. this.frontColor = new BABYLON.Color3(1, 1, 1);
  85264. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  85265. this.showBackLines = true;
  85266. this.renderList = new BABYLON.SmartArray(32);
  85267. this._vertexBuffers = {};
  85268. this._scene = scene;
  85269. }
  85270. BoundingBoxRenderer.prototype._prepareRessources = function () {
  85271. if (this._colorShader) {
  85272. return;
  85273. }
  85274. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  85275. attributes: [BABYLON.VertexBuffer.PositionKind],
  85276. uniforms: ["world", "viewProjection", "color"]
  85277. });
  85278. var engine = this._scene.getEngine();
  85279. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  85280. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  85281. this._createIndexBuffer();
  85282. };
  85283. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  85284. var engine = this._scene.getEngine();
  85285. 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]);
  85286. };
  85287. BoundingBoxRenderer.prototype._rebuild = function () {
  85288. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85289. if (vb) {
  85290. vb._rebuild();
  85291. }
  85292. this._createIndexBuffer();
  85293. };
  85294. BoundingBoxRenderer.prototype.reset = function () {
  85295. this.renderList.reset();
  85296. };
  85297. BoundingBoxRenderer.prototype.render = function () {
  85298. if (this.renderList.length === 0) {
  85299. return;
  85300. }
  85301. this._prepareRessources();
  85302. if (!this._colorShader.isReady()) {
  85303. return;
  85304. }
  85305. var engine = this._scene.getEngine();
  85306. engine.setDepthWrite(false);
  85307. this._colorShader._preBind();
  85308. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  85309. var boundingBox = this.renderList.data[boundingBoxIndex];
  85310. var min = boundingBox.minimum;
  85311. var max = boundingBox.maximum;
  85312. var diff = max.subtract(min);
  85313. var median = min.add(diff.scale(0.5));
  85314. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85315. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85316. .multiply(boundingBox.getWorldMatrix());
  85317. // VBOs
  85318. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85319. if (this.showBackLines) {
  85320. // Back
  85321. engine.setDepthFunctionToGreaterOrEqual();
  85322. this._scene.resetCachedMaterial();
  85323. this._colorShader.setColor4("color", this.backColor.toColor4());
  85324. this._colorShader.bind(worldMatrix);
  85325. // Draw order
  85326. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85327. }
  85328. // Front
  85329. engine.setDepthFunctionToLess();
  85330. this._scene.resetCachedMaterial();
  85331. this._colorShader.setColor4("color", this.frontColor.toColor4());
  85332. this._colorShader.bind(worldMatrix);
  85333. // Draw order
  85334. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85335. }
  85336. this._colorShader.unbind();
  85337. engine.setDepthFunctionToLessOrEqual();
  85338. engine.setDepthWrite(true);
  85339. };
  85340. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  85341. this._prepareRessources();
  85342. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  85343. return;
  85344. }
  85345. var engine = this._scene.getEngine();
  85346. engine.setDepthWrite(false);
  85347. engine.setColorWrite(false);
  85348. this._colorShader._preBind();
  85349. var boundingBox = mesh._boundingInfo.boundingBox;
  85350. var min = boundingBox.minimum;
  85351. var max = boundingBox.maximum;
  85352. var diff = max.subtract(min);
  85353. var median = min.add(diff.scale(0.5));
  85354. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85355. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85356. .multiply(boundingBox.getWorldMatrix());
  85357. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85358. engine.setDepthFunctionToLess();
  85359. this._scene.resetCachedMaterial();
  85360. this._colorShader.bind(worldMatrix);
  85361. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85362. this._colorShader.unbind();
  85363. engine.setDepthFunctionToLessOrEqual();
  85364. engine.setDepthWrite(true);
  85365. engine.setColorWrite(true);
  85366. };
  85367. BoundingBoxRenderer.prototype.dispose = function () {
  85368. if (!this._colorShader) {
  85369. return;
  85370. }
  85371. this.renderList.dispose();
  85372. this._colorShader.dispose();
  85373. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85374. if (buffer) {
  85375. buffer.dispose();
  85376. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85377. }
  85378. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85379. };
  85380. return BoundingBoxRenderer;
  85381. }());
  85382. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  85383. })(BABYLON || (BABYLON = {}));
  85384. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  85385. var BABYLON;
  85386. (function (BABYLON) {
  85387. /**
  85388. * Defines a target to use with MorphTargetManager
  85389. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85390. */
  85391. var MorphTarget = /** @class */ (function () {
  85392. /**
  85393. * Creates a new MorphTarget
  85394. * @param name defines the name of the target
  85395. * @param influence defines the influence to use
  85396. */
  85397. function MorphTarget(
  85398. /** defines the name of the target */
  85399. name, influence) {
  85400. if (influence === void 0) { influence = 0; }
  85401. this.name = name;
  85402. /**
  85403. * Gets or sets the list of animations
  85404. */
  85405. this.animations = new Array();
  85406. this._positions = null;
  85407. this._normals = null;
  85408. this._tangents = null;
  85409. /**
  85410. * Observable raised when the influence changes
  85411. */
  85412. this.onInfluenceChanged = new BABYLON.Observable();
  85413. this.influence = influence;
  85414. }
  85415. Object.defineProperty(MorphTarget.prototype, "influence", {
  85416. /**
  85417. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  85418. */
  85419. get: function () {
  85420. return this._influence;
  85421. },
  85422. set: function (influence) {
  85423. if (this._influence === influence) {
  85424. return;
  85425. }
  85426. var previous = this._influence;
  85427. this._influence = influence;
  85428. if (this.onInfluenceChanged.hasObservers) {
  85429. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  85430. }
  85431. },
  85432. enumerable: true,
  85433. configurable: true
  85434. });
  85435. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  85436. /**
  85437. * Gets a boolean defining if the target contains position data
  85438. */
  85439. get: function () {
  85440. return !!this._positions;
  85441. },
  85442. enumerable: true,
  85443. configurable: true
  85444. });
  85445. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  85446. /**
  85447. * Gets a boolean defining if the target contains normal data
  85448. */
  85449. get: function () {
  85450. return !!this._normals;
  85451. },
  85452. enumerable: true,
  85453. configurable: true
  85454. });
  85455. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  85456. /**
  85457. * Gets a boolean defining if the target contains tangent data
  85458. */
  85459. get: function () {
  85460. return !!this._tangents;
  85461. },
  85462. enumerable: true,
  85463. configurable: true
  85464. });
  85465. /**
  85466. * Affects position data to this target
  85467. * @param data defines the position data to use
  85468. */
  85469. MorphTarget.prototype.setPositions = function (data) {
  85470. this._positions = data;
  85471. };
  85472. /**
  85473. * Gets the position data stored in this target
  85474. * @returns a FloatArray containing the position data (or null if not present)
  85475. */
  85476. MorphTarget.prototype.getPositions = function () {
  85477. return this._positions;
  85478. };
  85479. /**
  85480. * Affects normal data to this target
  85481. * @param data defines the normal data to use
  85482. */
  85483. MorphTarget.prototype.setNormals = function (data) {
  85484. this._normals = data;
  85485. };
  85486. /**
  85487. * Gets the normal data stored in this target
  85488. * @returns a FloatArray containing the normal data (or null if not present)
  85489. */
  85490. MorphTarget.prototype.getNormals = function () {
  85491. return this._normals;
  85492. };
  85493. /**
  85494. * Affects tangent data to this target
  85495. * @param data defines the tangent data to use
  85496. */
  85497. MorphTarget.prototype.setTangents = function (data) {
  85498. this._tangents = data;
  85499. };
  85500. /**
  85501. * Gets the tangent data stored in this target
  85502. * @returns a FloatArray containing the tangent data (or null if not present)
  85503. */
  85504. MorphTarget.prototype.getTangents = function () {
  85505. return this._tangents;
  85506. };
  85507. /**
  85508. * Serializes the current target into a Serialization object
  85509. * @returns the serialized object
  85510. */
  85511. MorphTarget.prototype.serialize = function () {
  85512. var serializationObject = {};
  85513. serializationObject.name = this.name;
  85514. serializationObject.influence = this.influence;
  85515. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85516. if (this.hasNormals) {
  85517. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85518. }
  85519. if (this.hasTangents) {
  85520. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85521. }
  85522. // Animations
  85523. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85524. return serializationObject;
  85525. };
  85526. // Statics
  85527. /**
  85528. * Creates a new target from serialized data
  85529. * @param serializationObject defines the serialized data to use
  85530. * @returns a new MorphTarget
  85531. */
  85532. MorphTarget.Parse = function (serializationObject) {
  85533. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85534. result.setPositions(serializationObject.positions);
  85535. if (serializationObject.normals) {
  85536. result.setNormals(serializationObject.normals);
  85537. }
  85538. if (serializationObject.tangents) {
  85539. result.setTangents(serializationObject.tangents);
  85540. }
  85541. // Animations
  85542. if (serializationObject.animations) {
  85543. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85544. var parsedAnimation = serializationObject.animations[animationIndex];
  85545. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85546. }
  85547. }
  85548. return result;
  85549. };
  85550. /**
  85551. * Creates a MorphTarget from mesh data
  85552. * @param mesh defines the source mesh
  85553. * @param name defines the name to use for the new target
  85554. * @param influence defines the influence to attach to the target
  85555. * @returns a new MorphTarget
  85556. */
  85557. MorphTarget.FromMesh = function (mesh, name, influence) {
  85558. if (!name) {
  85559. name = mesh.name;
  85560. }
  85561. var result = new MorphTarget(name, influence);
  85562. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85563. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85564. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  85565. }
  85566. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  85567. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  85568. }
  85569. return result;
  85570. };
  85571. return MorphTarget;
  85572. }());
  85573. BABYLON.MorphTarget = MorphTarget;
  85574. })(BABYLON || (BABYLON = {}));
  85575. //# sourceMappingURL=babylon.morphTarget.js.map
  85576. var BABYLON;
  85577. (function (BABYLON) {
  85578. /**
  85579. * This class is used to deform meshes using morphing between different targets
  85580. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85581. */
  85582. var MorphTargetManager = /** @class */ (function () {
  85583. /**
  85584. * Creates a new MorphTargetManager
  85585. * @param scene defines the current scene
  85586. */
  85587. function MorphTargetManager(scene) {
  85588. if (scene === void 0) { scene = null; }
  85589. this._targets = new Array();
  85590. this._targetObservable = new Array();
  85591. this._activeTargets = new BABYLON.SmartArray(16);
  85592. this._supportsNormals = false;
  85593. this._supportsTangents = false;
  85594. this._vertexCount = 0;
  85595. this._uniqueId = 0;
  85596. this._tempInfluences = new Array();
  85597. if (!scene) {
  85598. scene = BABYLON.Engine.LastCreatedScene;
  85599. }
  85600. this._scene = scene;
  85601. if (this._scene) {
  85602. this._scene.morphTargetManagers.push(this);
  85603. this._uniqueId = this._scene.getUniqueId();
  85604. }
  85605. }
  85606. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  85607. /**
  85608. * Gets the unique ID of this manager
  85609. */
  85610. get: function () {
  85611. return this._uniqueId;
  85612. },
  85613. enumerable: true,
  85614. configurable: true
  85615. });
  85616. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  85617. /**
  85618. * Gets the number of vertices handled by this manager
  85619. */
  85620. get: function () {
  85621. return this._vertexCount;
  85622. },
  85623. enumerable: true,
  85624. configurable: true
  85625. });
  85626. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  85627. /**
  85628. * Gets a boolean indicating if this manager supports morphing of normals
  85629. */
  85630. get: function () {
  85631. return this._supportsNormals;
  85632. },
  85633. enumerable: true,
  85634. configurable: true
  85635. });
  85636. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  85637. /**
  85638. * Gets a boolean indicating if this manager supports morphing of tangents
  85639. */
  85640. get: function () {
  85641. return this._supportsTangents;
  85642. },
  85643. enumerable: true,
  85644. configurable: true
  85645. });
  85646. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  85647. /**
  85648. * Gets the number of targets stored in this manager
  85649. */
  85650. get: function () {
  85651. return this._targets.length;
  85652. },
  85653. enumerable: true,
  85654. configurable: true
  85655. });
  85656. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  85657. /**
  85658. * Gets the number of influencers (ie. the number of targets with influences > 0)
  85659. */
  85660. get: function () {
  85661. return this._activeTargets.length;
  85662. },
  85663. enumerable: true,
  85664. configurable: true
  85665. });
  85666. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  85667. /**
  85668. * Gets the list of influences (one per target)
  85669. */
  85670. get: function () {
  85671. return this._influences;
  85672. },
  85673. enumerable: true,
  85674. configurable: true
  85675. });
  85676. /**
  85677. * Gets the active target at specified index. An active target is a target with an influence > 0
  85678. * @param index defines the index to check
  85679. * @returns the requested target
  85680. */
  85681. MorphTargetManager.prototype.getActiveTarget = function (index) {
  85682. return this._activeTargets.data[index];
  85683. };
  85684. /**
  85685. * Gets the target at specified index
  85686. * @param index defines the index to check
  85687. * @returns the requested target
  85688. */
  85689. MorphTargetManager.prototype.getTarget = function (index) {
  85690. return this._targets[index];
  85691. };
  85692. /**
  85693. * Add a new target to this manager
  85694. * @param target defines the target to add
  85695. */
  85696. MorphTargetManager.prototype.addTarget = function (target) {
  85697. var _this = this;
  85698. this._targets.push(target);
  85699. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  85700. _this._syncActiveTargets(needUpdate);
  85701. }));
  85702. this._syncActiveTargets(true);
  85703. };
  85704. /**
  85705. * Removes a target from the manager
  85706. * @param target defines the target to remove
  85707. */
  85708. MorphTargetManager.prototype.removeTarget = function (target) {
  85709. var index = this._targets.indexOf(target);
  85710. if (index >= 0) {
  85711. this._targets.splice(index, 1);
  85712. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  85713. this._syncActiveTargets(true);
  85714. }
  85715. };
  85716. /**
  85717. * Serializes the current manager into a Serialization object
  85718. * @returns the serialized object
  85719. */
  85720. MorphTargetManager.prototype.serialize = function () {
  85721. var serializationObject = {};
  85722. serializationObject.id = this.uniqueId;
  85723. serializationObject.targets = [];
  85724. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85725. var target = _a[_i];
  85726. serializationObject.targets.push(target.serialize());
  85727. }
  85728. return serializationObject;
  85729. };
  85730. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  85731. var influenceCount = 0;
  85732. this._activeTargets.reset();
  85733. this._supportsNormals = true;
  85734. this._supportsTangents = true;
  85735. this._vertexCount = 0;
  85736. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85737. var target = _a[_i];
  85738. this._activeTargets.push(target);
  85739. this._tempInfluences[influenceCount++] = target.influence;
  85740. var positions = target.getPositions();
  85741. if (positions) {
  85742. this._supportsNormals = this._supportsNormals && target.hasNormals;
  85743. this._supportsTangents = this._supportsTangents && target.hasTangents;
  85744. var vertexCount = positions.length / 3;
  85745. if (this._vertexCount === 0) {
  85746. this._vertexCount = vertexCount;
  85747. }
  85748. else if (this._vertexCount !== vertexCount) {
  85749. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  85750. return;
  85751. }
  85752. }
  85753. }
  85754. if (!this._influences || this._influences.length !== influenceCount) {
  85755. this._influences = new Float32Array(influenceCount);
  85756. }
  85757. for (var index = 0; index < influenceCount; index++) {
  85758. this._influences[index] = this._tempInfluences[index];
  85759. }
  85760. if (needUpdate) {
  85761. this.synchronize();
  85762. }
  85763. };
  85764. /**
  85765. * Syncrhonize the targets with all the meshes using this morph target manager
  85766. */
  85767. MorphTargetManager.prototype.synchronize = function () {
  85768. if (!this._scene) {
  85769. return;
  85770. }
  85771. // Flag meshes as dirty to resync with the active targets
  85772. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  85773. var mesh = _a[_i];
  85774. if (mesh.morphTargetManager === this) {
  85775. mesh._syncGeometryWithMorphTargetManager();
  85776. }
  85777. }
  85778. };
  85779. // Statics
  85780. /**
  85781. * Creates a new MorphTargetManager from serialized data
  85782. * @param serializationObject defines the serialized data
  85783. * @param scene defines the hosting scene
  85784. * @returns the new MorphTargetManager
  85785. */
  85786. MorphTargetManager.Parse = function (serializationObject, scene) {
  85787. var result = new MorphTargetManager(scene);
  85788. result._uniqueId = serializationObject.id;
  85789. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  85790. var targetData = _a[_i];
  85791. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  85792. }
  85793. return result;
  85794. };
  85795. return MorphTargetManager;
  85796. }());
  85797. BABYLON.MorphTargetManager = MorphTargetManager;
  85798. })(BABYLON || (BABYLON = {}));
  85799. //# sourceMappingURL=babylon.morphTargetManager.js.map
  85800. var BABYLON;
  85801. (function (BABYLON) {
  85802. var Octree = /** @class */ (function () {
  85803. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  85804. if (maxDepth === void 0) { maxDepth = 2; }
  85805. this.maxDepth = maxDepth;
  85806. this.dynamicContent = new Array();
  85807. this._maxBlockCapacity = maxBlockCapacity || 64;
  85808. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  85809. this._creationFunc = creationFunc;
  85810. }
  85811. // Methods
  85812. Octree.prototype.update = function (worldMin, worldMax, entries) {
  85813. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  85814. };
  85815. Octree.prototype.addMesh = function (entry) {
  85816. for (var index = 0; index < this.blocks.length; index++) {
  85817. var block = this.blocks[index];
  85818. block.addEntry(entry);
  85819. }
  85820. };
  85821. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  85822. this._selectionContent.reset();
  85823. for (var index = 0; index < this.blocks.length; index++) {
  85824. var block = this.blocks[index];
  85825. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  85826. }
  85827. if (allowDuplicate) {
  85828. this._selectionContent.concat(this.dynamicContent);
  85829. }
  85830. else {
  85831. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85832. }
  85833. return this._selectionContent;
  85834. };
  85835. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  85836. this._selectionContent.reset();
  85837. for (var index = 0; index < this.blocks.length; index++) {
  85838. var block = this.blocks[index];
  85839. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  85840. }
  85841. if (allowDuplicate) {
  85842. this._selectionContent.concat(this.dynamicContent);
  85843. }
  85844. else {
  85845. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85846. }
  85847. return this._selectionContent;
  85848. };
  85849. Octree.prototype.intersectsRay = function (ray) {
  85850. this._selectionContent.reset();
  85851. for (var index = 0; index < this.blocks.length; index++) {
  85852. var block = this.blocks[index];
  85853. block.intersectsRay(ray, this._selectionContent);
  85854. }
  85855. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  85856. return this._selectionContent;
  85857. };
  85858. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  85859. target.blocks = new Array();
  85860. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  85861. // Segmenting space
  85862. for (var x = 0; x < 2; x++) {
  85863. for (var y = 0; y < 2; y++) {
  85864. for (var z = 0; z < 2; z++) {
  85865. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  85866. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  85867. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  85868. block.addEntries(entries);
  85869. target.blocks.push(block);
  85870. }
  85871. }
  85872. }
  85873. };
  85874. Octree.CreationFuncForMeshes = function (entry, block) {
  85875. var boundingInfo = entry.getBoundingInfo();
  85876. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  85877. block.entries.push(entry);
  85878. }
  85879. };
  85880. Octree.CreationFuncForSubMeshes = function (entry, block) {
  85881. var boundingInfo = entry.getBoundingInfo();
  85882. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  85883. block.entries.push(entry);
  85884. }
  85885. };
  85886. return Octree;
  85887. }());
  85888. BABYLON.Octree = Octree;
  85889. })(BABYLON || (BABYLON = {}));
  85890. //# sourceMappingURL=babylon.octree.js.map
  85891. var BABYLON;
  85892. (function (BABYLON) {
  85893. var OctreeBlock = /** @class */ (function () {
  85894. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  85895. this.entries = new Array();
  85896. this._boundingVectors = new Array();
  85897. this._capacity = capacity;
  85898. this._depth = depth;
  85899. this._maxDepth = maxDepth;
  85900. this._creationFunc = creationFunc;
  85901. this._minPoint = minPoint;
  85902. this._maxPoint = maxPoint;
  85903. this._boundingVectors.push(minPoint.clone());
  85904. this._boundingVectors.push(maxPoint.clone());
  85905. this._boundingVectors.push(minPoint.clone());
  85906. this._boundingVectors[2].x = maxPoint.x;
  85907. this._boundingVectors.push(minPoint.clone());
  85908. this._boundingVectors[3].y = maxPoint.y;
  85909. this._boundingVectors.push(minPoint.clone());
  85910. this._boundingVectors[4].z = maxPoint.z;
  85911. this._boundingVectors.push(maxPoint.clone());
  85912. this._boundingVectors[5].z = minPoint.z;
  85913. this._boundingVectors.push(maxPoint.clone());
  85914. this._boundingVectors[6].x = minPoint.x;
  85915. this._boundingVectors.push(maxPoint.clone());
  85916. this._boundingVectors[7].y = minPoint.y;
  85917. }
  85918. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  85919. // Property
  85920. get: function () {
  85921. return this._capacity;
  85922. },
  85923. enumerable: true,
  85924. configurable: true
  85925. });
  85926. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  85927. get: function () {
  85928. return this._minPoint;
  85929. },
  85930. enumerable: true,
  85931. configurable: true
  85932. });
  85933. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  85934. get: function () {
  85935. return this._maxPoint;
  85936. },
  85937. enumerable: true,
  85938. configurable: true
  85939. });
  85940. // Methods
  85941. OctreeBlock.prototype.addEntry = function (entry) {
  85942. if (this.blocks) {
  85943. for (var index = 0; index < this.blocks.length; index++) {
  85944. var block = this.blocks[index];
  85945. block.addEntry(entry);
  85946. }
  85947. return;
  85948. }
  85949. this._creationFunc(entry, this);
  85950. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  85951. this.createInnerBlocks();
  85952. }
  85953. };
  85954. OctreeBlock.prototype.addEntries = function (entries) {
  85955. for (var index = 0; index < entries.length; index++) {
  85956. var mesh = entries[index];
  85957. this.addEntry(mesh);
  85958. }
  85959. };
  85960. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  85961. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  85962. if (this.blocks) {
  85963. for (var index = 0; index < this.blocks.length; index++) {
  85964. var block = this.blocks[index];
  85965. block.select(frustumPlanes, selection, allowDuplicate);
  85966. }
  85967. return;
  85968. }
  85969. if (allowDuplicate) {
  85970. selection.concat(this.entries);
  85971. }
  85972. else {
  85973. selection.concatWithNoDuplicate(this.entries);
  85974. }
  85975. }
  85976. };
  85977. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  85978. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  85979. if (this.blocks) {
  85980. for (var index = 0; index < this.blocks.length; index++) {
  85981. var block = this.blocks[index];
  85982. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  85983. }
  85984. return;
  85985. }
  85986. if (allowDuplicate) {
  85987. selection.concat(this.entries);
  85988. }
  85989. else {
  85990. selection.concatWithNoDuplicate(this.entries);
  85991. }
  85992. }
  85993. };
  85994. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  85995. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  85996. if (this.blocks) {
  85997. for (var index = 0; index < this.blocks.length; index++) {
  85998. var block = this.blocks[index];
  85999. block.intersectsRay(ray, selection);
  86000. }
  86001. return;
  86002. }
  86003. selection.concatWithNoDuplicate(this.entries);
  86004. }
  86005. };
  86006. OctreeBlock.prototype.createInnerBlocks = function () {
  86007. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  86008. };
  86009. return OctreeBlock;
  86010. }());
  86011. BABYLON.OctreeBlock = OctreeBlock;
  86012. })(BABYLON || (BABYLON = {}));
  86013. //# sourceMappingURL=babylon.octreeBlock.js.map
  86014. var BABYLON;
  86015. (function (BABYLON) {
  86016. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86017. __extends(VRDistortionCorrectionPostProcess, _super);
  86018. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86019. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86020. 'LensCenter',
  86021. 'Scale',
  86022. 'ScaleIn',
  86023. 'HmdWarpParam'
  86024. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86025. _this._isRightEye = isRightEye;
  86026. _this._distortionFactors = vrMetrics.distortionK;
  86027. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86028. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86029. _this.adaptScaleToCurrentViewport = true;
  86030. _this.onSizeChangedObservable.add(function () {
  86031. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86032. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86033. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86034. });
  86035. _this.onApplyObservable.add(function (effect) {
  86036. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86037. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86038. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86039. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86040. });
  86041. return _this;
  86042. }
  86043. return VRDistortionCorrectionPostProcess;
  86044. }(BABYLON.PostProcess));
  86045. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  86046. })(BABYLON || (BABYLON = {}));
  86047. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  86048. var BABYLON;
  86049. (function (BABYLON) {
  86050. /**
  86051. * Postprocess used to generate anaglyphic rendering
  86052. */
  86053. var AnaglyphPostProcess = /** @class */ (function (_super) {
  86054. __extends(AnaglyphPostProcess, _super);
  86055. /**
  86056. * Creates a new AnaglyphPostProcess
  86057. * @param name defines postprocess name
  86058. * @param options defines creation options or target ratio scale
  86059. * @param rigCameras defines cameras using this postprocess
  86060. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  86061. * @param engine defines hosting engine
  86062. * @param reusable defines if the postprocess will be reused multiple times per frame
  86063. */
  86064. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  86065. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  86066. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86067. _this.onApplyObservable.add(function (effect) {
  86068. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  86069. });
  86070. return _this;
  86071. }
  86072. return AnaglyphPostProcess;
  86073. }(BABYLON.PostProcess));
  86074. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  86075. })(BABYLON || (BABYLON = {}));
  86076. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  86077. var BABYLON;
  86078. (function (BABYLON) {
  86079. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  86080. __extends(StereoscopicInterlacePostProcess, _super);
  86081. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  86082. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  86083. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86084. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86085. _this.onSizeChangedObservable.add(function () {
  86086. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86087. });
  86088. _this.onApplyObservable.add(function (effect) {
  86089. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  86090. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  86091. });
  86092. return _this;
  86093. }
  86094. return StereoscopicInterlacePostProcess;
  86095. }(BABYLON.PostProcess));
  86096. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  86097. })(BABYLON || (BABYLON = {}));
  86098. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  86099. var BABYLON;
  86100. (function (BABYLON) {
  86101. /**
  86102. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  86103. * Screen rotation is taken into account.
  86104. */
  86105. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  86106. function FreeCameraDeviceOrientationInput() {
  86107. var _this = this;
  86108. this._screenOrientationAngle = 0;
  86109. this._screenQuaternion = new BABYLON.Quaternion();
  86110. this._alpha = 0;
  86111. this._beta = 0;
  86112. this._gamma = 0;
  86113. this._orientationChanged = function () {
  86114. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  86115. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  86116. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  86117. };
  86118. this._deviceOrientation = function (evt) {
  86119. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  86120. _this._beta = evt.beta !== null ? evt.beta : 0;
  86121. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  86122. };
  86123. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  86124. this._orientationChanged();
  86125. }
  86126. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  86127. get: function () {
  86128. return this._camera;
  86129. },
  86130. set: function (camera) {
  86131. this._camera = camera;
  86132. if (this._camera != null && !this._camera.rotationQuaternion) {
  86133. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  86134. }
  86135. },
  86136. enumerable: true,
  86137. configurable: true
  86138. });
  86139. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86140. window.addEventListener("orientationchange", this._orientationChanged);
  86141. window.addEventListener("deviceorientation", this._deviceOrientation);
  86142. //In certain cases, the attach control is called AFTER orientation was changed,
  86143. //So this is needed.
  86144. this._orientationChanged();
  86145. };
  86146. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  86147. window.removeEventListener("orientationchange", this._orientationChanged);
  86148. window.removeEventListener("deviceorientation", this._deviceOrientation);
  86149. };
  86150. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  86151. //if no device orientation provided, don't update the rotation.
  86152. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  86153. if (!this._alpha)
  86154. return;
  86155. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  86156. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  86157. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  86158. //Mirror on XY Plane
  86159. this._camera.rotationQuaternion.z *= -1;
  86160. this._camera.rotationQuaternion.w *= -1;
  86161. };
  86162. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  86163. return "FreeCameraDeviceOrientationInput";
  86164. };
  86165. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  86166. return "deviceOrientation";
  86167. };
  86168. return FreeCameraDeviceOrientationInput;
  86169. }());
  86170. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  86171. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  86172. })(BABYLON || (BABYLON = {}));
  86173. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  86174. var BABYLON;
  86175. (function (BABYLON) {
  86176. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  86177. function ArcRotateCameraVRDeviceOrientationInput() {
  86178. this.alphaCorrection = 1;
  86179. this.betaCorrection = 1;
  86180. this.gammaCorrection = 1;
  86181. this._alpha = 0;
  86182. this._gamma = 0;
  86183. this._dirty = false;
  86184. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  86185. }
  86186. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86187. this.camera.attachControl(element, noPreventDefault);
  86188. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  86189. };
  86190. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  86191. if (evt.alpha !== null) {
  86192. this._alpha = +evt.alpha | 0;
  86193. }
  86194. if (evt.gamma !== null) {
  86195. this._gamma = +evt.gamma | 0;
  86196. }
  86197. this._dirty = true;
  86198. };
  86199. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  86200. if (this._dirty) {
  86201. this._dirty = false;
  86202. if (this._gamma < 0) {
  86203. this._gamma = 180 + this._gamma;
  86204. }
  86205. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  86206. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  86207. }
  86208. };
  86209. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  86210. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  86211. };
  86212. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  86213. return "ArcRotateCameraVRDeviceOrientationInput";
  86214. };
  86215. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  86216. return "VRDeviceOrientation";
  86217. };
  86218. return ArcRotateCameraVRDeviceOrientationInput;
  86219. }());
  86220. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  86221. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  86222. })(BABYLON || (BABYLON = {}));
  86223. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  86224. var BABYLON;
  86225. (function (BABYLON) {
  86226. var VRCameraMetrics = /** @class */ (function () {
  86227. function VRCameraMetrics() {
  86228. this.compensateDistortion = true;
  86229. }
  86230. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  86231. get: function () {
  86232. return this.hResolution / (2 * this.vResolution);
  86233. },
  86234. enumerable: true,
  86235. configurable: true
  86236. });
  86237. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  86238. get: function () {
  86239. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  86240. },
  86241. enumerable: true,
  86242. configurable: true
  86243. });
  86244. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  86245. get: function () {
  86246. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86247. var h = (4 * meters) / this.hScreenSize;
  86248. return BABYLON.Matrix.Translation(h, 0, 0);
  86249. },
  86250. enumerable: true,
  86251. configurable: true
  86252. });
  86253. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  86254. get: function () {
  86255. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86256. var h = (4 * meters) / this.hScreenSize;
  86257. return BABYLON.Matrix.Translation(-h, 0, 0);
  86258. },
  86259. enumerable: true,
  86260. configurable: true
  86261. });
  86262. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  86263. get: function () {
  86264. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  86265. },
  86266. enumerable: true,
  86267. configurable: true
  86268. });
  86269. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  86270. get: function () {
  86271. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  86272. },
  86273. enumerable: true,
  86274. configurable: true
  86275. });
  86276. VRCameraMetrics.GetDefault = function () {
  86277. var result = new VRCameraMetrics();
  86278. result.hResolution = 1280;
  86279. result.vResolution = 800;
  86280. result.hScreenSize = 0.149759993;
  86281. result.vScreenSize = 0.0935999975;
  86282. result.vScreenCenter = 0.0467999987;
  86283. result.eyeToScreenDistance = 0.0410000011;
  86284. result.lensSeparationDistance = 0.0635000020;
  86285. result.interpupillaryDistance = 0.0640000030;
  86286. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  86287. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  86288. result.postProcessScaleFactor = 1.714605507808412;
  86289. result.lensCenterOffset = 0.151976421;
  86290. return result;
  86291. };
  86292. return VRCameraMetrics;
  86293. }());
  86294. BABYLON.VRCameraMetrics = VRCameraMetrics;
  86295. })(BABYLON || (BABYLON = {}));
  86296. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  86297. var BABYLON;
  86298. (function (BABYLON) {
  86299. /**
  86300. * This represents a WebVR camera.
  86301. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  86302. * @example http://doc.babylonjs.com/how_to/webvr_camera
  86303. */
  86304. var WebVRFreeCamera = /** @class */ (function (_super) {
  86305. __extends(WebVRFreeCamera, _super);
  86306. /**
  86307. * Instantiates a WebVRFreeCamera.
  86308. * @param name The name of the WebVRFreeCamera
  86309. * @param position The starting anchor position for the camera
  86310. * @param scene The scene the camera belongs to
  86311. * @param webVROptions a set of customizable options for the webVRCamera
  86312. */
  86313. function WebVRFreeCamera(name, position, scene, webVROptions) {
  86314. if (webVROptions === void 0) { webVROptions = {}; }
  86315. var _this = _super.call(this, name, position, scene) || this;
  86316. _this.webVROptions = webVROptions;
  86317. /**
  86318. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  86319. */
  86320. _this._vrDevice = null;
  86321. /**
  86322. * The rawPose of the vrDevice.
  86323. */
  86324. _this.rawPose = null;
  86325. _this._specsVersion = "1.1";
  86326. _this._attached = false;
  86327. _this._descendants = [];
  86328. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  86329. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  86330. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  86331. _this._standingMatrix = null;
  86332. /**
  86333. * Represents device position in babylon space.
  86334. */
  86335. _this.devicePosition = BABYLON.Vector3.Zero();
  86336. /**
  86337. * Represents device rotation in babylon space.
  86338. */
  86339. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  86340. /**
  86341. * The scale of the device to be used when translating from device space to babylon space.
  86342. */
  86343. _this.deviceScaleFactor = 1;
  86344. _this._deviceToWorld = BABYLON.Matrix.Identity();
  86345. _this._worldToDevice = BABYLON.Matrix.Identity();
  86346. /**
  86347. * References to the webVR controllers for the vrDevice.
  86348. */
  86349. _this.controllers = [];
  86350. /**
  86351. * Emits an event when a controller is attached.
  86352. */
  86353. _this.onControllersAttachedObservable = new BABYLON.Observable();
  86354. /**
  86355. * Emits an event when a controller's mesh has been loaded;
  86356. */
  86357. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86358. /**
  86359. * If the rig cameras be used as parent instead of this camera.
  86360. */
  86361. _this.rigParenting = true;
  86362. _this._defaultHeight = undefined;
  86363. _this._workingVector = BABYLON.Vector3.Zero();
  86364. _this._oneVector = BABYLON.Vector3.One();
  86365. _this._workingMatrix = BABYLON.Matrix.Identity();
  86366. _this._cache.position = BABYLON.Vector3.Zero();
  86367. if (webVROptions.defaultHeight) {
  86368. _this._defaultHeight = webVROptions.defaultHeight;
  86369. _this.position.y = _this._defaultHeight;
  86370. }
  86371. _this.minZ = 0.1;
  86372. //legacy support - the compensation boolean was removed.
  86373. if (arguments.length === 5) {
  86374. _this.webVROptions = arguments[4];
  86375. }
  86376. // default webVR options
  86377. if (_this.webVROptions.trackPosition == undefined) {
  86378. _this.webVROptions.trackPosition = true;
  86379. }
  86380. if (_this.webVROptions.controllerMeshes == undefined) {
  86381. _this.webVROptions.controllerMeshes = true;
  86382. }
  86383. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  86384. _this.webVROptions.defaultLightingOnControllers = true;
  86385. }
  86386. _this.rotationQuaternion = new BABYLON.Quaternion();
  86387. if (_this.webVROptions && _this.webVROptions.positionScale) {
  86388. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  86389. }
  86390. //enable VR
  86391. var engine = _this.getEngine();
  86392. _this._onVREnabled = function (success) { if (success) {
  86393. _this.initControllers();
  86394. } };
  86395. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  86396. engine.initWebVR().add(function (event) {
  86397. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  86398. return;
  86399. }
  86400. _this._vrDevice = event.vrDisplay;
  86401. //reset the rig parameters.
  86402. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  86403. if (_this._attached) {
  86404. _this.getEngine().enableVR();
  86405. }
  86406. });
  86407. if (typeof (VRFrameData) !== "undefined")
  86408. _this._frameData = new VRFrameData();
  86409. /**
  86410. * The idea behind the following lines:
  86411. * objects that have the camera as parent should actually have the rig cameras as a parent.
  86412. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  86413. * the second will not show it correctly.
  86414. *
  86415. * To solve this - each object that has the camera as parent will be added to a protected array.
  86416. * When the rig camera renders, it will take this array and set all of those to be its children.
  86417. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  86418. * Amazing!
  86419. */
  86420. scene.onBeforeCameraRenderObservable.add(function (camera) {
  86421. if (camera.parent === _this && _this.rigParenting) {
  86422. _this._descendants = _this.getDescendants(true, function (n) {
  86423. // don't take the cameras or the controllers!
  86424. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  86425. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  86426. return !isController && !isRigCamera;
  86427. });
  86428. _this._descendants.forEach(function (node) {
  86429. node.parent = camera;
  86430. });
  86431. }
  86432. });
  86433. scene.onAfterCameraRenderObservable.add(function (camera) {
  86434. if (camera.parent === _this && _this.rigParenting) {
  86435. _this._descendants.forEach(function (node) {
  86436. node.parent = _this;
  86437. });
  86438. }
  86439. });
  86440. return _this;
  86441. }
  86442. /**
  86443. * Gets the device distance from the ground in meters.
  86444. * @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.
  86445. */
  86446. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  86447. if (this._standingMatrix) {
  86448. // Add standing matrix offset to get real offset from ground in room
  86449. this._standingMatrix.getTranslationToRef(this._workingVector);
  86450. return this._deviceRoomPosition.y + this._workingVector.y;
  86451. }
  86452. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  86453. return this._defaultHeight || 0;
  86454. };
  86455. /**
  86456. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86457. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  86458. */
  86459. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  86460. var _this = this;
  86461. if (callback === void 0) { callback = function (bool) { }; }
  86462. // Use standing matrix if available
  86463. this.getEngine().initWebVRAsync().then(function (result) {
  86464. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  86465. callback(false);
  86466. }
  86467. else {
  86468. _this._standingMatrix = new BABYLON.Matrix();
  86469. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  86470. if (!_this.getScene().useRightHandedSystem) {
  86471. [2, 6, 8, 9, 14].forEach(function (num) {
  86472. if (_this._standingMatrix) {
  86473. _this._standingMatrix.m[num] *= -1;
  86474. }
  86475. });
  86476. }
  86477. callback(true);
  86478. }
  86479. });
  86480. };
  86481. /**
  86482. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86483. * @returns A promise with a boolean set to if the standing matrix is supported.
  86484. */
  86485. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  86486. var _this = this;
  86487. return new Promise(function (res, rej) {
  86488. _this.useStandingMatrix(function (supported) {
  86489. res(supported);
  86490. });
  86491. });
  86492. };
  86493. /**
  86494. * Disposes the camera
  86495. */
  86496. WebVRFreeCamera.prototype.dispose = function () {
  86497. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  86498. _super.prototype.dispose.call(this);
  86499. };
  86500. /**
  86501. * Gets a vrController by name.
  86502. * @param name The name of the controller to retreive
  86503. * @returns the controller matching the name specified or null if not found
  86504. */
  86505. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  86506. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  86507. var gp = _a[_i];
  86508. if (gp.hand === name) {
  86509. return gp;
  86510. }
  86511. }
  86512. return null;
  86513. };
  86514. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  86515. /**
  86516. * The controller corrisponding to the users left hand.
  86517. */
  86518. get: function () {
  86519. if (!this._leftController) {
  86520. this._leftController = this.getControllerByName("left");
  86521. }
  86522. return this._leftController;
  86523. },
  86524. enumerable: true,
  86525. configurable: true
  86526. });
  86527. ;
  86528. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86529. /**
  86530. * The controller corrisponding to the users right hand.
  86531. */
  86532. get: function () {
  86533. if (!this._rightController) {
  86534. this._rightController = this.getControllerByName("right");
  86535. }
  86536. return this._rightController;
  86537. },
  86538. enumerable: true,
  86539. configurable: true
  86540. });
  86541. ;
  86542. /**
  86543. * Casts a ray forward from the vrCamera's gaze.
  86544. * @param length Length of the ray (default: 100)
  86545. * @returns the ray corrisponding to the gaze
  86546. */
  86547. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86548. if (length === void 0) { length = 100; }
  86549. if (this.leftCamera) {
  86550. // Use left eye to avoid computation to compute center on every call
  86551. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86552. }
  86553. else {
  86554. return _super.prototype.getForwardRay.call(this, length);
  86555. }
  86556. };
  86557. /**
  86558. * Updates the camera based on device's frame data
  86559. */
  86560. WebVRFreeCamera.prototype._checkInputs = function () {
  86561. if (this._vrDevice && this._vrDevice.isPresenting) {
  86562. this._vrDevice.getFrameData(this._frameData);
  86563. this.updateFromDevice(this._frameData.pose);
  86564. }
  86565. _super.prototype._checkInputs.call(this);
  86566. };
  86567. /**
  86568. * Updates the poseControlled values based on the input device pose.
  86569. * @param poseData Pose coming from the device
  86570. */
  86571. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  86572. if (poseData && poseData.orientation) {
  86573. this.rawPose = poseData;
  86574. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  86575. if (this.getScene().useRightHandedSystem) {
  86576. this._deviceRoomRotationQuaternion.z *= -1;
  86577. this._deviceRoomRotationQuaternion.w *= -1;
  86578. }
  86579. if (this.webVROptions.trackPosition && this.rawPose.position) {
  86580. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  86581. if (this.getScene().useRightHandedSystem) {
  86582. this._deviceRoomPosition.z *= -1;
  86583. }
  86584. }
  86585. }
  86586. };
  86587. /**
  86588. * WebVR's attach control will start broadcasting frames to the device.
  86589. * Note that in certain browsers (chrome for example) this function must be called
  86590. * within a user-interaction callback. Example:
  86591. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  86592. *
  86593. * @param element html element to attach the vrDevice to
  86594. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  86595. */
  86596. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  86597. _super.prototype.attachControl.call(this, element, noPreventDefault);
  86598. this._attached = true;
  86599. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  86600. if (this._vrDevice) {
  86601. this.getEngine().enableVR();
  86602. }
  86603. };
  86604. /**
  86605. * Detaches the camera from the html element and disables VR
  86606. *
  86607. * @param element html element to detach from
  86608. */
  86609. WebVRFreeCamera.prototype.detachControl = function (element) {
  86610. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  86611. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  86612. _super.prototype.detachControl.call(this, element);
  86613. this._attached = false;
  86614. this.getEngine().disableVR();
  86615. };
  86616. /**
  86617. * @returns the name of this class
  86618. */
  86619. WebVRFreeCamera.prototype.getClassName = function () {
  86620. return "WebVRFreeCamera";
  86621. };
  86622. /**
  86623. * Calls resetPose on the vrDisplay
  86624. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  86625. */
  86626. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  86627. //uses the vrDisplay's "resetPose()".
  86628. //pitch and roll won't be affected.
  86629. this._vrDevice.resetPose();
  86630. };
  86631. /**
  86632. * Updates the rig cameras (left and right eye)
  86633. */
  86634. WebVRFreeCamera.prototype._updateRigCameras = function () {
  86635. var camLeft = this._rigCameras[0];
  86636. var camRight = this._rigCameras[1];
  86637. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86638. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86639. camLeft.position.copyFrom(this._deviceRoomPosition);
  86640. camRight.position.copyFrom(this._deviceRoomPosition);
  86641. };
  86642. /**
  86643. * Updates the cached values of the camera
  86644. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  86645. */
  86646. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  86647. var _this = this;
  86648. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  86649. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  86650. if (!this.updateCacheCalled) {
  86651. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  86652. this.updateCacheCalled = true;
  86653. this.update();
  86654. }
  86655. // Set working vector to the device position in room space rotated by the new rotation
  86656. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  86657. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  86658. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  86659. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  86660. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  86661. // Add translation from anchor position
  86662. this._deviceToWorld.getTranslationToRef(this._workingVector);
  86663. this._workingVector.addInPlace(this.position);
  86664. this._workingVector.subtractInPlace(this._cache.position);
  86665. this._deviceToWorld.setTranslation(this._workingVector);
  86666. // Set an inverted matrix to be used when updating the camera
  86667. this._deviceToWorld.invertToRef(this._worldToDevice);
  86668. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  86669. this.controllers.forEach(function (controller) {
  86670. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  86671. controller.update();
  86672. });
  86673. }
  86674. if (!ignoreParentClass) {
  86675. _super.prototype._updateCache.call(this);
  86676. }
  86677. this.updateCacheCalled = false;
  86678. };
  86679. /**
  86680. * Updates the current device position and rotation in the babylon world
  86681. */
  86682. WebVRFreeCamera.prototype.update = function () {
  86683. // Get current device position in babylon world
  86684. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  86685. // Get current device rotation in babylon world
  86686. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  86687. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  86688. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  86689. _super.prototype.update.call(this);
  86690. };
  86691. /**
  86692. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  86693. * @returns an identity matrix
  86694. */
  86695. WebVRFreeCamera.prototype._getViewMatrix = function () {
  86696. return BABYLON.Matrix.Identity();
  86697. };
  86698. /**
  86699. * This function is called by the two RIG cameras.
  86700. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  86701. */
  86702. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  86703. var _this = this;
  86704. // Update the parent camera prior to using a child camera to avoid desynchronization
  86705. var parentCamera = this._cameraRigParams["parentCamera"];
  86706. parentCamera._updateCache();
  86707. //WebVR 1.1
  86708. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  86709. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  86710. if (!this.getScene().useRightHandedSystem) {
  86711. [2, 6, 8, 9, 14].forEach(function (num) {
  86712. _this._webvrViewMatrix.m[num] *= -1;
  86713. });
  86714. }
  86715. // update the camera rotation matrix
  86716. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  86717. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  86718. // Computing target and final matrix
  86719. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  86720. // should the view matrix be updated with scale and position offset?
  86721. if (parentCamera.deviceScaleFactor !== 1) {
  86722. this._webvrViewMatrix.invert();
  86723. // scale the position, if set
  86724. if (parentCamera.deviceScaleFactor) {
  86725. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  86726. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  86727. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  86728. }
  86729. this._webvrViewMatrix.invert();
  86730. }
  86731. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  86732. // Compute global position
  86733. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  86734. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  86735. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  86736. this._workingMatrix.getTranslationToRef(this._globalPosition);
  86737. this._markSyncedWithParent();
  86738. return this._webvrViewMatrix;
  86739. };
  86740. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  86741. var _this = this;
  86742. var parentCamera = this.parent;
  86743. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  86744. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  86745. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  86746. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  86747. //babylon compatible matrix
  86748. if (!this.getScene().useRightHandedSystem) {
  86749. [8, 9, 10, 11].forEach(function (num) {
  86750. _this._projectionMatrix.m[num] *= -1;
  86751. });
  86752. }
  86753. return this._projectionMatrix;
  86754. };
  86755. /**
  86756. * Initializes the controllers and their meshes
  86757. */
  86758. WebVRFreeCamera.prototype.initControllers = function () {
  86759. var _this = this;
  86760. this.controllers = [];
  86761. var manager = this.getScene().gamepadManager;
  86762. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  86763. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86764. var webVrController = gamepad;
  86765. if (webVrController.defaultModel) {
  86766. webVrController.defaultModel.setEnabled(false);
  86767. }
  86768. if (webVrController.hand === "right") {
  86769. _this._rightController = null;
  86770. }
  86771. if (webVrController.hand === "left") {
  86772. _this._leftController = null;
  86773. }
  86774. var controllerIndex = _this.controllers.indexOf(webVrController);
  86775. if (controllerIndex !== -1) {
  86776. _this.controllers.splice(controllerIndex, 1);
  86777. }
  86778. }
  86779. });
  86780. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  86781. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86782. var webVrController_1 = gamepad;
  86783. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  86784. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  86785. if (_this.webVROptions.controllerMeshes) {
  86786. if (webVrController_1.defaultModel) {
  86787. webVrController_1.defaultModel.setEnabled(true);
  86788. }
  86789. else {
  86790. // Load the meshes
  86791. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  86792. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  86793. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  86794. if (_this.webVROptions.defaultLightingOnControllers) {
  86795. if (!_this._lightOnControllers) {
  86796. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  86797. }
  86798. var activateLightOnSubMeshes_1 = function (mesh, light) {
  86799. var children = mesh.getChildren();
  86800. if (children.length !== 0) {
  86801. children.forEach(function (mesh) {
  86802. light.includedOnlyMeshes.push(mesh);
  86803. activateLightOnSubMeshes_1(mesh, light);
  86804. });
  86805. }
  86806. };
  86807. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  86808. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  86809. }
  86810. });
  86811. }
  86812. }
  86813. webVrController_1.attachToPoseControlledCamera(_this);
  86814. // since this is async - sanity check. Is the controller already stored?
  86815. if (_this.controllers.indexOf(webVrController_1) === -1) {
  86816. //add to the controllers array
  86817. _this.controllers.push(webVrController_1);
  86818. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  86819. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  86820. // So we're overriding setting left & right manually to be sure
  86821. var firstViveWandDetected = false;
  86822. for (var i = 0; i < _this.controllers.length; i++) {
  86823. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  86824. if (!firstViveWandDetected) {
  86825. firstViveWandDetected = true;
  86826. _this.controllers[i].hand = "left";
  86827. }
  86828. else {
  86829. _this.controllers[i].hand = "right";
  86830. }
  86831. }
  86832. }
  86833. //did we find enough controllers? Great! let the developer know.
  86834. if (_this.controllers.length >= 2) {
  86835. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  86836. }
  86837. }
  86838. }
  86839. });
  86840. };
  86841. return WebVRFreeCamera;
  86842. }(BABYLON.FreeCamera));
  86843. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  86844. })(BABYLON || (BABYLON = {}));
  86845. //# sourceMappingURL=babylon.webVRCamera.js.map
  86846. var BABYLON;
  86847. (function (BABYLON) {
  86848. // We're mainly based on the logic defined into the FreeCamera code
  86849. /**
  86850. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  86851. * being tilted forward or back and left or right.
  86852. */
  86853. var DeviceOrientationCamera = /** @class */ (function (_super) {
  86854. __extends(DeviceOrientationCamera, _super);
  86855. /**
  86856. * Creates a new device orientation camera
  86857. * @param name The name of the camera
  86858. * @param position The start position camera
  86859. * @param scene The scene the camera belongs to
  86860. */
  86861. function DeviceOrientationCamera(name, position, scene) {
  86862. var _this = _super.call(this, name, position, scene) || this;
  86863. _this._quaternionCache = new BABYLON.Quaternion();
  86864. _this.inputs.addDeviceOrientation();
  86865. return _this;
  86866. }
  86867. /**
  86868. * Gets the current instance class name ("DeviceOrientationCamera").
  86869. * This helps avoiding instanceof at run time.
  86870. * @returns the class name
  86871. */
  86872. DeviceOrientationCamera.prototype.getClassName = function () {
  86873. return "DeviceOrientationCamera";
  86874. };
  86875. /**
  86876. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  86877. */
  86878. DeviceOrientationCamera.prototype._checkInputs = function () {
  86879. _super.prototype._checkInputs.call(this);
  86880. this._quaternionCache.copyFrom(this.rotationQuaternion);
  86881. if (this._initialQuaternion) {
  86882. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  86883. }
  86884. };
  86885. /**
  86886. * Reset the camera to its default orientation on the specified axis only.
  86887. * @param axis The axis to reset
  86888. */
  86889. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  86890. var _this = this;
  86891. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  86892. //can only work if this camera has a rotation quaternion already.
  86893. if (!this.rotationQuaternion)
  86894. return;
  86895. if (!this._initialQuaternion) {
  86896. this._initialQuaternion = new BABYLON.Quaternion();
  86897. }
  86898. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  86899. ['x', 'y', 'z'].forEach(function (axisName) {
  86900. if (!axis[axisName]) {
  86901. _this._initialQuaternion[axisName] = 0;
  86902. }
  86903. else {
  86904. _this._initialQuaternion[axisName] *= -1;
  86905. }
  86906. });
  86907. this._initialQuaternion.normalize();
  86908. //force rotation update
  86909. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  86910. };
  86911. return DeviceOrientationCamera;
  86912. }(BABYLON.FreeCamera));
  86913. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  86914. })(BABYLON || (BABYLON = {}));
  86915. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  86916. var BABYLON;
  86917. (function (BABYLON) {
  86918. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  86919. __extends(VRDeviceOrientationFreeCamera, _super);
  86920. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  86921. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86922. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86923. var _this = _super.call(this, name, position, scene) || this;
  86924. vrCameraMetrics.compensateDistortion = compensateDistortion;
  86925. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  86926. return _this;
  86927. }
  86928. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  86929. return "VRDeviceOrientationFreeCamera";
  86930. };
  86931. return VRDeviceOrientationFreeCamera;
  86932. }(BABYLON.DeviceOrientationCamera));
  86933. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  86934. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  86935. __extends(VRDeviceOrientationGamepadCamera, _super);
  86936. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  86937. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86938. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86939. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  86940. _this.inputs.addGamepad();
  86941. return _this;
  86942. }
  86943. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  86944. return "VRDeviceOrientationGamepadCamera";
  86945. };
  86946. return VRDeviceOrientationGamepadCamera;
  86947. }(VRDeviceOrientationFreeCamera));
  86948. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  86949. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  86950. __extends(VRDeviceOrientationArcRotateCamera, _super);
  86951. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  86952. if (compensateDistortion === void 0) { compensateDistortion = true; }
  86953. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  86954. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  86955. vrCameraMetrics.compensateDistortion = compensateDistortion;
  86956. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  86957. _this.inputs.addVRDeviceOrientation();
  86958. return _this;
  86959. }
  86960. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  86961. return "VRDeviceOrientationArcRotateCamera";
  86962. };
  86963. return VRDeviceOrientationArcRotateCamera;
  86964. }(BABYLON.ArcRotateCamera));
  86965. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  86966. })(BABYLON || (BABYLON = {}));
  86967. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  86968. var BABYLON;
  86969. (function (BABYLON) {
  86970. /**
  86971. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  86972. */
  86973. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  86974. __extends(AnaglyphFreeCamera, _super);
  86975. /**
  86976. * Creates a new AnaglyphFreeCamera
  86977. * @param name defines camera name
  86978. * @param position defines initial position
  86979. * @param interaxialDistance defines distance between each color axis
  86980. * @param scene defines the hosting scene
  86981. */
  86982. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  86983. var _this = _super.call(this, name, position, scene) || this;
  86984. _this.interaxialDistance = interaxialDistance;
  86985. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  86986. return _this;
  86987. }
  86988. /**
  86989. * Gets camera class name
  86990. * @returns AnaglyphFreeCamera
  86991. */
  86992. AnaglyphFreeCamera.prototype.getClassName = function () {
  86993. return "AnaglyphFreeCamera";
  86994. };
  86995. return AnaglyphFreeCamera;
  86996. }(BABYLON.FreeCamera));
  86997. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  86998. /**
  86999. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  87000. */
  87001. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  87002. __extends(AnaglyphArcRotateCamera, _super);
  87003. /**
  87004. * Creates a new AnaglyphArcRotateCamera
  87005. * @param name defines camera name
  87006. * @param alpha defines alpha angle (in radians)
  87007. * @param beta defines beta angle (in radians)
  87008. * @param radius defines radius
  87009. * @param target defines camera target
  87010. * @param interaxialDistance defines distance between each color axis
  87011. * @param scene defines the hosting scene
  87012. */
  87013. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  87014. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87015. _this.interaxialDistance = interaxialDistance;
  87016. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87017. return _this;
  87018. }
  87019. /**
  87020. * Gets camera class name
  87021. * @returns AnaglyphArcRotateCamera
  87022. */
  87023. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87024. return "AnaglyphArcRotateCamera";
  87025. };
  87026. return AnaglyphArcRotateCamera;
  87027. }(BABYLON.ArcRotateCamera));
  87028. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87029. /**
  87030. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87031. */
  87032. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87033. __extends(AnaglyphGamepadCamera, _super);
  87034. /**
  87035. * Creates a new AnaglyphGamepadCamera
  87036. * @param name defines camera name
  87037. * @param position defines initial position
  87038. * @param interaxialDistance defines distance between each color axis
  87039. * @param scene defines the hosting scene
  87040. */
  87041. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  87042. var _this = _super.call(this, name, position, scene) || this;
  87043. _this.interaxialDistance = interaxialDistance;
  87044. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87045. return _this;
  87046. }
  87047. /**
  87048. * Gets camera class name
  87049. * @returns AnaglyphGamepadCamera
  87050. */
  87051. AnaglyphGamepadCamera.prototype.getClassName = function () {
  87052. return "AnaglyphGamepadCamera";
  87053. };
  87054. return AnaglyphGamepadCamera;
  87055. }(BABYLON.GamepadCamera));
  87056. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  87057. /**
  87058. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  87059. */
  87060. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  87061. __extends(AnaglyphUniversalCamera, _super);
  87062. /**
  87063. * Creates a new AnaglyphUniversalCamera
  87064. * @param name defines camera name
  87065. * @param position defines initial position
  87066. * @param interaxialDistance defines distance between each color axis
  87067. * @param scene defines the hosting scene
  87068. */
  87069. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  87070. var _this = _super.call(this, name, position, scene) || this;
  87071. _this.interaxialDistance = interaxialDistance;
  87072. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87073. return _this;
  87074. }
  87075. /**
  87076. * Gets camera class name
  87077. * @returns AnaglyphUniversalCamera
  87078. */
  87079. AnaglyphUniversalCamera.prototype.getClassName = function () {
  87080. return "AnaglyphUniversalCamera";
  87081. };
  87082. return AnaglyphUniversalCamera;
  87083. }(BABYLON.UniversalCamera));
  87084. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  87085. /**
  87086. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  87087. */
  87088. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  87089. __extends(StereoscopicFreeCamera, _super);
  87090. /**
  87091. * Creates a new StereoscopicFreeCamera
  87092. * @param name defines camera name
  87093. * @param position defines initial position
  87094. * @param interaxialDistance defines distance between each color axis
  87095. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87096. * @param scene defines the hosting scene
  87097. */
  87098. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87099. var _this = _super.call(this, name, position, scene) || this;
  87100. _this.interaxialDistance = interaxialDistance;
  87101. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87102. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87103. return _this;
  87104. }
  87105. /**
  87106. * Gets camera class name
  87107. * @returns StereoscopicFreeCamera
  87108. */
  87109. StereoscopicFreeCamera.prototype.getClassName = function () {
  87110. return "StereoscopicFreeCamera";
  87111. };
  87112. return StereoscopicFreeCamera;
  87113. }(BABYLON.FreeCamera));
  87114. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  87115. /**
  87116. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  87117. */
  87118. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  87119. __extends(StereoscopicArcRotateCamera, _super);
  87120. /**
  87121. * Creates a new StereoscopicArcRotateCamera
  87122. * @param name defines camera name
  87123. * @param alpha defines alpha angle (in radians)
  87124. * @param beta defines beta angle (in radians)
  87125. * @param radius defines radius
  87126. * @param target defines camera target
  87127. * @param interaxialDistance defines distance between each color axis
  87128. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87129. * @param scene defines the hosting scene
  87130. */
  87131. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  87132. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87133. _this.interaxialDistance = interaxialDistance;
  87134. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87135. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87136. return _this;
  87137. }
  87138. /**
  87139. * Gets camera class name
  87140. * @returns StereoscopicArcRotateCamera
  87141. */
  87142. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  87143. return "StereoscopicArcRotateCamera";
  87144. };
  87145. return StereoscopicArcRotateCamera;
  87146. }(BABYLON.ArcRotateCamera));
  87147. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  87148. /**
  87149. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  87150. */
  87151. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  87152. __extends(StereoscopicGamepadCamera, _super);
  87153. /**
  87154. * Creates a new StereoscopicGamepadCamera
  87155. * @param name defines camera name
  87156. * @param position defines initial position
  87157. * @param interaxialDistance defines distance between each color axis
  87158. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87159. * @param scene defines the hosting scene
  87160. */
  87161. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87162. var _this = _super.call(this, name, position, scene) || this;
  87163. _this.interaxialDistance = interaxialDistance;
  87164. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87165. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87166. return _this;
  87167. }
  87168. /**
  87169. * Gets camera class name
  87170. * @returns StereoscopicGamepadCamera
  87171. */
  87172. StereoscopicGamepadCamera.prototype.getClassName = function () {
  87173. return "StereoscopicGamepadCamera";
  87174. };
  87175. return StereoscopicGamepadCamera;
  87176. }(BABYLON.GamepadCamera));
  87177. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  87178. /**
  87179. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  87180. */
  87181. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  87182. __extends(StereoscopicUniversalCamera, _super);
  87183. /**
  87184. * Creates a new StereoscopicUniversalCamera
  87185. * @param name defines camera name
  87186. * @param position defines initial position
  87187. * @param interaxialDistance defines distance between each color axis
  87188. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87189. * @param scene defines the hosting scene
  87190. */
  87191. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87192. var _this = _super.call(this, name, position, scene) || this;
  87193. _this.interaxialDistance = interaxialDistance;
  87194. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87195. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87196. return _this;
  87197. }
  87198. /**
  87199. * Gets camera class name
  87200. * @returns StereoscopicUniversalCamera
  87201. */
  87202. StereoscopicUniversalCamera.prototype.getClassName = function () {
  87203. return "StereoscopicUniversalCamera";
  87204. };
  87205. return StereoscopicUniversalCamera;
  87206. }(BABYLON.UniversalCamera));
  87207. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  87208. })(BABYLON || (BABYLON = {}));
  87209. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  87210. var BABYLON;
  87211. (function (BABYLON) {
  87212. var VRExperienceHelperGazer = /** @class */ (function () {
  87213. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  87214. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  87215. this.scene = scene;
  87216. this._pointerDownOnMeshAsked = false;
  87217. this._isActionableMesh = false;
  87218. this._teleportationRequestInitiated = false;
  87219. this._teleportationBackRequestInitiated = false;
  87220. this._dpadPressed = true;
  87221. this._activePointer = false;
  87222. this._id = VRExperienceHelperGazer._idCounter++;
  87223. // Gaze tracker
  87224. if (!gazeTrackerToClone) {
  87225. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  87226. this._gazeTracker.bakeCurrentTransformIntoVertices();
  87227. this._gazeTracker.isPickable = false;
  87228. this._gazeTracker.isVisible = false;
  87229. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  87230. targetMat.specularColor = BABYLON.Color3.Black();
  87231. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87232. targetMat.backFaceCulling = false;
  87233. this._gazeTracker.material = targetMat;
  87234. }
  87235. else {
  87236. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  87237. }
  87238. }
  87239. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  87240. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  87241. };
  87242. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  87243. this._pointerDownOnMeshAsked = true;
  87244. if (this._currentMeshSelected && this._currentHit) {
  87245. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  87246. }
  87247. };
  87248. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  87249. if (this._currentMeshSelected && this._currentHit) {
  87250. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  87251. }
  87252. this._pointerDownOnMeshAsked = false;
  87253. };
  87254. VRExperienceHelperGazer.prototype._activatePointer = function () {
  87255. this._activePointer = true;
  87256. };
  87257. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  87258. this._activePointer = false;
  87259. };
  87260. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  87261. };
  87262. VRExperienceHelperGazer.prototype.dispose = function () {
  87263. this._interactionsEnabled = false;
  87264. this._teleportationEnabled = false;
  87265. };
  87266. VRExperienceHelperGazer._idCounter = 0;
  87267. return VRExperienceHelperGazer;
  87268. }());
  87269. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  87270. __extends(VRExperienceHelperControllerGazer, _super);
  87271. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  87272. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  87273. _this.webVRController = webVRController;
  87274. // Laser pointer
  87275. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  87276. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  87277. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87278. laserPointerMaterial.alpha = 0.6;
  87279. _this._laserPointer.material = laserPointerMaterial;
  87280. _this._laserPointer.rotation.x = Math.PI / 2;
  87281. _this._laserPointer.position.z = -0.5;
  87282. _this._laserPointer.isVisible = false;
  87283. if (!webVRController.mesh) {
  87284. // Create an empty mesh that is used prior to loading the high quality model
  87285. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  87286. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  87287. preloadPointerPose.rotation.x = -0.7;
  87288. preloadMesh.addChild(preloadPointerPose);
  87289. webVRController.attachToMesh(preloadMesh);
  87290. }
  87291. _this._setLaserPointerParent(webVRController.mesh);
  87292. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  87293. _this._setLaserPointerParent(mesh);
  87294. });
  87295. return _this;
  87296. }
  87297. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  87298. return this.webVRController.getForwardRay(length);
  87299. };
  87300. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  87301. _super.prototype._activatePointer.call(this);
  87302. this._laserPointer.isVisible = true;
  87303. };
  87304. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  87305. _super.prototype._deactivatePointer.call(this);
  87306. this._laserPointer.isVisible = false;
  87307. };
  87308. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  87309. this._laserPointer.material.emissiveColor = color;
  87310. };
  87311. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  87312. var makeNotPick = function (root) {
  87313. root.name += " laserPointer";
  87314. root.getChildMeshes().forEach(function (c) {
  87315. makeNotPick(c);
  87316. });
  87317. };
  87318. makeNotPick(mesh);
  87319. var childMeshes = mesh.getChildMeshes();
  87320. this.webVRController._pointingPoseNode = null;
  87321. for (var i = 0; i < childMeshes.length; i++) {
  87322. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  87323. mesh = childMeshes[i];
  87324. this.webVRController._pointingPoseNode = mesh;
  87325. break;
  87326. }
  87327. }
  87328. this._laserPointer.parent = mesh;
  87329. };
  87330. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  87331. this._laserPointer.scaling.y = distance;
  87332. this._laserPointer.position.z = -distance / 2;
  87333. };
  87334. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  87335. _super.prototype.dispose.call(this);
  87336. this._laserPointer.dispose();
  87337. if (this._meshAttachedObserver) {
  87338. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  87339. }
  87340. };
  87341. return VRExperienceHelperControllerGazer;
  87342. }(VRExperienceHelperGazer));
  87343. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  87344. __extends(VRExperienceHelperCameraGazer, _super);
  87345. function VRExperienceHelperCameraGazer(getCamera, scene) {
  87346. var _this = _super.call(this, scene) || this;
  87347. _this.getCamera = getCamera;
  87348. return _this;
  87349. }
  87350. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  87351. var camera = this.getCamera();
  87352. if (camera) {
  87353. return camera.getForwardRay(length);
  87354. }
  87355. else {
  87356. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  87357. }
  87358. };
  87359. return VRExperienceHelperCameraGazer;
  87360. }(VRExperienceHelperGazer));
  87361. /**
  87362. * Helps to quickly add VR support to an existing scene.
  87363. * See http://doc.babylonjs.com/how_to/webvr_helper
  87364. */
  87365. var VRExperienceHelper = /** @class */ (function () {
  87366. /**
  87367. * Instantiates a VRExperienceHelper.
  87368. * Helps to quickly add VR support to an existing scene.
  87369. * @param scene The scene the VRExperienceHelper belongs to.
  87370. * @param webVROptions Options to modify the vr experience helper's behavior.
  87371. */
  87372. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  87373. if (webVROptions === void 0) { webVROptions = {}; }
  87374. var _this = this;
  87375. this.webVROptions = webVROptions;
  87376. // Can the system support WebVR, even if a headset isn't plugged in?
  87377. this._webVRsupported = false;
  87378. // If WebVR is supported, is a headset plugged in and are we ready to present?
  87379. this._webVRready = false;
  87380. // Are we waiting for the requestPresent callback to complete?
  87381. this._webVRrequesting = false;
  87382. // Are we presenting to the headset right now?
  87383. this._webVRpresenting = false;
  87384. // Are we presenting in the fullscreen fallback?
  87385. this._fullscreenVRpresenting = false;
  87386. /**
  87387. * Observable raised when entering VR.
  87388. */
  87389. this.onEnteringVRObservable = new BABYLON.Observable();
  87390. /**
  87391. * Observable raised when exiting VR.
  87392. */
  87393. this.onExitingVRObservable = new BABYLON.Observable();
  87394. /**
  87395. * Observable raised when controller mesh is loaded.
  87396. */
  87397. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87398. this._useCustomVRButton = false;
  87399. this._teleportationRequested = false;
  87400. this._teleportActive = false;
  87401. this._floorMeshesCollection = [];
  87402. this._rotationAllowed = true;
  87403. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  87404. this._rotationRightAsked = false;
  87405. this._rotationLeftAsked = false;
  87406. this._isDefaultTeleportationTarget = true;
  87407. this._teleportationFillColor = "#444444";
  87408. this._teleportationBorderColor = "#FFFFFF";
  87409. this._rotationAngle = 0;
  87410. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  87411. this._padSensibilityUp = 0.65;
  87412. this._padSensibilityDown = 0.35;
  87413. this.leftController = null;
  87414. this.rightController = null;
  87415. /**
  87416. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  87417. */
  87418. this.onNewMeshSelected = new BABYLON.Observable();
  87419. /**
  87420. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  87421. */
  87422. this.onNewMeshPicked = new BABYLON.Observable();
  87423. /**
  87424. * Observable raised before camera teleportation
  87425. */
  87426. this.onBeforeCameraTeleport = new BABYLON.Observable();
  87427. /**
  87428. * Observable raised after camera teleportation
  87429. */
  87430. this.onAfterCameraTeleport = new BABYLON.Observable();
  87431. /**
  87432. * Observable raised when current selected mesh gets unselected
  87433. */
  87434. this.onSelectedMeshUnselected = new BABYLON.Observable();
  87435. /**
  87436. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  87437. */
  87438. this.teleportationEnabled = true;
  87439. this._teleportationInitialized = false;
  87440. this._interactionsEnabled = false;
  87441. this._interactionsRequested = false;
  87442. this._displayGaze = true;
  87443. this._displayLaserPointer = true;
  87444. this._onResize = function () {
  87445. _this.moveButtonToBottomRight();
  87446. if (_this._fullscreenVRpresenting && _this._webVRready) {
  87447. _this.exitVR();
  87448. }
  87449. };
  87450. this._onFullscreenChange = function () {
  87451. if (document.fullscreen !== undefined) {
  87452. _this._fullscreenVRpresenting = document.fullscreen;
  87453. }
  87454. else if (document.mozFullScreen !== undefined) {
  87455. _this._fullscreenVRpresenting = document.mozFullScreen;
  87456. }
  87457. else if (document.webkitIsFullScreen !== undefined) {
  87458. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  87459. }
  87460. else if (document.msIsFullScreen !== undefined) {
  87461. _this._fullscreenVRpresenting = document.msIsFullScreen;
  87462. }
  87463. if (!_this._fullscreenVRpresenting && _this._canvas) {
  87464. _this.exitVR();
  87465. if (!_this._useCustomVRButton) {
  87466. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  87467. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  87468. }
  87469. }
  87470. };
  87471. this.beforeRender = function () {
  87472. if (_this.leftController && _this.leftController._activePointer) {
  87473. _this._castRayAndSelectObject(_this.leftController);
  87474. }
  87475. if (_this.rightController && _this.rightController._activePointer) {
  87476. _this._castRayAndSelectObject(_this.rightController);
  87477. }
  87478. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  87479. _this._castRayAndSelectObject(_this._cameraGazer);
  87480. }
  87481. else {
  87482. _this._cameraGazer._gazeTracker.isVisible = false;
  87483. }
  87484. };
  87485. this._onNewGamepadConnected = function (gamepad) {
  87486. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  87487. if (gamepad.leftStick) {
  87488. gamepad.onleftstickchanged(function (stickValues) {
  87489. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  87490. // Listening to classic/xbox gamepad only if no VR controller is active
  87491. if ((!_this.leftController && !_this.rightController) ||
  87492. ((_this.leftController && !_this.leftController._activePointer) &&
  87493. (_this.rightController && !_this.rightController._activePointer))) {
  87494. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  87495. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  87496. }
  87497. }
  87498. });
  87499. }
  87500. if (gamepad.rightStick) {
  87501. gamepad.onrightstickchanged(function (stickValues) {
  87502. if (_this._teleportationInitialized) {
  87503. _this._checkRotate(stickValues, _this._cameraGazer);
  87504. }
  87505. });
  87506. }
  87507. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  87508. gamepad.onbuttondown(function (buttonPressed) {
  87509. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87510. _this._cameraGazer._selectionPointerDown();
  87511. }
  87512. });
  87513. gamepad.onbuttonup(function (buttonPressed) {
  87514. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87515. _this._cameraGazer._selectionPointerUp();
  87516. }
  87517. });
  87518. }
  87519. }
  87520. else {
  87521. var webVRController = gamepad;
  87522. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  87523. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  87524. _this.rightController = controller;
  87525. }
  87526. else {
  87527. _this.leftController = controller;
  87528. }
  87529. _this._tryEnableInteractionOnController(controller);
  87530. }
  87531. };
  87532. // 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
  87533. this._tryEnableInteractionOnController = function (controller) {
  87534. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  87535. _this._enableInteractionOnController(controller);
  87536. }
  87537. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  87538. _this._enableTeleportationOnController(controller);
  87539. }
  87540. };
  87541. this._onNewGamepadDisconnected = function (gamepad) {
  87542. if (gamepad instanceof BABYLON.WebVRController) {
  87543. if (gamepad.hand === "left" && _this.leftController != null) {
  87544. _this.leftController.dispose();
  87545. _this.leftController = null;
  87546. }
  87547. if (gamepad.hand === "right" && _this.rightController != null) {
  87548. _this.rightController.dispose();
  87549. _this.rightController = null;
  87550. }
  87551. }
  87552. };
  87553. this._workingVector = BABYLON.Vector3.Zero();
  87554. this._workingQuaternion = BABYLON.Quaternion.Identity();
  87555. this._workingMatrix = BABYLON.Matrix.Identity();
  87556. this._scene = scene;
  87557. this._canvas = scene.getEngine().getRenderingCanvas();
  87558. // Parse options
  87559. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  87560. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  87561. }
  87562. if (webVROptions.createDeviceOrientationCamera === undefined) {
  87563. webVROptions.createDeviceOrientationCamera = true;
  87564. }
  87565. if (webVROptions.defaultHeight === undefined) {
  87566. webVROptions.defaultHeight = 1.7;
  87567. }
  87568. if (webVROptions.useCustomVRButton) {
  87569. this._useCustomVRButton = true;
  87570. if (webVROptions.customVRButton) {
  87571. this._btnVR = webVROptions.customVRButton;
  87572. }
  87573. }
  87574. if (webVROptions.rayLength) {
  87575. this._rayLength = webVROptions.rayLength;
  87576. }
  87577. this._defaultHeight = webVROptions.defaultHeight;
  87578. if (webVROptions.positionScale) {
  87579. this._rayLength *= webVROptions.positionScale;
  87580. this._defaultHeight *= webVROptions.positionScale;
  87581. }
  87582. // Set position
  87583. if (this._scene.activeCamera) {
  87584. this._position = this._scene.activeCamera.position.clone();
  87585. }
  87586. else {
  87587. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  87588. }
  87589. // Set non-vr camera
  87590. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  87591. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  87592. // Copy data from existing camera
  87593. if (this._scene.activeCamera) {
  87594. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87595. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  87596. // Set rotation from previous camera
  87597. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  87598. var targetCamera = this._scene.activeCamera;
  87599. if (targetCamera.rotationQuaternion) {
  87600. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  87601. }
  87602. else {
  87603. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  87604. }
  87605. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  87606. }
  87607. }
  87608. this._scene.activeCamera = this._deviceOrientationCamera;
  87609. if (this._canvas) {
  87610. this._scene.activeCamera.attachControl(this._canvas);
  87611. }
  87612. }
  87613. else {
  87614. this._existingCamera = this._scene.activeCamera;
  87615. }
  87616. // Create VR cameras
  87617. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87618. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  87619. }
  87620. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  87621. this._webVRCamera.useStandingMatrix();
  87622. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  87623. // Create default button
  87624. if (!this._useCustomVRButton) {
  87625. this._btnVR = document.createElement("BUTTON");
  87626. this._btnVR.className = "babylonVRicon";
  87627. this._btnVR.id = "babylonVRiconbtn";
  87628. this._btnVR.title = "Click to switch to VR";
  87629. 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) }";
  87630. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  87631. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  87632. // css += ".babylonVRicon.vrdisplaysupported { }";
  87633. // css += ".babylonVRicon.vrdisplayready { }";
  87634. // css += ".babylonVRicon.vrdisplayrequesting { }";
  87635. var style = document.createElement('style');
  87636. style.appendChild(document.createTextNode(css));
  87637. document.getElementsByTagName('head')[0].appendChild(style);
  87638. this.moveButtonToBottomRight();
  87639. }
  87640. // VR button click event
  87641. if (this._btnVR) {
  87642. this._btnVR.addEventListener("click", function () {
  87643. if (!_this.isInVRMode) {
  87644. _this.enterVR();
  87645. }
  87646. else {
  87647. _this.exitVR();
  87648. }
  87649. });
  87650. }
  87651. // Window events
  87652. window.addEventListener("resize", this._onResize);
  87653. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  87654. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  87655. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  87656. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  87657. // Display vr button when headset is connected
  87658. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87659. this.displayVRButton();
  87660. }
  87661. else {
  87662. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  87663. if (e.vrDisplay) {
  87664. _this.displayVRButton();
  87665. }
  87666. });
  87667. }
  87668. // Exiting VR mode using 'ESC' key on desktop
  87669. this._onKeyDown = function (event) {
  87670. if (event.keyCode === 27 && _this.isInVRMode) {
  87671. _this.exitVR();
  87672. }
  87673. };
  87674. document.addEventListener("keydown", this._onKeyDown);
  87675. // Exiting VR mode double tapping the touch screen
  87676. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  87677. if (_this.isInVRMode) {
  87678. _this.exitVR();
  87679. if (_this._fullscreenVRpresenting) {
  87680. _this._scene.getEngine().switchFullscreen(true);
  87681. }
  87682. }
  87683. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  87684. // Listen for WebVR display changes
  87685. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  87686. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  87687. this._onVRRequestPresentStart = function () {
  87688. _this._webVRrequesting = true;
  87689. _this.updateButtonVisibility();
  87690. };
  87691. this._onVRRequestPresentComplete = function (success) {
  87692. _this._webVRrequesting = false;
  87693. _this.updateButtonVisibility();
  87694. };
  87695. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  87696. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  87697. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  87698. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87699. scene.onDisposeObservable.add(function () {
  87700. _this.dispose();
  87701. });
  87702. // Gamepad connection events
  87703. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  87704. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  87705. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  87706. this.updateButtonVisibility();
  87707. //create easing functions
  87708. this._circleEase = new BABYLON.CircleEase();
  87709. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87710. }
  87711. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  87712. /** Return this.onEnteringVRObservable
  87713. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  87714. */
  87715. get: function () {
  87716. return this.onEnteringVRObservable;
  87717. },
  87718. enumerable: true,
  87719. configurable: true
  87720. });
  87721. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  87722. /** Return this.onExitingVRObservable
  87723. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  87724. */
  87725. get: function () {
  87726. return this.onExitingVRObservable;
  87727. },
  87728. enumerable: true,
  87729. configurable: true
  87730. });
  87731. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  87732. /** Return this.onControllerMeshLoadedObservable
  87733. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  87734. */
  87735. get: function () {
  87736. return this.onControllerMeshLoadedObservable;
  87737. },
  87738. enumerable: true,
  87739. configurable: true
  87740. });
  87741. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  87742. /**
  87743. * The mesh used to display where the user is going to teleport.
  87744. */
  87745. get: function () {
  87746. return this._teleportationTarget;
  87747. },
  87748. /**
  87749. * Sets the mesh to be used to display where the user is going to teleport.
  87750. */
  87751. set: function (value) {
  87752. if (value) {
  87753. value.name = "teleportationTarget";
  87754. this._isDefaultTeleportationTarget = false;
  87755. this._teleportationTarget = value;
  87756. }
  87757. },
  87758. enumerable: true,
  87759. configurable: true
  87760. });
  87761. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  87762. /**
  87763. * The mesh used to display where the user is selecting,
  87764. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  87765. * See http://doc.babylonjs.com/resources/baking_transformations
  87766. */
  87767. get: function () {
  87768. return this._cameraGazer._gazeTracker;
  87769. },
  87770. set: function (value) {
  87771. if (value) {
  87772. this._cameraGazer._gazeTracker = value;
  87773. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  87774. this._cameraGazer._gazeTracker.isPickable = false;
  87775. this._cameraGazer._gazeTracker.isVisible = false;
  87776. this._cameraGazer._gazeTracker.name = "gazeTracker";
  87777. if (this.leftController) {
  87778. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87779. }
  87780. if (this.rightController) {
  87781. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87782. }
  87783. }
  87784. },
  87785. enumerable: true,
  87786. configurable: true
  87787. });
  87788. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  87789. /**
  87790. * If the ray of the gaze should be displayed.
  87791. */
  87792. get: function () {
  87793. return this._displayGaze;
  87794. },
  87795. /**
  87796. * Sets if the ray of the gaze should be displayed.
  87797. */
  87798. set: function (value) {
  87799. this._displayGaze = value;
  87800. if (!value) {
  87801. this._cameraGazer._gazeTracker.isVisible = false;
  87802. if (this.leftController) {
  87803. this.leftController._gazeTracker.isVisible = false;
  87804. }
  87805. if (this.rightController) {
  87806. this.rightController._gazeTracker.isVisible = false;
  87807. }
  87808. }
  87809. },
  87810. enumerable: true,
  87811. configurable: true
  87812. });
  87813. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  87814. /**
  87815. * If the ray of the LaserPointer should be displayed.
  87816. */
  87817. get: function () {
  87818. return this._displayLaserPointer;
  87819. },
  87820. /**
  87821. * Sets if the ray of the LaserPointer should be displayed.
  87822. */
  87823. set: function (value) {
  87824. this._displayLaserPointer = value;
  87825. if (!value) {
  87826. if (this.rightController) {
  87827. this.rightController._deactivatePointer();
  87828. this.rightController._gazeTracker.isVisible = false;
  87829. }
  87830. if (this.leftController) {
  87831. this.leftController._deactivatePointer();
  87832. this.leftController._gazeTracker.isVisible = false;
  87833. }
  87834. }
  87835. else {
  87836. if (this.rightController) {
  87837. this.rightController._activatePointer();
  87838. }
  87839. else if (this.leftController) {
  87840. this.leftController._activatePointer();
  87841. }
  87842. }
  87843. },
  87844. enumerable: true,
  87845. configurable: true
  87846. });
  87847. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  87848. /**
  87849. * The deviceOrientationCamera used as the camera when not in VR.
  87850. */
  87851. get: function () {
  87852. return this._deviceOrientationCamera;
  87853. },
  87854. enumerable: true,
  87855. configurable: true
  87856. });
  87857. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  87858. /**
  87859. * Based on the current WebVR support, returns the current VR camera used.
  87860. */
  87861. get: function () {
  87862. if (this._webVRready) {
  87863. return this._webVRCamera;
  87864. }
  87865. else {
  87866. return this._scene.activeCamera;
  87867. }
  87868. },
  87869. enumerable: true,
  87870. configurable: true
  87871. });
  87872. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  87873. /**
  87874. * The webVRCamera which is used when in VR.
  87875. */
  87876. get: function () {
  87877. return this._webVRCamera;
  87878. },
  87879. enumerable: true,
  87880. configurable: true
  87881. });
  87882. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  87883. /**
  87884. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  87885. */
  87886. get: function () {
  87887. return this._vrDeviceOrientationCamera;
  87888. },
  87889. enumerable: true,
  87890. configurable: true
  87891. });
  87892. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  87893. get: function () {
  87894. var result = this._cameraGazer._teleportationRequestInitiated
  87895. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  87896. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  87897. return result;
  87898. },
  87899. enumerable: true,
  87900. configurable: true
  87901. });
  87902. // Raised when one of the controller has loaded successfully its associated default mesh
  87903. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  87904. if (this.leftController && this.leftController.webVRController == webVRController) {
  87905. if (webVRController.mesh) {
  87906. this.leftController._setLaserPointerParent(webVRController.mesh);
  87907. }
  87908. }
  87909. if (this.rightController && this.rightController.webVRController == webVRController) {
  87910. if (webVRController.mesh) {
  87911. this.rightController._setLaserPointerParent(webVRController.mesh);
  87912. }
  87913. }
  87914. try {
  87915. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  87916. }
  87917. catch (err) {
  87918. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  87919. }
  87920. };
  87921. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  87922. /**
  87923. * Gets a value indicating if we are currently in VR mode.
  87924. */
  87925. get: function () {
  87926. return this._webVRpresenting || this._fullscreenVRpresenting;
  87927. },
  87928. enumerable: true,
  87929. configurable: true
  87930. });
  87931. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  87932. var vrDisplay = this._scene.getEngine().getVRDevice();
  87933. if (vrDisplay) {
  87934. var wasPresenting = this._webVRpresenting;
  87935. // A VR display is connected
  87936. this._webVRpresenting = vrDisplay.isPresenting;
  87937. if (wasPresenting && !this._webVRpresenting)
  87938. this.exitVR();
  87939. }
  87940. else {
  87941. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  87942. }
  87943. this.updateButtonVisibility();
  87944. };
  87945. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  87946. this._webVRsupported = eventArgs.vrSupported;
  87947. this._webVRready = !!eventArgs.vrDisplay;
  87948. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  87949. this.updateButtonVisibility();
  87950. };
  87951. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  87952. if (this._canvas && !this._useCustomVRButton) {
  87953. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  87954. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  87955. }
  87956. };
  87957. VRExperienceHelper.prototype.displayVRButton = function () {
  87958. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  87959. document.body.appendChild(this._btnVR);
  87960. this._btnVRDisplayed = true;
  87961. }
  87962. };
  87963. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  87964. if (!this._btnVR || this._useCustomVRButton) {
  87965. return;
  87966. }
  87967. this._btnVR.className = "babylonVRicon";
  87968. if (this.isInVRMode) {
  87969. this._btnVR.className += " vrdisplaypresenting";
  87970. }
  87971. else {
  87972. if (this._webVRready)
  87973. this._btnVR.className += " vrdisplayready";
  87974. if (this._webVRsupported)
  87975. this._btnVR.className += " vrdisplaysupported";
  87976. if (this._webVRrequesting)
  87977. this._btnVR.className += " vrdisplayrequesting";
  87978. }
  87979. };
  87980. /**
  87981. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  87982. * Otherwise, will use the fullscreen API.
  87983. */
  87984. VRExperienceHelper.prototype.enterVR = function () {
  87985. if (this.onEnteringVRObservable) {
  87986. try {
  87987. this.onEnteringVRObservable.notifyObservers(this);
  87988. }
  87989. catch (err) {
  87990. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  87991. }
  87992. }
  87993. if (this._scene.activeCamera) {
  87994. this._position = this._scene.activeCamera.position.clone();
  87995. // make sure that we return to the last active camera
  87996. this._existingCamera = this._scene.activeCamera;
  87997. }
  87998. if (this._webVRrequesting)
  87999. return;
  88000. // If WebVR is supported and a headset is connected
  88001. if (this._webVRready) {
  88002. if (!this._webVRpresenting) {
  88003. this._webVRCamera.position = this._position;
  88004. this._scene.activeCamera = this._webVRCamera;
  88005. }
  88006. }
  88007. else if (this._vrDeviceOrientationCamera) {
  88008. this._vrDeviceOrientationCamera.position = this._position;
  88009. if (this._scene.activeCamera) {
  88010. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88011. }
  88012. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  88013. this._scene.getEngine().switchFullscreen(true);
  88014. this.updateButtonVisibility();
  88015. }
  88016. if (this._scene.activeCamera && this._canvas) {
  88017. this._scene.activeCamera.attachControl(this._canvas);
  88018. }
  88019. if (this._interactionsEnabled) {
  88020. this._scene.registerBeforeRender(this.beforeRender);
  88021. }
  88022. };
  88023. /**
  88024. * Attempt to exit VR, or fullscreen.
  88025. */
  88026. VRExperienceHelper.prototype.exitVR = function () {
  88027. if (this.onExitingVRObservable) {
  88028. try {
  88029. this.onExitingVRObservable.notifyObservers(this);
  88030. }
  88031. catch (err) {
  88032. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  88033. }
  88034. }
  88035. if (this._webVRpresenting) {
  88036. this._scene.getEngine().disableVR();
  88037. }
  88038. if (this._scene.activeCamera) {
  88039. this._position = this._scene.activeCamera.position.clone();
  88040. }
  88041. if (this._deviceOrientationCamera) {
  88042. this._deviceOrientationCamera.position = this._position;
  88043. this._scene.activeCamera = this._deviceOrientationCamera;
  88044. if (this._canvas) {
  88045. this._scene.activeCamera.attachControl(this._canvas);
  88046. }
  88047. }
  88048. else if (this._existingCamera) {
  88049. this._existingCamera.position = this._position;
  88050. this._scene.activeCamera = this._existingCamera;
  88051. }
  88052. this.updateButtonVisibility();
  88053. if (this._interactionsEnabled) {
  88054. this._scene.unregisterBeforeRender(this.beforeRender);
  88055. }
  88056. // resize to update width and height when exiting vr exits fullscreen
  88057. this._scene.getEngine().resize();
  88058. };
  88059. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  88060. /**
  88061. * The position of the vr experience helper.
  88062. */
  88063. get: function () {
  88064. return this._position;
  88065. },
  88066. /**
  88067. * Sets the position of the vr experience helper.
  88068. */
  88069. set: function (value) {
  88070. this._position = value;
  88071. if (this._scene.activeCamera) {
  88072. this._scene.activeCamera.position = value;
  88073. }
  88074. },
  88075. enumerable: true,
  88076. configurable: true
  88077. });
  88078. /**
  88079. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  88080. */
  88081. VRExperienceHelper.prototype.enableInteractions = function () {
  88082. var _this = this;
  88083. if (!this._interactionsEnabled) {
  88084. this._interactionsRequested = true;
  88085. if (this.leftController) {
  88086. this._enableInteractionOnController(this.leftController);
  88087. }
  88088. if (this.rightController) {
  88089. this._enableInteractionOnController(this.rightController);
  88090. }
  88091. this.raySelectionPredicate = function (mesh) {
  88092. return mesh.isVisible;
  88093. };
  88094. this.meshSelectionPredicate = function (mesh) {
  88095. return true;
  88096. };
  88097. this._raySelectionPredicate = function (mesh) {
  88098. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  88099. && mesh.name.indexOf("teleportationTarget") === -1
  88100. && mesh.name.indexOf("torusTeleportation") === -1
  88101. && mesh.name.indexOf("laserPointer") === -1)) {
  88102. return _this.raySelectionPredicate(mesh);
  88103. }
  88104. return false;
  88105. };
  88106. this._interactionsEnabled = true;
  88107. }
  88108. };
  88109. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  88110. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  88111. if (this._floorMeshesCollection[i].id === mesh.id) {
  88112. return true;
  88113. }
  88114. }
  88115. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  88116. return true;
  88117. }
  88118. return false;
  88119. };
  88120. /**
  88121. * Adds a floor mesh to be used for teleportation.
  88122. * @param floorMesh the mesh to be used for teleportation.
  88123. */
  88124. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  88125. if (!this._floorMeshesCollection) {
  88126. return;
  88127. }
  88128. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  88129. return;
  88130. }
  88131. this._floorMeshesCollection.push(floorMesh);
  88132. };
  88133. /**
  88134. * Removes a floor mesh from being used for teleportation.
  88135. * @param floorMesh the mesh to be removed.
  88136. */
  88137. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  88138. if (!this._floorMeshesCollection) {
  88139. return;
  88140. }
  88141. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  88142. if (meshIndex !== -1) {
  88143. this._floorMeshesCollection.splice(meshIndex, 1);
  88144. }
  88145. };
  88146. /**
  88147. * Enables interactions and teleportation using the VR controllers and gaze.
  88148. * @param vrTeleportationOptions options to modify teleportation behavior.
  88149. */
  88150. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  88151. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  88152. if (!this._teleportationInitialized) {
  88153. this._teleportationRequested = true;
  88154. this.enableInteractions();
  88155. if (vrTeleportationOptions.floorMeshName) {
  88156. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  88157. }
  88158. if (vrTeleportationOptions.floorMeshes) {
  88159. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  88160. }
  88161. if (this.leftController != null) {
  88162. this._enableTeleportationOnController(this.leftController);
  88163. }
  88164. if (this.rightController != null) {
  88165. this._enableTeleportationOnController(this.rightController);
  88166. }
  88167. // Creates an image processing post process for the vignette not relying
  88168. // on the main scene configuration for image processing to reduce setup and spaces
  88169. // (gamma/linear) conflicts.
  88170. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  88171. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88172. imageProcessingConfiguration.vignetteEnabled = true;
  88173. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  88174. this._webVRCamera.detachPostProcess(this._postProcessMove);
  88175. this._teleportationInitialized = true;
  88176. if (this._isDefaultTeleportationTarget) {
  88177. this._createTeleportationCircles();
  88178. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  88179. }
  88180. }
  88181. };
  88182. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  88183. var _this = this;
  88184. var controllerMesh = controller.webVRController.mesh;
  88185. if (controllerMesh) {
  88186. controller._interactionsEnabled = true;
  88187. controller._activatePointer();
  88188. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  88189. // Enabling / disabling laserPointer
  88190. if (_this._displayLaserPointer && stateObject.value === 1) {
  88191. if (controller._activePointer) {
  88192. controller._deactivatePointer();
  88193. }
  88194. else {
  88195. controller._activatePointer();
  88196. }
  88197. if (_this.displayGaze) {
  88198. controller._gazeTracker.isVisible = controller._activePointer;
  88199. }
  88200. }
  88201. });
  88202. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  88203. if (!controller._pointerDownOnMeshAsked) {
  88204. if (stateObject.value > _this._padSensibilityUp) {
  88205. controller._selectionPointerDown();
  88206. }
  88207. }
  88208. else if (stateObject.value < _this._padSensibilityDown) {
  88209. controller._selectionPointerUp();
  88210. }
  88211. });
  88212. }
  88213. };
  88214. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  88215. // Dont teleport if another gaze already requested teleportation
  88216. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  88217. return;
  88218. }
  88219. if (!gazer._teleportationRequestInitiated) {
  88220. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  88221. gazer._activatePointer();
  88222. gazer._teleportationRequestInitiated = true;
  88223. }
  88224. }
  88225. else {
  88226. // Listening to the proper controller values changes to confirm teleportation
  88227. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  88228. if (this._teleportActive) {
  88229. this._teleportCamera(this._haloCenter);
  88230. }
  88231. gazer._teleportationRequestInitiated = false;
  88232. }
  88233. }
  88234. };
  88235. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  88236. // Only rotate when user is not currently selecting a teleportation location
  88237. if (gazer._teleportationRequestInitiated) {
  88238. return;
  88239. }
  88240. if (!this._rotationLeftAsked) {
  88241. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  88242. this._rotationLeftAsked = true;
  88243. if (this._rotationAllowed) {
  88244. this._rotateCamera(false);
  88245. }
  88246. }
  88247. }
  88248. else {
  88249. if (stateObject.x > -this._padSensibilityDown) {
  88250. this._rotationLeftAsked = false;
  88251. }
  88252. }
  88253. if (!this._rotationRightAsked) {
  88254. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  88255. this._rotationRightAsked = true;
  88256. if (this._rotationAllowed) {
  88257. this._rotateCamera(true);
  88258. }
  88259. }
  88260. }
  88261. else {
  88262. if (stateObject.x < this._padSensibilityDown) {
  88263. this._rotationRightAsked = false;
  88264. }
  88265. }
  88266. };
  88267. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  88268. // Only teleport backwards when user is not currently selecting a teleportation location
  88269. if (gazer._teleportationRequestInitiated) {
  88270. return;
  88271. }
  88272. // Teleport backwards
  88273. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  88274. if (!gazer._teleportationBackRequestInitiated) {
  88275. if (!this.currentVRCamera) {
  88276. return;
  88277. }
  88278. // Get rotation and position of the current camera
  88279. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  88280. var position = this.currentVRCamera.position;
  88281. // If the camera has device position, use that instead
  88282. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  88283. rotation = this.currentVRCamera.deviceRotationQuaternion;
  88284. position = this.currentVRCamera.devicePosition;
  88285. }
  88286. // Get matrix with only the y rotation of the device rotation
  88287. rotation.toEulerAnglesToRef(this._workingVector);
  88288. this._workingVector.z = 0;
  88289. this._workingVector.x = 0;
  88290. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  88291. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  88292. // Rotate backwards ray by device rotation to cast at the ground behind the user
  88293. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  88294. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  88295. var ray = new BABYLON.Ray(position, this._workingVector);
  88296. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88297. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  88298. this._teleportCamera(hit.pickedPoint);
  88299. }
  88300. gazer._teleportationBackRequestInitiated = true;
  88301. }
  88302. }
  88303. else {
  88304. gazer._teleportationBackRequestInitiated = false;
  88305. }
  88306. };
  88307. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  88308. var _this = this;
  88309. var controllerMesh = controller.webVRController.mesh;
  88310. if (controllerMesh) {
  88311. if (!controller._interactionsEnabled) {
  88312. this._enableInteractionOnController(controller);
  88313. }
  88314. controller._interactionsEnabled = true;
  88315. controller._teleportationEnabled = true;
  88316. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  88317. controller._dpadPressed = false;
  88318. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  88319. controller._dpadPressed = stateObject.pressed;
  88320. if (!controller._dpadPressed) {
  88321. _this._rotationLeftAsked = false;
  88322. _this._rotationRightAsked = false;
  88323. controller._teleportationBackRequestInitiated = false;
  88324. }
  88325. });
  88326. }
  88327. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  88328. if (_this.teleportationEnabled) {
  88329. _this._checkTeleportBackwards(stateObject, controller);
  88330. _this._checkTeleportWithRay(stateObject, controller);
  88331. }
  88332. _this._checkRotate(stateObject, controller);
  88333. });
  88334. }
  88335. };
  88336. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  88337. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  88338. this._teleportationTarget.isPickable = false;
  88339. var length = 512;
  88340. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  88341. dynamicTexture.hasAlpha = true;
  88342. var context = dynamicTexture.getContext();
  88343. var centerX = length / 2;
  88344. var centerY = length / 2;
  88345. var radius = 200;
  88346. context.beginPath();
  88347. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  88348. context.fillStyle = this._teleportationFillColor;
  88349. context.fill();
  88350. context.lineWidth = 10;
  88351. context.strokeStyle = this._teleportationBorderColor;
  88352. context.stroke();
  88353. context.closePath();
  88354. dynamicTexture.update();
  88355. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  88356. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  88357. this._teleportationTarget.material = teleportationCircleMaterial;
  88358. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  88359. torus.isPickable = false;
  88360. torus.parent = this._teleportationTarget;
  88361. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88362. var keys = [];
  88363. keys.push({
  88364. frame: 0,
  88365. value: 0
  88366. });
  88367. keys.push({
  88368. frame: 30,
  88369. value: 0.4
  88370. });
  88371. keys.push({
  88372. frame: 60,
  88373. value: 0
  88374. });
  88375. animationInnerCircle.setKeys(keys);
  88376. var easingFunction = new BABYLON.SineEase();
  88377. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88378. animationInnerCircle.setEasingFunction(easingFunction);
  88379. torus.animations = [];
  88380. torus.animations.push(animationInnerCircle);
  88381. this._scene.beginAnimation(torus, 0, 60, true);
  88382. this._hideTeleportationTarget();
  88383. };
  88384. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  88385. this._teleportActive = true;
  88386. if (this._teleportationInitialized) {
  88387. this._teleportationTarget.isVisible = true;
  88388. if (this._isDefaultTeleportationTarget) {
  88389. this._teleportationTarget.getChildren()[0].isVisible = true;
  88390. }
  88391. }
  88392. };
  88393. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  88394. this._teleportActive = false;
  88395. if (this._teleportationInitialized) {
  88396. this._teleportationTarget.isVisible = false;
  88397. if (this._isDefaultTeleportationTarget) {
  88398. this._teleportationTarget.getChildren()[0].isVisible = false;
  88399. }
  88400. }
  88401. };
  88402. VRExperienceHelper.prototype._rotateCamera = function (right) {
  88403. var _this = this;
  88404. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88405. return;
  88406. }
  88407. if (right) {
  88408. this._rotationAngle++;
  88409. }
  88410. else {
  88411. this._rotationAngle--;
  88412. }
  88413. this.currentVRCamera.animations = [];
  88414. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  88415. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88416. var animationRotationKeys = [];
  88417. animationRotationKeys.push({
  88418. frame: 0,
  88419. value: this.currentVRCamera.rotationQuaternion
  88420. });
  88421. animationRotationKeys.push({
  88422. frame: 6,
  88423. value: target
  88424. });
  88425. animationRotation.setKeys(animationRotationKeys);
  88426. animationRotation.setEasingFunction(this._circleEase);
  88427. this.currentVRCamera.animations.push(animationRotation);
  88428. this._postProcessMove.animations = [];
  88429. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88430. var vignetteWeightKeys = [];
  88431. vignetteWeightKeys.push({
  88432. frame: 0,
  88433. value: 0
  88434. });
  88435. vignetteWeightKeys.push({
  88436. frame: 3,
  88437. value: 4
  88438. });
  88439. vignetteWeightKeys.push({
  88440. frame: 6,
  88441. value: 0
  88442. });
  88443. animationPP.setKeys(vignetteWeightKeys);
  88444. animationPP.setEasingFunction(this._circleEase);
  88445. this._postProcessMove.animations.push(animationPP);
  88446. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88447. var vignetteStretchKeys = [];
  88448. vignetteStretchKeys.push({
  88449. frame: 0,
  88450. value: 0
  88451. });
  88452. vignetteStretchKeys.push({
  88453. frame: 3,
  88454. value: 10
  88455. });
  88456. vignetteStretchKeys.push({
  88457. frame: 6,
  88458. value: 0
  88459. });
  88460. animationPP2.setKeys(vignetteStretchKeys);
  88461. animationPP2.setEasingFunction(this._circleEase);
  88462. this._postProcessMove.animations.push(animationPP2);
  88463. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88464. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88465. this._postProcessMove.samples = 4;
  88466. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88467. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  88468. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88469. });
  88470. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  88471. };
  88472. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  88473. if (hit.pickedPoint) {
  88474. if (gazer._teleportationRequestInitiated) {
  88475. this._displayTeleportationTarget();
  88476. this._haloCenter.copyFrom(hit.pickedPoint);
  88477. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  88478. }
  88479. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  88480. if (pickNormal) {
  88481. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88482. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88483. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  88484. }
  88485. this._teleportationTarget.position.y += 0.1;
  88486. }
  88487. };
  88488. VRExperienceHelper.prototype._teleportCamera = function (location) {
  88489. var _this = this;
  88490. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88491. return;
  88492. }
  88493. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  88494. // offset of the headset from the anchor.
  88495. if (this.webVRCamera.leftCamera) {
  88496. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  88497. this._workingVector.subtractInPlace(this.webVRCamera.position);
  88498. location.subtractToRef(this._workingVector, this._workingVector);
  88499. }
  88500. else {
  88501. this._workingVector.copyFrom(location);
  88502. }
  88503. // Add height to account for user's height offset
  88504. if (this.isInVRMode) {
  88505. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  88506. }
  88507. else {
  88508. this._workingVector.y += this._defaultHeight;
  88509. }
  88510. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  88511. // Create animation from the camera's position to the new location
  88512. this.currentVRCamera.animations = [];
  88513. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88514. var animationCameraTeleportationKeys = [{
  88515. frame: 0,
  88516. value: this.currentVRCamera.position
  88517. },
  88518. {
  88519. frame: 11,
  88520. value: this._workingVector
  88521. }
  88522. ];
  88523. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  88524. animationCameraTeleportation.setEasingFunction(this._circleEase);
  88525. this.currentVRCamera.animations.push(animationCameraTeleportation);
  88526. this._postProcessMove.animations = [];
  88527. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88528. var vignetteWeightKeys = [];
  88529. vignetteWeightKeys.push({
  88530. frame: 0,
  88531. value: 0
  88532. });
  88533. vignetteWeightKeys.push({
  88534. frame: 5,
  88535. value: 8
  88536. });
  88537. vignetteWeightKeys.push({
  88538. frame: 11,
  88539. value: 0
  88540. });
  88541. animationPP.setKeys(vignetteWeightKeys);
  88542. this._postProcessMove.animations.push(animationPP);
  88543. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88544. var vignetteStretchKeys = [];
  88545. vignetteStretchKeys.push({
  88546. frame: 0,
  88547. value: 0
  88548. });
  88549. vignetteStretchKeys.push({
  88550. frame: 5,
  88551. value: 10
  88552. });
  88553. vignetteStretchKeys.push({
  88554. frame: 11,
  88555. value: 0
  88556. });
  88557. animationPP2.setKeys(vignetteStretchKeys);
  88558. this._postProcessMove.animations.push(animationPP2);
  88559. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88560. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88561. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88562. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  88563. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88564. });
  88565. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  88566. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  88567. });
  88568. this._hideTeleportationTarget();
  88569. };
  88570. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  88571. if (normal) {
  88572. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  88573. if (angle < Math.PI / 2) {
  88574. normal.scaleInPlace(-1);
  88575. }
  88576. }
  88577. return normal;
  88578. };
  88579. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  88580. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88581. return;
  88582. }
  88583. var ray = gazer._getForwardRay(this._rayLength);
  88584. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88585. // Moving the gazeTracker on the mesh face targetted
  88586. if (hit && hit.pickedPoint) {
  88587. if (this._displayGaze) {
  88588. var multiplier = 1;
  88589. gazer._gazeTracker.isVisible = true;
  88590. if (gazer._isActionableMesh) {
  88591. multiplier = 3;
  88592. }
  88593. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  88594. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  88595. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  88596. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  88597. // To avoid z-fighting
  88598. var deltaFighting = 0.002;
  88599. if (pickNormal) {
  88600. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88601. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88602. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  88603. }
  88604. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  88605. if (gazer._gazeTracker.position.x < 0) {
  88606. gazer._gazeTracker.position.x += deltaFighting;
  88607. }
  88608. else {
  88609. gazer._gazeTracker.position.x -= deltaFighting;
  88610. }
  88611. if (gazer._gazeTracker.position.y < 0) {
  88612. gazer._gazeTracker.position.y += deltaFighting;
  88613. }
  88614. else {
  88615. gazer._gazeTracker.position.y -= deltaFighting;
  88616. }
  88617. if (gazer._gazeTracker.position.z < 0) {
  88618. gazer._gazeTracker.position.z += deltaFighting;
  88619. }
  88620. else {
  88621. gazer._gazeTracker.position.z -= deltaFighting;
  88622. }
  88623. }
  88624. // Changing the size of the laser pointer based on the distance from the targetted point
  88625. gazer._updatePointerDistance(hit.distance);
  88626. }
  88627. else {
  88628. gazer._gazeTracker.isVisible = false;
  88629. }
  88630. if (hit && hit.pickedMesh) {
  88631. gazer._currentHit = hit;
  88632. if (gazer._pointerDownOnMeshAsked) {
  88633. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  88634. }
  88635. // The object selected is the floor, we're in a teleportation scenario
  88636. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  88637. // Moving the teleportation area to this targetted point
  88638. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  88639. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  88640. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88641. }
  88642. gazer._currentMeshSelected = null;
  88643. if (gazer._teleportationRequestInitiated) {
  88644. this._moveTeleportationSelectorTo(hit, gazer, ray);
  88645. }
  88646. return;
  88647. }
  88648. // If not, we're in a selection scenario
  88649. //this._teleportationAllowed = false;
  88650. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  88651. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  88652. this.onNewMeshPicked.notifyObservers(hit);
  88653. gazer._currentMeshSelected = hit.pickedMesh;
  88654. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  88655. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  88656. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  88657. gazer._isActionableMesh = true;
  88658. }
  88659. else {
  88660. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88661. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88662. gazer._isActionableMesh = false;
  88663. }
  88664. try {
  88665. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  88666. }
  88667. catch (err) {
  88668. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  88669. }
  88670. }
  88671. else {
  88672. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88673. gazer._currentMeshSelected = null;
  88674. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88675. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88676. }
  88677. }
  88678. }
  88679. else {
  88680. gazer._currentHit = null;
  88681. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88682. gazer._currentMeshSelected = null;
  88683. //this._teleportationAllowed = false;
  88684. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88685. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88686. }
  88687. };
  88688. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  88689. if (mesh) {
  88690. this.onSelectedMeshUnselected.notifyObservers(mesh);
  88691. }
  88692. };
  88693. /**
  88694. * Sets the color of the laser ray from the vr controllers.
  88695. * @param color new color for the ray.
  88696. */
  88697. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  88698. if (this.leftController) {
  88699. this.leftController._setLaserPointerColor(color);
  88700. }
  88701. if (this.rightController) {
  88702. this.rightController._setLaserPointerColor(color);
  88703. }
  88704. };
  88705. /**
  88706. * Sets the color of the ray from the vr headsets gaze.
  88707. * @param color new color for the ray.
  88708. */
  88709. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  88710. if (!this._cameraGazer._gazeTracker.material) {
  88711. return;
  88712. }
  88713. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  88714. if (this.leftController) {
  88715. this.leftController._gazeTracker.material.emissiveColor = color;
  88716. }
  88717. if (this.rightController) {
  88718. this.rightController._gazeTracker.material.emissiveColor = color;
  88719. }
  88720. };
  88721. /**
  88722. * Exits VR and disposes of the vr experience helper
  88723. */
  88724. VRExperienceHelper.prototype.dispose = function () {
  88725. if (this.isInVRMode) {
  88726. this.exitVR();
  88727. }
  88728. if (this._postProcessMove) {
  88729. this._postProcessMove.dispose();
  88730. }
  88731. if (this._webVRCamera) {
  88732. this._webVRCamera.dispose();
  88733. }
  88734. if (this._vrDeviceOrientationCamera) {
  88735. this._vrDeviceOrientationCamera.dispose();
  88736. }
  88737. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  88738. document.body.removeChild(this._btnVR);
  88739. }
  88740. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  88741. this._deviceOrientationCamera.dispose();
  88742. }
  88743. if (this._cameraGazer) {
  88744. this._cameraGazer.dispose();
  88745. }
  88746. if (this.leftController) {
  88747. this.leftController.dispose();
  88748. }
  88749. if (this.rightController) {
  88750. this.rightController.dispose();
  88751. }
  88752. if (this._teleportationTarget) {
  88753. this._teleportationTarget.dispose();
  88754. }
  88755. this._floorMeshesCollection = [];
  88756. document.removeEventListener("keydown", this._onKeyDown);
  88757. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88758. window.removeEventListener("resize", this._onResize);
  88759. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  88760. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  88761. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  88762. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  88763. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  88764. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  88765. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  88766. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88767. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  88768. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  88769. this._scene.unregisterBeforeRender(this.beforeRender);
  88770. };
  88771. /**
  88772. * Gets the name of the VRExperienceHelper class
  88773. * @returns "VRExperienceHelper"
  88774. */
  88775. VRExperienceHelper.prototype.getClassName = function () {
  88776. return "VRExperienceHelper";
  88777. };
  88778. return VRExperienceHelper;
  88779. }());
  88780. BABYLON.VRExperienceHelper = VRExperienceHelper;
  88781. })(BABYLON || (BABYLON = {}));
  88782. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  88783. // Mainly based on these 2 articles :
  88784. // 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
  88785. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  88786. var BABYLON;
  88787. (function (BABYLON) {
  88788. /**
  88789. * Defines the potential axis of a Joystick
  88790. */
  88791. var JoystickAxis;
  88792. (function (JoystickAxis) {
  88793. /** X axis */
  88794. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  88795. /** Y axis */
  88796. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  88797. /** Z axis */
  88798. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  88799. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  88800. /**
  88801. * Class used to define virtual joystick (used in touch mode)
  88802. */
  88803. var VirtualJoystick = /** @class */ (function () {
  88804. /**
  88805. * Creates a new virtual joystick
  88806. * @param leftJoystick defines that the joystick is for left hand (false by default)
  88807. */
  88808. function VirtualJoystick(leftJoystick) {
  88809. var _this = this;
  88810. if (leftJoystick) {
  88811. this._leftJoystick = true;
  88812. }
  88813. else {
  88814. this._leftJoystick = false;
  88815. }
  88816. VirtualJoystick._globalJoystickIndex++;
  88817. // By default left & right arrow keys are moving the X
  88818. // and up & down keys are moving the Y
  88819. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  88820. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  88821. this.reverseLeftRight = false;
  88822. this.reverseUpDown = false;
  88823. // collections of pointers
  88824. this._touches = new BABYLON.StringDictionary();
  88825. this.deltaPosition = BABYLON.Vector3.Zero();
  88826. this._joystickSensibility = 25;
  88827. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88828. this._onResize = function (evt) {
  88829. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88830. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88831. if (VirtualJoystick.vjCanvas) {
  88832. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  88833. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  88834. }
  88835. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  88836. };
  88837. // injecting a canvas element on top of the canvas 3D game
  88838. if (!VirtualJoystick.vjCanvas) {
  88839. window.addEventListener("resize", this._onResize, false);
  88840. VirtualJoystick.vjCanvas = document.createElement("canvas");
  88841. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  88842. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  88843. VirtualJoystick.vjCanvas.width = window.innerWidth;
  88844. VirtualJoystick.vjCanvas.height = window.innerHeight;
  88845. VirtualJoystick.vjCanvas.style.width = "100%";
  88846. VirtualJoystick.vjCanvas.style.height = "100%";
  88847. VirtualJoystick.vjCanvas.style.position = "absolute";
  88848. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  88849. VirtualJoystick.vjCanvas.style.top = "0px";
  88850. VirtualJoystick.vjCanvas.style.left = "0px";
  88851. VirtualJoystick.vjCanvas.style.zIndex = "5";
  88852. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  88853. // Support for jQuery PEP polyfill
  88854. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  88855. var context = VirtualJoystick.vjCanvas.getContext('2d');
  88856. if (!context) {
  88857. throw new Error("Unable to create canvas for virtual joystick");
  88858. }
  88859. VirtualJoystick.vjCanvasContext = context;
  88860. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  88861. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  88862. document.body.appendChild(VirtualJoystick.vjCanvas);
  88863. }
  88864. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  88865. this.pressed = false;
  88866. // default joystick color
  88867. this._joystickColor = "cyan";
  88868. this._joystickPointerID = -1;
  88869. // current joystick position
  88870. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  88871. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  88872. // origin joystick position
  88873. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  88874. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  88875. this._onPointerDownHandlerRef = function (evt) {
  88876. _this._onPointerDown(evt);
  88877. };
  88878. this._onPointerMoveHandlerRef = function (evt) {
  88879. _this._onPointerMove(evt);
  88880. };
  88881. this._onPointerUpHandlerRef = function (evt) {
  88882. _this._onPointerUp(evt);
  88883. };
  88884. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  88885. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  88886. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  88887. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  88888. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  88889. evt.preventDefault(); // Disables system menu
  88890. }, false);
  88891. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  88892. }
  88893. /**
  88894. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  88895. * @param newJoystickSensibility defines the new sensibility
  88896. */
  88897. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  88898. this._joystickSensibility = newJoystickSensibility;
  88899. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  88900. };
  88901. VirtualJoystick.prototype._onPointerDown = function (e) {
  88902. var positionOnScreenCondition;
  88903. e.preventDefault();
  88904. if (this._leftJoystick === true) {
  88905. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  88906. }
  88907. else {
  88908. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  88909. }
  88910. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  88911. // First contact will be dedicated to the virtual joystick
  88912. this._joystickPointerID = e.pointerId;
  88913. this._joystickPointerStartPos.x = e.clientX;
  88914. this._joystickPointerStartPos.y = e.clientY;
  88915. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  88916. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  88917. this._deltaJoystickVector.x = 0;
  88918. this._deltaJoystickVector.y = 0;
  88919. this.pressed = true;
  88920. this._touches.add(e.pointerId.toString(), e);
  88921. }
  88922. else {
  88923. // You can only trigger the action buttons with a joystick declared
  88924. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  88925. this._action();
  88926. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  88927. }
  88928. }
  88929. };
  88930. VirtualJoystick.prototype._onPointerMove = function (e) {
  88931. // If the current pointer is the one associated to the joystick (first touch contact)
  88932. if (this._joystickPointerID == e.pointerId) {
  88933. this._joystickPointerPos.x = e.clientX;
  88934. this._joystickPointerPos.y = e.clientY;
  88935. this._deltaJoystickVector = this._joystickPointerPos.clone();
  88936. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  88937. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  88938. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  88939. switch (this._axisTargetedByLeftAndRight) {
  88940. case JoystickAxis.X:
  88941. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  88942. break;
  88943. case JoystickAxis.Y:
  88944. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  88945. break;
  88946. case JoystickAxis.Z:
  88947. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  88948. break;
  88949. }
  88950. var directionUpDown = this.reverseUpDown ? 1 : -1;
  88951. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  88952. switch (this._axisTargetedByUpAndDown) {
  88953. case JoystickAxis.X:
  88954. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  88955. break;
  88956. case JoystickAxis.Y:
  88957. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  88958. break;
  88959. case JoystickAxis.Z:
  88960. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  88961. break;
  88962. }
  88963. }
  88964. else {
  88965. var data = this._touches.get(e.pointerId.toString());
  88966. if (data) {
  88967. data.x = e.clientX;
  88968. data.y = e.clientY;
  88969. }
  88970. }
  88971. };
  88972. VirtualJoystick.prototype._onPointerUp = function (e) {
  88973. if (this._joystickPointerID == e.pointerId) {
  88974. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  88975. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  88976. this._joystickPointerID = -1;
  88977. this.pressed = false;
  88978. }
  88979. else {
  88980. var touch = this._touches.get(e.pointerId.toString());
  88981. if (touch) {
  88982. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  88983. }
  88984. }
  88985. this._deltaJoystickVector.x = 0;
  88986. this._deltaJoystickVector.y = 0;
  88987. this._touches.remove(e.pointerId.toString());
  88988. };
  88989. /**
  88990. * Change the color of the virtual joystick
  88991. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  88992. */
  88993. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  88994. this._joystickColor = newColor;
  88995. };
  88996. /**
  88997. * Defines a callback to call when the joystick is touched
  88998. * @param action defines the callback
  88999. */
  89000. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  89001. this._action = action;
  89002. };
  89003. /**
  89004. * Defines which axis you'd like to control for left & right
  89005. * @param axis defines the axis to use
  89006. */
  89007. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  89008. switch (axis) {
  89009. case JoystickAxis.X:
  89010. case JoystickAxis.Y:
  89011. case JoystickAxis.Z:
  89012. this._axisTargetedByLeftAndRight = axis;
  89013. break;
  89014. default:
  89015. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89016. break;
  89017. }
  89018. };
  89019. /**
  89020. * Defines which axis you'd like to control for up & down
  89021. * @param axis defines the axis to use
  89022. */
  89023. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  89024. switch (axis) {
  89025. case JoystickAxis.X:
  89026. case JoystickAxis.Y:
  89027. case JoystickAxis.Z:
  89028. this._axisTargetedByUpAndDown = axis;
  89029. break;
  89030. default:
  89031. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89032. break;
  89033. }
  89034. };
  89035. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  89036. var _this = this;
  89037. if (this.pressed) {
  89038. this._touches.forEach(function (key, touch) {
  89039. if (touch.pointerId === _this._joystickPointerID) {
  89040. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  89041. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  89042. VirtualJoystick.vjCanvasContext.beginPath();
  89043. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89044. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89045. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  89046. VirtualJoystick.vjCanvasContext.stroke();
  89047. VirtualJoystick.vjCanvasContext.closePath();
  89048. VirtualJoystick.vjCanvasContext.beginPath();
  89049. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89050. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89051. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  89052. VirtualJoystick.vjCanvasContext.stroke();
  89053. VirtualJoystick.vjCanvasContext.closePath();
  89054. VirtualJoystick.vjCanvasContext.beginPath();
  89055. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89056. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  89057. VirtualJoystick.vjCanvasContext.stroke();
  89058. VirtualJoystick.vjCanvasContext.closePath();
  89059. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  89060. }
  89061. else {
  89062. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89063. VirtualJoystick.vjCanvasContext.beginPath();
  89064. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  89065. VirtualJoystick.vjCanvasContext.beginPath();
  89066. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  89067. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89068. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  89069. VirtualJoystick.vjCanvasContext.stroke();
  89070. VirtualJoystick.vjCanvasContext.closePath();
  89071. touch.prevX = touch.x;
  89072. touch.prevY = touch.y;
  89073. }
  89074. ;
  89075. });
  89076. }
  89077. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89078. };
  89079. /**
  89080. * Release internal HTML canvas
  89081. */
  89082. VirtualJoystick.prototype.releaseCanvas = function () {
  89083. if (VirtualJoystick.vjCanvas) {
  89084. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  89085. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  89086. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  89087. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  89088. window.removeEventListener("resize", this._onResize);
  89089. document.body.removeChild(VirtualJoystick.vjCanvas);
  89090. VirtualJoystick.vjCanvas = null;
  89091. }
  89092. };
  89093. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  89094. VirtualJoystick._globalJoystickIndex = 0;
  89095. return VirtualJoystick;
  89096. }());
  89097. BABYLON.VirtualJoystick = VirtualJoystick;
  89098. })(BABYLON || (BABYLON = {}));
  89099. //# sourceMappingURL=babylon.virtualJoystick.js.map
  89100. var BABYLON;
  89101. (function (BABYLON) {
  89102. // We're mainly based on the logic defined into the FreeCamera code
  89103. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  89104. __extends(VirtualJoysticksCamera, _super);
  89105. function VirtualJoysticksCamera(name, position, scene) {
  89106. var _this = _super.call(this, name, position, scene) || this;
  89107. _this.inputs.addVirtualJoystick();
  89108. return _this;
  89109. }
  89110. VirtualJoysticksCamera.prototype.getClassName = function () {
  89111. return "VirtualJoysticksCamera";
  89112. };
  89113. return VirtualJoysticksCamera;
  89114. }(BABYLON.FreeCamera));
  89115. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  89116. })(BABYLON || (BABYLON = {}));
  89117. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  89118. var BABYLON;
  89119. (function (BABYLON) {
  89120. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  89121. function FreeCameraVirtualJoystickInput() {
  89122. }
  89123. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  89124. return this._leftjoystick;
  89125. };
  89126. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  89127. return this._rightjoystick;
  89128. };
  89129. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  89130. if (this._leftjoystick) {
  89131. var camera = this.camera;
  89132. var speed = camera._computeLocalCameraSpeed() * 50;
  89133. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  89134. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  89135. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  89136. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  89137. if (!this._leftjoystick.pressed) {
  89138. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  89139. }
  89140. if (!this._rightjoystick.pressed) {
  89141. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  89142. }
  89143. }
  89144. };
  89145. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  89146. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  89147. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  89148. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  89149. this._leftjoystick.setJoystickSensibility(0.15);
  89150. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  89151. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  89152. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  89153. this._rightjoystick.reverseUpDown = true;
  89154. this._rightjoystick.setJoystickSensibility(0.05);
  89155. this._rightjoystick.setJoystickColor("yellow");
  89156. };
  89157. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  89158. this._leftjoystick.releaseCanvas();
  89159. this._rightjoystick.releaseCanvas();
  89160. };
  89161. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  89162. return "FreeCameraVirtualJoystickInput";
  89163. };
  89164. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  89165. return "virtualJoystick";
  89166. };
  89167. return FreeCameraVirtualJoystickInput;
  89168. }());
  89169. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  89170. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  89171. })(BABYLON || (BABYLON = {}));
  89172. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  89173. var BABYLON;
  89174. (function (BABYLON) {
  89175. var SimplificationSettings = /** @class */ (function () {
  89176. function SimplificationSettings(quality, distance, optimizeMesh) {
  89177. this.quality = quality;
  89178. this.distance = distance;
  89179. this.optimizeMesh = optimizeMesh;
  89180. }
  89181. return SimplificationSettings;
  89182. }());
  89183. BABYLON.SimplificationSettings = SimplificationSettings;
  89184. var SimplificationQueue = /** @class */ (function () {
  89185. function SimplificationQueue() {
  89186. this.running = false;
  89187. this._simplificationArray = [];
  89188. }
  89189. SimplificationQueue.prototype.addTask = function (task) {
  89190. this._simplificationArray.push(task);
  89191. };
  89192. SimplificationQueue.prototype.executeNext = function () {
  89193. var task = this._simplificationArray.pop();
  89194. if (task) {
  89195. this.running = true;
  89196. this.runSimplification(task);
  89197. }
  89198. else {
  89199. this.running = false;
  89200. }
  89201. };
  89202. SimplificationQueue.prototype.runSimplification = function (task) {
  89203. var _this = this;
  89204. if (task.parallelProcessing) {
  89205. //parallel simplifier
  89206. task.settings.forEach(function (setting) {
  89207. var simplifier = _this.getSimplifier(task);
  89208. simplifier.simplify(setting, function (newMesh) {
  89209. task.mesh.addLODLevel(setting.distance, newMesh);
  89210. newMesh.isVisible = true;
  89211. //check if it is the last
  89212. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  89213. //all done, run the success callback.
  89214. task.successCallback();
  89215. }
  89216. _this.executeNext();
  89217. });
  89218. });
  89219. }
  89220. else {
  89221. //single simplifier.
  89222. var simplifier = this.getSimplifier(task);
  89223. var runDecimation = function (setting, callback) {
  89224. simplifier.simplify(setting, function (newMesh) {
  89225. task.mesh.addLODLevel(setting.distance, newMesh);
  89226. newMesh.isVisible = true;
  89227. //run the next quality level
  89228. callback();
  89229. });
  89230. };
  89231. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  89232. runDecimation(task.settings[loop.index], function () {
  89233. loop.executeNext();
  89234. });
  89235. }, function () {
  89236. //execution ended, run the success callback.
  89237. if (task.successCallback) {
  89238. task.successCallback();
  89239. }
  89240. _this.executeNext();
  89241. });
  89242. }
  89243. };
  89244. SimplificationQueue.prototype.getSimplifier = function (task) {
  89245. switch (task.simplificationType) {
  89246. case SimplificationType.QUADRATIC:
  89247. default:
  89248. return new QuadraticErrorSimplification(task.mesh);
  89249. }
  89250. };
  89251. return SimplificationQueue;
  89252. }());
  89253. BABYLON.SimplificationQueue = SimplificationQueue;
  89254. /**
  89255. * The implemented types of simplification
  89256. * At the moment only Quadratic Error Decimation is implemented
  89257. */
  89258. var SimplificationType;
  89259. (function (SimplificationType) {
  89260. /** Quadratic error decimation */
  89261. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  89262. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  89263. var DecimationTriangle = /** @class */ (function () {
  89264. function DecimationTriangle(vertices) {
  89265. this.vertices = vertices;
  89266. this.error = new Array(4);
  89267. this.deleted = false;
  89268. this.isDirty = false;
  89269. this.deletePending = false;
  89270. this.borderFactor = 0;
  89271. }
  89272. return DecimationTriangle;
  89273. }());
  89274. BABYLON.DecimationTriangle = DecimationTriangle;
  89275. var DecimationVertex = /** @class */ (function () {
  89276. function DecimationVertex(position, id) {
  89277. this.position = position;
  89278. this.id = id;
  89279. this.isBorder = true;
  89280. this.q = new QuadraticMatrix();
  89281. this.triangleCount = 0;
  89282. this.triangleStart = 0;
  89283. this.originalOffsets = [];
  89284. }
  89285. DecimationVertex.prototype.updatePosition = function (newPosition) {
  89286. this.position.copyFrom(newPosition);
  89287. };
  89288. return DecimationVertex;
  89289. }());
  89290. BABYLON.DecimationVertex = DecimationVertex;
  89291. var QuadraticMatrix = /** @class */ (function () {
  89292. function QuadraticMatrix(data) {
  89293. this.data = new Array(10);
  89294. for (var i = 0; i < 10; ++i) {
  89295. if (data && data[i]) {
  89296. this.data[i] = data[i];
  89297. }
  89298. else {
  89299. this.data[i] = 0;
  89300. }
  89301. }
  89302. }
  89303. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  89304. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  89305. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  89306. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  89307. return det;
  89308. };
  89309. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  89310. for (var i = 0; i < 10; ++i) {
  89311. this.data[i] += matrix.data[i];
  89312. }
  89313. };
  89314. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  89315. for (var i = 0; i < 10; ++i) {
  89316. this.data[i] += data[i];
  89317. }
  89318. };
  89319. QuadraticMatrix.prototype.add = function (matrix) {
  89320. var m = new QuadraticMatrix();
  89321. for (var i = 0; i < 10; ++i) {
  89322. m.data[i] = this.data[i] + matrix.data[i];
  89323. }
  89324. return m;
  89325. };
  89326. QuadraticMatrix.FromData = function (a, b, c, d) {
  89327. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  89328. };
  89329. //returning an array to avoid garbage collection
  89330. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  89331. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  89332. };
  89333. return QuadraticMatrix;
  89334. }());
  89335. BABYLON.QuadraticMatrix = QuadraticMatrix;
  89336. var Reference = /** @class */ (function () {
  89337. function Reference(vertexId, triangleId) {
  89338. this.vertexId = vertexId;
  89339. this.triangleId = triangleId;
  89340. }
  89341. return Reference;
  89342. }());
  89343. BABYLON.Reference = Reference;
  89344. /**
  89345. * An implementation of the Quadratic Error simplification algorithm.
  89346. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  89347. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  89348. * @author RaananW
  89349. */
  89350. var QuadraticErrorSimplification = /** @class */ (function () {
  89351. function QuadraticErrorSimplification(_mesh) {
  89352. this._mesh = _mesh;
  89353. this.syncIterations = 5000;
  89354. this.aggressiveness = 7;
  89355. this.decimationIterations = 100;
  89356. this.boundingBoxEpsilon = BABYLON.Epsilon;
  89357. }
  89358. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  89359. var _this = this;
  89360. this.initDecimatedMesh();
  89361. //iterating through the submeshes array, one after the other.
  89362. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  89363. _this.initWithMesh(loop.index, function () {
  89364. _this.runDecimation(settings, loop.index, function () {
  89365. loop.executeNext();
  89366. });
  89367. }, settings.optimizeMesh);
  89368. }, function () {
  89369. setTimeout(function () {
  89370. successCallback(_this._reconstructedMesh);
  89371. }, 0);
  89372. });
  89373. };
  89374. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  89375. var _this = this;
  89376. var targetCount = ~~(this.triangles.length * settings.quality);
  89377. var deletedTriangles = 0;
  89378. var triangleCount = this.triangles.length;
  89379. var iterationFunction = function (iteration, callback) {
  89380. setTimeout(function () {
  89381. if (iteration % 5 === 0) {
  89382. _this.updateMesh(iteration === 0);
  89383. }
  89384. for (var i = 0; i < _this.triangles.length; ++i) {
  89385. _this.triangles[i].isDirty = false;
  89386. }
  89387. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  89388. var trianglesIterator = function (i) {
  89389. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  89390. var t = _this.triangles[tIdx];
  89391. if (!t)
  89392. return;
  89393. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  89394. return;
  89395. }
  89396. for (var j = 0; j < 3; ++j) {
  89397. if (t.error[j] < threshold) {
  89398. var deleted0 = [];
  89399. var deleted1 = [];
  89400. var v0 = t.vertices[j];
  89401. var v1 = t.vertices[(j + 1) % 3];
  89402. if (v0.isBorder || v1.isBorder)
  89403. continue;
  89404. var p = BABYLON.Vector3.Zero();
  89405. var n = BABYLON.Vector3.Zero();
  89406. var uv = BABYLON.Vector2.Zero();
  89407. var color = new BABYLON.Color4(0, 0, 0, 1);
  89408. _this.calculateError(v0, v1, p, n, uv, color);
  89409. var delTr = new Array();
  89410. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  89411. continue;
  89412. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  89413. continue;
  89414. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  89415. continue;
  89416. var uniqueArray = new Array();
  89417. delTr.forEach(function (deletedT) {
  89418. if (uniqueArray.indexOf(deletedT) === -1) {
  89419. deletedT.deletePending = true;
  89420. uniqueArray.push(deletedT);
  89421. }
  89422. });
  89423. if (uniqueArray.length % 2 !== 0) {
  89424. continue;
  89425. }
  89426. v0.q = v1.q.add(v0.q);
  89427. v0.updatePosition(p);
  89428. var tStart = _this.references.length;
  89429. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  89430. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  89431. var tCount = _this.references.length - tStart;
  89432. if (tCount <= v0.triangleCount) {
  89433. if (tCount) {
  89434. for (var c = 0; c < tCount; c++) {
  89435. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  89436. }
  89437. }
  89438. }
  89439. else {
  89440. v0.triangleStart = tStart;
  89441. }
  89442. v0.triangleCount = tCount;
  89443. break;
  89444. }
  89445. }
  89446. };
  89447. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  89448. }, 0);
  89449. };
  89450. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  89451. if (triangleCount - deletedTriangles <= targetCount)
  89452. loop.breakLoop();
  89453. else {
  89454. iterationFunction(loop.index, function () {
  89455. loop.executeNext();
  89456. });
  89457. }
  89458. }, function () {
  89459. setTimeout(function () {
  89460. //reconstruct this part of the mesh
  89461. _this.reconstructMesh(submeshIndex);
  89462. successCallback();
  89463. }, 0);
  89464. });
  89465. };
  89466. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  89467. var _this = this;
  89468. this.vertices = [];
  89469. this.triangles = [];
  89470. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  89471. var indices = this._mesh.getIndices();
  89472. var submesh = this._mesh.subMeshes[submeshIndex];
  89473. var findInVertices = function (positionToSearch) {
  89474. if (optimizeMesh) {
  89475. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  89476. if (_this.vertices[ii].position.equals(positionToSearch)) {
  89477. return _this.vertices[ii];
  89478. }
  89479. }
  89480. }
  89481. return null;
  89482. };
  89483. var vertexReferences = [];
  89484. var vertexInit = function (i) {
  89485. if (!positionData) {
  89486. return;
  89487. }
  89488. var offset = i + submesh.verticesStart;
  89489. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  89490. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  89491. vertex.originalOffsets.push(offset);
  89492. if (vertex.id === _this.vertices.length) {
  89493. _this.vertices.push(vertex);
  89494. }
  89495. vertexReferences.push(vertex.id);
  89496. };
  89497. //var totalVertices = mesh.getTotalVertices();
  89498. var totalVertices = submesh.verticesCount;
  89499. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  89500. var indicesInit = function (i) {
  89501. if (!indices) {
  89502. return;
  89503. }
  89504. var offset = (submesh.indexStart / 3) + i;
  89505. var pos = (offset * 3);
  89506. var i0 = indices[pos + 0];
  89507. var i1 = indices[pos + 1];
  89508. var i2 = indices[pos + 2];
  89509. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  89510. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  89511. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  89512. var triangle = new DecimationTriangle([v0, v1, v2]);
  89513. triangle.originalOffset = pos;
  89514. _this.triangles.push(triangle);
  89515. };
  89516. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  89517. _this.init(callback);
  89518. });
  89519. });
  89520. };
  89521. QuadraticErrorSimplification.prototype.init = function (callback) {
  89522. var _this = this;
  89523. var triangleInit1 = function (i) {
  89524. var t = _this.triangles[i];
  89525. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  89526. for (var j = 0; j < 3; j++) {
  89527. 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))));
  89528. }
  89529. };
  89530. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  89531. var triangleInit2 = function (i) {
  89532. var t = _this.triangles[i];
  89533. for (var j = 0; j < 3; ++j) {
  89534. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  89535. }
  89536. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89537. };
  89538. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  89539. callback();
  89540. });
  89541. });
  89542. };
  89543. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  89544. var newTriangles = [];
  89545. var i;
  89546. for (i = 0; i < this.vertices.length; ++i) {
  89547. this.vertices[i].triangleCount = 0;
  89548. }
  89549. var t;
  89550. var j;
  89551. for (i = 0; i < this.triangles.length; ++i) {
  89552. if (!this.triangles[i].deleted) {
  89553. t = this.triangles[i];
  89554. for (j = 0; j < 3; ++j) {
  89555. t.vertices[j].triangleCount = 1;
  89556. }
  89557. newTriangles.push(t);
  89558. }
  89559. }
  89560. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  89561. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  89562. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  89563. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  89564. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  89565. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89566. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  89567. var vertexCount = 0;
  89568. for (i = 0; i < this.vertices.length; ++i) {
  89569. var vertex = this.vertices[i];
  89570. vertex.id = vertexCount;
  89571. if (vertex.triangleCount) {
  89572. vertex.originalOffsets.forEach(function (originalOffset) {
  89573. if (!normalData) {
  89574. return;
  89575. }
  89576. newPositionData.push(vertex.position.x);
  89577. newPositionData.push(vertex.position.y);
  89578. newPositionData.push(vertex.position.z);
  89579. newNormalData.push(normalData[originalOffset * 3]);
  89580. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  89581. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  89582. if (uvs && uvs.length) {
  89583. newUVsData.push(uvs[(originalOffset * 2)]);
  89584. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  89585. }
  89586. else if (colorsData && colorsData.length) {
  89587. newColorsData.push(colorsData[(originalOffset * 4)]);
  89588. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  89589. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  89590. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  89591. }
  89592. ++vertexCount;
  89593. });
  89594. }
  89595. }
  89596. var startingIndex = this._reconstructedMesh.getTotalIndices();
  89597. var startingVertex = this._reconstructedMesh.getTotalVertices();
  89598. var submeshesArray = this._reconstructedMesh.subMeshes;
  89599. this._reconstructedMesh.subMeshes = [];
  89600. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  89601. var originalIndices = this._mesh.getIndices();
  89602. for (i = 0; i < newTriangles.length; ++i) {
  89603. t = newTriangles[i]; //now get the new referencing point for each vertex
  89604. [0, 1, 2].forEach(function (idx) {
  89605. var id = originalIndices[t.originalOffset + idx];
  89606. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  89607. if (offset < 0)
  89608. offset = 0;
  89609. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  89610. });
  89611. }
  89612. //overwriting the old vertex buffers and indices.
  89613. this._reconstructedMesh.setIndices(newIndicesArray);
  89614. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  89615. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  89616. if (newUVsData.length > 0)
  89617. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  89618. if (newColorsData.length > 0)
  89619. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  89620. //create submesh
  89621. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  89622. if (submeshIndex > 0) {
  89623. this._reconstructedMesh.subMeshes = [];
  89624. submeshesArray.forEach(function (submesh) {
  89625. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  89626. });
  89627. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  89628. }
  89629. };
  89630. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  89631. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  89632. this._reconstructedMesh.material = this._mesh.material;
  89633. this._reconstructedMesh.parent = this._mesh.parent;
  89634. this._reconstructedMesh.isVisible = false;
  89635. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  89636. };
  89637. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  89638. for (var i = 0; i < vertex1.triangleCount; ++i) {
  89639. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  89640. if (t.deleted)
  89641. continue;
  89642. var s = this.references[vertex1.triangleStart + i].vertexId;
  89643. var v1 = t.vertices[(s + 1) % 3];
  89644. var v2 = t.vertices[(s + 2) % 3];
  89645. if ((v1 === vertex2 || v2 === vertex2)) {
  89646. deletedArray[i] = true;
  89647. delTr.push(t);
  89648. continue;
  89649. }
  89650. var d1 = v1.position.subtract(point);
  89651. d1 = d1.normalize();
  89652. var d2 = v2.position.subtract(point);
  89653. d2 = d2.normalize();
  89654. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  89655. return true;
  89656. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  89657. deletedArray[i] = false;
  89658. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  89659. return true;
  89660. }
  89661. return false;
  89662. };
  89663. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  89664. var newDeleted = deletedTriangles;
  89665. for (var i = 0; i < vertex.triangleCount; ++i) {
  89666. var ref = this.references[vertex.triangleStart + i];
  89667. var t = this.triangles[ref.triangleId];
  89668. if (t.deleted)
  89669. continue;
  89670. if (deletedArray[i] && t.deletePending) {
  89671. t.deleted = true;
  89672. newDeleted++;
  89673. continue;
  89674. }
  89675. t.vertices[ref.vertexId] = origVertex;
  89676. t.isDirty = true;
  89677. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  89678. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  89679. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  89680. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89681. this.references.push(ref);
  89682. }
  89683. return newDeleted;
  89684. };
  89685. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  89686. for (var i = 0; i < this.vertices.length; ++i) {
  89687. var vCount = [];
  89688. var vId = [];
  89689. var v = this.vertices[i];
  89690. var j;
  89691. for (j = 0; j < v.triangleCount; ++j) {
  89692. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  89693. for (var ii = 0; ii < 3; ii++) {
  89694. var ofs = 0;
  89695. var vv = triangle.vertices[ii];
  89696. while (ofs < vCount.length) {
  89697. if (vId[ofs] === vv.id)
  89698. break;
  89699. ++ofs;
  89700. }
  89701. if (ofs === vCount.length) {
  89702. vCount.push(1);
  89703. vId.push(vv.id);
  89704. }
  89705. else {
  89706. vCount[ofs]++;
  89707. }
  89708. }
  89709. }
  89710. for (j = 0; j < vCount.length; ++j) {
  89711. if (vCount[j] === 1) {
  89712. this.vertices[vId[j]].isBorder = true;
  89713. }
  89714. else {
  89715. this.vertices[vId[j]].isBorder = false;
  89716. }
  89717. }
  89718. }
  89719. };
  89720. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  89721. if (identifyBorders === void 0) { identifyBorders = false; }
  89722. var i;
  89723. if (!identifyBorders) {
  89724. var newTrianglesVector = [];
  89725. for (i = 0; i < this.triangles.length; ++i) {
  89726. if (!this.triangles[i].deleted) {
  89727. newTrianglesVector.push(this.triangles[i]);
  89728. }
  89729. }
  89730. this.triangles = newTrianglesVector;
  89731. }
  89732. for (i = 0; i < this.vertices.length; ++i) {
  89733. this.vertices[i].triangleCount = 0;
  89734. this.vertices[i].triangleStart = 0;
  89735. }
  89736. var t;
  89737. var j;
  89738. var v;
  89739. for (i = 0; i < this.triangles.length; ++i) {
  89740. t = this.triangles[i];
  89741. for (j = 0; j < 3; ++j) {
  89742. v = t.vertices[j];
  89743. v.triangleCount++;
  89744. }
  89745. }
  89746. var tStart = 0;
  89747. for (i = 0; i < this.vertices.length; ++i) {
  89748. this.vertices[i].triangleStart = tStart;
  89749. tStart += this.vertices[i].triangleCount;
  89750. this.vertices[i].triangleCount = 0;
  89751. }
  89752. var newReferences = new Array(this.triangles.length * 3);
  89753. for (i = 0; i < this.triangles.length; ++i) {
  89754. t = this.triangles[i];
  89755. for (j = 0; j < 3; ++j) {
  89756. v = t.vertices[j];
  89757. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  89758. v.triangleCount++;
  89759. }
  89760. }
  89761. this.references = newReferences;
  89762. if (identifyBorders) {
  89763. this.identifyBorder();
  89764. }
  89765. };
  89766. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  89767. var x = point.x;
  89768. var y = point.y;
  89769. var z = point.z;
  89770. 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
  89771. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  89772. };
  89773. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  89774. var q = vertex1.q.add(vertex2.q);
  89775. var border = vertex1.isBorder && vertex2.isBorder;
  89776. var error = 0;
  89777. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  89778. if (qDet !== 0 && !border) {
  89779. if (!pointResult) {
  89780. pointResult = BABYLON.Vector3.Zero();
  89781. }
  89782. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  89783. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  89784. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  89785. error = this.vertexError(q, pointResult);
  89786. }
  89787. else {
  89788. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  89789. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  89790. var error1 = this.vertexError(q, vertex1.position);
  89791. var error2 = this.vertexError(q, vertex2.position);
  89792. var error3 = this.vertexError(q, p3);
  89793. error = Math.min(error1, error2, error3);
  89794. if (error === error1) {
  89795. if (pointResult) {
  89796. pointResult.copyFrom(vertex1.position);
  89797. }
  89798. }
  89799. else if (error === error2) {
  89800. if (pointResult) {
  89801. pointResult.copyFrom(vertex2.position);
  89802. }
  89803. }
  89804. else {
  89805. if (pointResult) {
  89806. pointResult.copyFrom(p3);
  89807. }
  89808. }
  89809. }
  89810. return error;
  89811. };
  89812. return QuadraticErrorSimplification;
  89813. }());
  89814. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  89815. })(BABYLON || (BABYLON = {}));
  89816. //# sourceMappingURL=babylon.meshSimplification.js.map
  89817. var BABYLON;
  89818. (function (BABYLON) {
  89819. var MeshLODLevel = /** @class */ (function () {
  89820. function MeshLODLevel(distance, mesh) {
  89821. this.distance = distance;
  89822. this.mesh = mesh;
  89823. }
  89824. return MeshLODLevel;
  89825. }());
  89826. BABYLON.MeshLODLevel = MeshLODLevel;
  89827. })(BABYLON || (BABYLON = {}));
  89828. //# sourceMappingURL=babylon.meshLODLevel.js.map
  89829. var BABYLON;
  89830. (function (BABYLON) {
  89831. /**
  89832. * Defines the root class used to create scene optimization to use with SceneOptimizer
  89833. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89834. */
  89835. var SceneOptimization = /** @class */ (function () {
  89836. /**
  89837. * Creates the SceneOptimization object
  89838. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89839. * @param desc defines the description associated with the optimization
  89840. */
  89841. function SceneOptimization(
  89842. /**
  89843. * Defines the priority of this optimization (0 by default which means first in the list)
  89844. */
  89845. priority) {
  89846. if (priority === void 0) { priority = 0; }
  89847. this.priority = priority;
  89848. }
  89849. /**
  89850. * Gets a string describing the action executed by the current optimization
  89851. * @returns description string
  89852. */
  89853. SceneOptimization.prototype.getDescription = function () {
  89854. return "";
  89855. };
  89856. /**
  89857. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89858. * @param scene defines the current scene where to apply this optimization
  89859. * @param optimizer defines the current optimizer
  89860. * @returns true if everything that can be done was applied
  89861. */
  89862. SceneOptimization.prototype.apply = function (scene, optimizer) {
  89863. return true;
  89864. };
  89865. ;
  89866. return SceneOptimization;
  89867. }());
  89868. BABYLON.SceneOptimization = SceneOptimization;
  89869. /**
  89870. * Defines an optimization used to reduce the size of render target textures
  89871. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89872. */
  89873. var TextureOptimization = /** @class */ (function (_super) {
  89874. __extends(TextureOptimization, _super);
  89875. /**
  89876. * Creates the TextureOptimization object
  89877. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89878. * @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
  89879. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  89880. */
  89881. function TextureOptimization(
  89882. /**
  89883. * Defines the priority of this optimization (0 by default which means first in the list)
  89884. */
  89885. priority,
  89886. /**
  89887. * 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
  89888. */
  89889. maximumSize,
  89890. /**
  89891. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  89892. */
  89893. step) {
  89894. if (priority === void 0) { priority = 0; }
  89895. if (maximumSize === void 0) { maximumSize = 1024; }
  89896. if (step === void 0) { step = 0.5; }
  89897. var _this = _super.call(this, priority) || this;
  89898. _this.priority = priority;
  89899. _this.maximumSize = maximumSize;
  89900. _this.step = step;
  89901. return _this;
  89902. }
  89903. /**
  89904. * Gets a string describing the action executed by the current optimization
  89905. * @returns description string
  89906. */
  89907. TextureOptimization.prototype.getDescription = function () {
  89908. return "Reducing render target texture size to " + this.maximumSize;
  89909. };
  89910. /**
  89911. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89912. * @param scene defines the current scene where to apply this optimization
  89913. * @param optimizer defines the current optimizer
  89914. * @returns true if everything that can be done was applied
  89915. */
  89916. TextureOptimization.prototype.apply = function (scene, optimizer) {
  89917. var allDone = true;
  89918. for (var index = 0; index < scene.textures.length; index++) {
  89919. var texture = scene.textures[index];
  89920. if (!texture.canRescale || texture.getContext) {
  89921. continue;
  89922. }
  89923. var currentSize = texture.getSize();
  89924. var maxDimension = Math.max(currentSize.width, currentSize.height);
  89925. if (maxDimension > this.maximumSize) {
  89926. texture.scale(this.step);
  89927. allDone = false;
  89928. }
  89929. }
  89930. return allDone;
  89931. };
  89932. return TextureOptimization;
  89933. }(SceneOptimization));
  89934. BABYLON.TextureOptimization = TextureOptimization;
  89935. /**
  89936. * Defines an optimization used to increase or decrease the rendering resolution
  89937. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  89938. */
  89939. var HardwareScalingOptimization = /** @class */ (function (_super) {
  89940. __extends(HardwareScalingOptimization, _super);
  89941. /**
  89942. * Creates the HardwareScalingOptimization object
  89943. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  89944. * @param maximumScale defines the maximum scale to use (2 by default)
  89945. * @param step defines the step to use between two passes (0.5 by default)
  89946. */
  89947. function HardwareScalingOptimization(
  89948. /**
  89949. * Defines the priority of this optimization (0 by default which means first in the list)
  89950. */
  89951. priority,
  89952. /**
  89953. * Defines the maximum scale to use (2 by default)
  89954. */
  89955. maximumScale,
  89956. /**
  89957. * Defines the step to use between two passes (0.5 by default)
  89958. */
  89959. step) {
  89960. if (priority === void 0) { priority = 0; }
  89961. if (maximumScale === void 0) { maximumScale = 2; }
  89962. if (step === void 0) { step = 0.25; }
  89963. var _this = _super.call(this, priority) || this;
  89964. _this.priority = priority;
  89965. _this.maximumScale = maximumScale;
  89966. _this.step = step;
  89967. _this._currentScale = -1;
  89968. _this._directionOffset = 1;
  89969. return _this;
  89970. }
  89971. /**
  89972. * Gets a string describing the action executed by the current optimization
  89973. * @return description string
  89974. */
  89975. HardwareScalingOptimization.prototype.getDescription = function () {
  89976. return "Setting hardware scaling level to " + this._currentScale;
  89977. };
  89978. /**
  89979. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  89980. * @param scene defines the current scene where to apply this optimization
  89981. * @param optimizer defines the current optimizer
  89982. * @returns true if everything that can be done was applied
  89983. */
  89984. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  89985. if (this._currentScale === -1) {
  89986. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  89987. if (this._currentScale > this.maximumScale) {
  89988. this._directionOffset = -1;
  89989. }
  89990. }
  89991. this._currentScale += this._directionOffset * this.step;
  89992. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  89993. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  89994. };
  89995. ;
  89996. return HardwareScalingOptimization;
  89997. }(SceneOptimization));
  89998. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  89999. /**
  90000. * Defines an optimization used to remove shadows
  90001. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90002. */
  90003. var ShadowsOptimization = /** @class */ (function (_super) {
  90004. __extends(ShadowsOptimization, _super);
  90005. function ShadowsOptimization() {
  90006. return _super !== null && _super.apply(this, arguments) || this;
  90007. }
  90008. /**
  90009. * Gets a string describing the action executed by the current optimization
  90010. * @return description string
  90011. */
  90012. ShadowsOptimization.prototype.getDescription = function () {
  90013. return "Turning shadows on/off";
  90014. };
  90015. /**
  90016. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90017. * @param scene defines the current scene where to apply this optimization
  90018. * @param optimizer defines the current optimizer
  90019. * @returns true if everything that can be done was applied
  90020. */
  90021. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  90022. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90023. return true;
  90024. };
  90025. ;
  90026. return ShadowsOptimization;
  90027. }(SceneOptimization));
  90028. BABYLON.ShadowsOptimization = ShadowsOptimization;
  90029. /**
  90030. * Defines an optimization used to turn post-processes off
  90031. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90032. */
  90033. var PostProcessesOptimization = /** @class */ (function (_super) {
  90034. __extends(PostProcessesOptimization, _super);
  90035. function PostProcessesOptimization() {
  90036. return _super !== null && _super.apply(this, arguments) || this;
  90037. }
  90038. /**
  90039. * Gets a string describing the action executed by the current optimization
  90040. * @return description string
  90041. */
  90042. PostProcessesOptimization.prototype.getDescription = function () {
  90043. return "Turning post-processes on/off";
  90044. };
  90045. /**
  90046. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90047. * @param scene defines the current scene where to apply this optimization
  90048. * @param optimizer defines the current optimizer
  90049. * @returns true if everything that can be done was applied
  90050. */
  90051. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  90052. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  90053. return true;
  90054. };
  90055. ;
  90056. return PostProcessesOptimization;
  90057. }(SceneOptimization));
  90058. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  90059. /**
  90060. * Defines an optimization used to turn lens flares off
  90061. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90062. */
  90063. var LensFlaresOptimization = /** @class */ (function (_super) {
  90064. __extends(LensFlaresOptimization, _super);
  90065. function LensFlaresOptimization() {
  90066. return _super !== null && _super.apply(this, arguments) || this;
  90067. }
  90068. /**
  90069. * Gets a string describing the action executed by the current optimization
  90070. * @return description string
  90071. */
  90072. LensFlaresOptimization.prototype.getDescription = function () {
  90073. return "Turning lens flares on/off";
  90074. };
  90075. /**
  90076. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90077. * @param scene defines the current scene where to apply this optimization
  90078. * @param optimizer defines the current optimizer
  90079. * @returns true if everything that can be done was applied
  90080. */
  90081. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  90082. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  90083. return true;
  90084. };
  90085. ;
  90086. return LensFlaresOptimization;
  90087. }(SceneOptimization));
  90088. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  90089. /**
  90090. * Defines an optimization based on user defined callback.
  90091. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90092. */
  90093. var CustomOptimization = /** @class */ (function (_super) {
  90094. __extends(CustomOptimization, _super);
  90095. function CustomOptimization() {
  90096. return _super !== null && _super.apply(this, arguments) || this;
  90097. }
  90098. /**
  90099. * Gets a string describing the action executed by the current optimization
  90100. * @returns description string
  90101. */
  90102. CustomOptimization.prototype.getDescription = function () {
  90103. if (this.onGetDescription) {
  90104. return this.onGetDescription();
  90105. }
  90106. return "Running user defined callback";
  90107. };
  90108. /**
  90109. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90110. * @param scene defines the current scene where to apply this optimization
  90111. * @param optimizer defines the current optimizer
  90112. * @returns true if everything that can be done was applied
  90113. */
  90114. CustomOptimization.prototype.apply = function (scene, optimizer) {
  90115. if (this.onApply) {
  90116. return this.onApply(scene, optimizer);
  90117. }
  90118. return true;
  90119. };
  90120. ;
  90121. return CustomOptimization;
  90122. }(SceneOptimization));
  90123. BABYLON.CustomOptimization = CustomOptimization;
  90124. /**
  90125. * Defines an optimization used to turn particles off
  90126. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90127. */
  90128. var ParticlesOptimization = /** @class */ (function (_super) {
  90129. __extends(ParticlesOptimization, _super);
  90130. function ParticlesOptimization() {
  90131. return _super !== null && _super.apply(this, arguments) || this;
  90132. }
  90133. /**
  90134. * Gets a string describing the action executed by the current optimization
  90135. * @return description string
  90136. */
  90137. ParticlesOptimization.prototype.getDescription = function () {
  90138. return "Turning particles on/off";
  90139. };
  90140. /**
  90141. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90142. * @param scene defines the current scene where to apply this optimization
  90143. * @param optimizer defines the current optimizer
  90144. * @returns true if everything that can be done was applied
  90145. */
  90146. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  90147. scene.particlesEnabled = optimizer.isInImprovementMode;
  90148. return true;
  90149. };
  90150. ;
  90151. return ParticlesOptimization;
  90152. }(SceneOptimization));
  90153. BABYLON.ParticlesOptimization = ParticlesOptimization;
  90154. /**
  90155. * Defines an optimization used to turn render targets off
  90156. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90157. */
  90158. var RenderTargetsOptimization = /** @class */ (function (_super) {
  90159. __extends(RenderTargetsOptimization, _super);
  90160. function RenderTargetsOptimization() {
  90161. return _super !== null && _super.apply(this, arguments) || this;
  90162. }
  90163. /**
  90164. * Gets a string describing the action executed by the current optimization
  90165. * @return description string
  90166. */
  90167. RenderTargetsOptimization.prototype.getDescription = function () {
  90168. return "Turning render targets off";
  90169. };
  90170. /**
  90171. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90172. * @param scene defines the current scene where to apply this optimization
  90173. * @param optimizer defines the current optimizer
  90174. * @returns true if everything that can be done was applied
  90175. */
  90176. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  90177. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  90178. return true;
  90179. };
  90180. ;
  90181. return RenderTargetsOptimization;
  90182. }(SceneOptimization));
  90183. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  90184. /**
  90185. * Defines an optimization used to merge meshes with compatible materials
  90186. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90187. */
  90188. var MergeMeshesOptimization = /** @class */ (function (_super) {
  90189. __extends(MergeMeshesOptimization, _super);
  90190. function MergeMeshesOptimization() {
  90191. var _this = _super !== null && _super.apply(this, arguments) || this;
  90192. _this._canBeMerged = function (abstractMesh) {
  90193. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  90194. return false;
  90195. }
  90196. var mesh = abstractMesh;
  90197. if (!mesh.isVisible || !mesh.isEnabled()) {
  90198. return false;
  90199. }
  90200. if (mesh.instances.length > 0) {
  90201. return false;
  90202. }
  90203. if (mesh.skeleton || mesh.hasLODLevels) {
  90204. return false;
  90205. }
  90206. if (mesh.parent) {
  90207. return false;
  90208. }
  90209. return true;
  90210. };
  90211. return _this;
  90212. }
  90213. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  90214. /**
  90215. * Gets or sets a boolean which defines if optimization octree has to be updated
  90216. */
  90217. get: function () {
  90218. return MergeMeshesOptimization._UpdateSelectionTree;
  90219. },
  90220. /**
  90221. * Gets or sets a boolean which defines if optimization octree has to be updated
  90222. */
  90223. set: function (value) {
  90224. MergeMeshesOptimization._UpdateSelectionTree = value;
  90225. },
  90226. enumerable: true,
  90227. configurable: true
  90228. });
  90229. /**
  90230. * Gets a string describing the action executed by the current optimization
  90231. * @return description string
  90232. */
  90233. MergeMeshesOptimization.prototype.getDescription = function () {
  90234. return "Merging similar meshes together";
  90235. };
  90236. /**
  90237. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90238. * @param scene defines the current scene where to apply this optimization
  90239. * @param optimizer defines the current optimizer
  90240. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  90241. * @returns true if everything that can be done was applied
  90242. */
  90243. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  90244. var globalPool = scene.meshes.slice(0);
  90245. var globalLength = globalPool.length;
  90246. for (var index = 0; index < globalLength; index++) {
  90247. var currentPool = new Array();
  90248. var current = globalPool[index];
  90249. // Checks
  90250. if (!this._canBeMerged(current)) {
  90251. continue;
  90252. }
  90253. currentPool.push(current);
  90254. // Find compatible meshes
  90255. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  90256. var otherMesh = globalPool[subIndex];
  90257. if (!this._canBeMerged(otherMesh)) {
  90258. continue;
  90259. }
  90260. if (otherMesh.material !== current.material) {
  90261. continue;
  90262. }
  90263. if (otherMesh.checkCollisions !== current.checkCollisions) {
  90264. continue;
  90265. }
  90266. currentPool.push(otherMesh);
  90267. globalLength--;
  90268. globalPool.splice(subIndex, 1);
  90269. subIndex--;
  90270. }
  90271. if (currentPool.length < 2) {
  90272. continue;
  90273. }
  90274. // Merge meshes
  90275. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  90276. }
  90277. if (updateSelectionTree != undefined) {
  90278. if (updateSelectionTree) {
  90279. scene.createOrUpdateSelectionOctree();
  90280. }
  90281. }
  90282. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  90283. scene.createOrUpdateSelectionOctree();
  90284. }
  90285. return true;
  90286. };
  90287. ;
  90288. MergeMeshesOptimization._UpdateSelectionTree = false;
  90289. return MergeMeshesOptimization;
  90290. }(SceneOptimization));
  90291. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  90292. /**
  90293. * Defines a list of options used by SceneOptimizer
  90294. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90295. */
  90296. var SceneOptimizerOptions = /** @class */ (function () {
  90297. /**
  90298. * Creates a new list of options used by SceneOptimizer
  90299. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  90300. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  90301. */
  90302. function SceneOptimizerOptions(
  90303. /**
  90304. * Defines the target frame rate to reach (60 by default)
  90305. */
  90306. targetFrameRate,
  90307. /**
  90308. * Defines the interval between two checkes (2000ms by default)
  90309. */
  90310. trackerDuration) {
  90311. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  90312. if (trackerDuration === void 0) { trackerDuration = 2000; }
  90313. this.targetFrameRate = targetFrameRate;
  90314. this.trackerDuration = trackerDuration;
  90315. /**
  90316. * Gets the list of optimizations to apply
  90317. */
  90318. this.optimizations = new Array();
  90319. }
  90320. /**
  90321. * Add a new optimization
  90322. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  90323. * @returns the current SceneOptimizerOptions
  90324. */
  90325. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  90326. this.optimizations.push(optimization);
  90327. return this;
  90328. };
  90329. /**
  90330. * Add a new custom optimization
  90331. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  90332. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  90333. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90334. * @returns the current SceneOptimizerOptions
  90335. */
  90336. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  90337. if (priority === void 0) { priority = 0; }
  90338. var optimization = new CustomOptimization(priority);
  90339. optimization.onApply = onApply;
  90340. optimization.onGetDescription = onGetDescription;
  90341. this.optimizations.push(optimization);
  90342. return this;
  90343. };
  90344. /**
  90345. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  90346. * @param targetFrameRate defines the target frame rate (60 by default)
  90347. * @returns a SceneOptimizerOptions object
  90348. */
  90349. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  90350. var result = new SceneOptimizerOptions(targetFrameRate);
  90351. var priority = 0;
  90352. result.addOptimization(new MergeMeshesOptimization(priority));
  90353. result.addOptimization(new ShadowsOptimization(priority));
  90354. result.addOptimization(new LensFlaresOptimization(priority));
  90355. // Next priority
  90356. priority++;
  90357. result.addOptimization(new PostProcessesOptimization(priority));
  90358. result.addOptimization(new ParticlesOptimization(priority));
  90359. // Next priority
  90360. priority++;
  90361. result.addOptimization(new TextureOptimization(priority, 1024));
  90362. return result;
  90363. };
  90364. /**
  90365. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  90366. * @param targetFrameRate defines the target frame rate (60 by default)
  90367. * @returns a SceneOptimizerOptions object
  90368. */
  90369. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  90370. var result = new SceneOptimizerOptions(targetFrameRate);
  90371. var priority = 0;
  90372. result.addOptimization(new MergeMeshesOptimization(priority));
  90373. result.addOptimization(new ShadowsOptimization(priority));
  90374. result.addOptimization(new LensFlaresOptimization(priority));
  90375. // Next priority
  90376. priority++;
  90377. result.addOptimization(new PostProcessesOptimization(priority));
  90378. result.addOptimization(new ParticlesOptimization(priority));
  90379. // Next priority
  90380. priority++;
  90381. result.addOptimization(new TextureOptimization(priority, 512));
  90382. // Next priority
  90383. priority++;
  90384. result.addOptimization(new RenderTargetsOptimization(priority));
  90385. // Next priority
  90386. priority++;
  90387. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  90388. return result;
  90389. };
  90390. /**
  90391. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  90392. * @param targetFrameRate defines the target frame rate (60 by default)
  90393. * @returns a SceneOptimizerOptions object
  90394. */
  90395. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  90396. var result = new SceneOptimizerOptions(targetFrameRate);
  90397. var priority = 0;
  90398. result.addOptimization(new MergeMeshesOptimization(priority));
  90399. result.addOptimization(new ShadowsOptimization(priority));
  90400. result.addOptimization(new LensFlaresOptimization(priority));
  90401. // Next priority
  90402. priority++;
  90403. result.addOptimization(new PostProcessesOptimization(priority));
  90404. result.addOptimization(new ParticlesOptimization(priority));
  90405. // Next priority
  90406. priority++;
  90407. result.addOptimization(new TextureOptimization(priority, 256));
  90408. // Next priority
  90409. priority++;
  90410. result.addOptimization(new RenderTargetsOptimization(priority));
  90411. // Next priority
  90412. priority++;
  90413. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  90414. return result;
  90415. };
  90416. return SceneOptimizerOptions;
  90417. }());
  90418. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  90419. /**
  90420. * Class used to run optimizations in order to reach a target frame rate
  90421. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90422. */
  90423. var SceneOptimizer = /** @class */ (function () {
  90424. /**
  90425. * Creates a new SceneOptimizer
  90426. * @param scene defines the scene to work on
  90427. * @param options defines the options to use with the SceneOptimizer
  90428. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  90429. * @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)
  90430. */
  90431. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  90432. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  90433. if (improvementMode === void 0) { improvementMode = false; }
  90434. var _this = this;
  90435. this._isRunning = false;
  90436. this._currentPriorityLevel = 0;
  90437. this._targetFrameRate = 60;
  90438. this._trackerDuration = 2000;
  90439. this._currentFrameRate = 0;
  90440. this._improvementMode = false;
  90441. /**
  90442. * Defines an observable called when the optimizer reaches the target frame rate
  90443. */
  90444. this.onSuccessObservable = new BABYLON.Observable();
  90445. /**
  90446. * Defines an observable called when the optimizer enables an optimization
  90447. */
  90448. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  90449. /**
  90450. * Defines an observable called when the optimizer is not able to reach the target frame rate
  90451. */
  90452. this.onFailureObservable = new BABYLON.Observable();
  90453. if (!options) {
  90454. this._options = new SceneOptimizerOptions();
  90455. }
  90456. else {
  90457. this._options = options;
  90458. }
  90459. if (this._options.targetFrameRate) {
  90460. this._targetFrameRate = this._options.targetFrameRate;
  90461. }
  90462. if (this._options.trackerDuration) {
  90463. this._trackerDuration = this._options.trackerDuration;
  90464. }
  90465. if (autoGeneratePriorities) {
  90466. var priority = 0;
  90467. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  90468. var optim = _a[_i];
  90469. optim.priority = priority++;
  90470. }
  90471. }
  90472. this._improvementMode = improvementMode;
  90473. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90474. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  90475. _this._sceneDisposeObserver = null;
  90476. _this.dispose();
  90477. });
  90478. }
  90479. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  90480. /**
  90481. * Gets a boolean indicating if the optimizer is in improvement mode
  90482. */
  90483. get: function () {
  90484. return this._improvementMode;
  90485. },
  90486. enumerable: true,
  90487. configurable: true
  90488. });
  90489. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  90490. /**
  90491. * Gets the current priority level (0 at start)
  90492. */
  90493. get: function () {
  90494. return this._currentPriorityLevel;
  90495. },
  90496. enumerable: true,
  90497. configurable: true
  90498. });
  90499. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  90500. /**
  90501. * Gets the current frame rate checked by the SceneOptimizer
  90502. */
  90503. get: function () {
  90504. return this._currentFrameRate;
  90505. },
  90506. enumerable: true,
  90507. configurable: true
  90508. });
  90509. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  90510. /**
  90511. * Gets or sets the current target frame rate (60 by default)
  90512. */
  90513. get: function () {
  90514. return this._targetFrameRate;
  90515. },
  90516. /**
  90517. * Gets or sets the current target frame rate (60 by default)
  90518. */
  90519. set: function (value) {
  90520. this._targetFrameRate = value;
  90521. },
  90522. enumerable: true,
  90523. configurable: true
  90524. });
  90525. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  90526. /**
  90527. * Gets or sets the current interval between two checks (every 2000ms by default)
  90528. */
  90529. get: function () {
  90530. return this._trackerDuration;
  90531. },
  90532. /**
  90533. * Gets or sets the current interval between two checks (every 2000ms by default)
  90534. */
  90535. set: function (value) {
  90536. this._trackerDuration = value;
  90537. },
  90538. enumerable: true,
  90539. configurable: true
  90540. });
  90541. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  90542. /**
  90543. * Gets the list of active optimizations
  90544. */
  90545. get: function () {
  90546. return this._options.optimizations;
  90547. },
  90548. enumerable: true,
  90549. configurable: true
  90550. });
  90551. /**
  90552. * Stops the current optimizer
  90553. */
  90554. SceneOptimizer.prototype.stop = function () {
  90555. this._isRunning = false;
  90556. };
  90557. /**
  90558. * Reset the optimizer to initial step (current priority level = 0)
  90559. */
  90560. SceneOptimizer.prototype.reset = function () {
  90561. this._currentPriorityLevel = 0;
  90562. };
  90563. /**
  90564. * Start the optimizer. By default it will try to reach a specific framerate
  90565. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  90566. */
  90567. SceneOptimizer.prototype.start = function () {
  90568. var _this = this;
  90569. if (this._isRunning) {
  90570. return;
  90571. }
  90572. this._isRunning = true;
  90573. // Let's wait for the scene to be ready before running our check
  90574. this._scene.executeWhenReady(function () {
  90575. setTimeout(function () {
  90576. _this._checkCurrentState();
  90577. }, _this._trackerDuration);
  90578. });
  90579. };
  90580. SceneOptimizer.prototype._checkCurrentState = function () {
  90581. var _this = this;
  90582. if (!this._isRunning) {
  90583. return;
  90584. }
  90585. var scene = this._scene;
  90586. var options = this._options;
  90587. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  90588. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  90589. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  90590. this._isRunning = false;
  90591. this.onSuccessObservable.notifyObservers(this);
  90592. return;
  90593. }
  90594. // Apply current level of optimizations
  90595. var allDone = true;
  90596. var noOptimizationApplied = true;
  90597. for (var index = 0; index < options.optimizations.length; index++) {
  90598. var optimization = options.optimizations[index];
  90599. if (optimization.priority === this._currentPriorityLevel) {
  90600. noOptimizationApplied = false;
  90601. allDone = allDone && optimization.apply(scene, this);
  90602. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  90603. }
  90604. }
  90605. // If no optimization was applied, this is a failure :(
  90606. if (noOptimizationApplied) {
  90607. this._isRunning = false;
  90608. this.onFailureObservable.notifyObservers(this);
  90609. return;
  90610. }
  90611. // If all optimizations were done, move to next level
  90612. if (allDone) {
  90613. this._currentPriorityLevel++;
  90614. }
  90615. // Let's the system running for a specific amount of time before checking FPS
  90616. scene.executeWhenReady(function () {
  90617. setTimeout(function () {
  90618. _this._checkCurrentState();
  90619. }, _this._trackerDuration);
  90620. });
  90621. };
  90622. /**
  90623. * Release all resources
  90624. */
  90625. SceneOptimizer.prototype.dispose = function () {
  90626. this.stop();
  90627. this.onSuccessObservable.clear();
  90628. this.onFailureObservable.clear();
  90629. this.onNewOptimizationAppliedObservable.clear();
  90630. if (this._sceneDisposeObserver) {
  90631. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  90632. }
  90633. };
  90634. /**
  90635. * Helper function to create a SceneOptimizer with one single line of code
  90636. * @param scene defines the scene to work on
  90637. * @param options defines the options to use with the SceneOptimizer
  90638. * @param onSuccess defines a callback to call on success
  90639. * @param onFailure defines a callback to call on failure
  90640. * @returns the new SceneOptimizer object
  90641. */
  90642. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  90643. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  90644. if (onSuccess) {
  90645. optimizer.onSuccessObservable.add(function () {
  90646. onSuccess();
  90647. });
  90648. }
  90649. if (onFailure) {
  90650. optimizer.onFailureObservable.add(function () {
  90651. onFailure();
  90652. });
  90653. }
  90654. optimizer.start();
  90655. return optimizer;
  90656. };
  90657. return SceneOptimizer;
  90658. }());
  90659. BABYLON.SceneOptimizer = SceneOptimizer;
  90660. })(BABYLON || (BABYLON = {}));
  90661. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  90662. var BABYLON;
  90663. (function (BABYLON) {
  90664. var OutlineRenderer = /** @class */ (function () {
  90665. function OutlineRenderer(scene) {
  90666. this.zOffset = 1;
  90667. this._scene = scene;
  90668. }
  90669. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  90670. var _this = this;
  90671. if (useOverlay === void 0) { useOverlay = false; }
  90672. var scene = this._scene;
  90673. var engine = this._scene.getEngine();
  90674. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90675. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  90676. return;
  90677. }
  90678. var mesh = subMesh.getRenderingMesh();
  90679. var material = subMesh.getMaterial();
  90680. if (!material || !scene.activeCamera) {
  90681. return;
  90682. }
  90683. engine.enableEffect(this._effect);
  90684. // Logarithmic depth
  90685. if (material.useLogarithmicDepth) {
  90686. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  90687. }
  90688. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  90689. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  90690. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  90691. // Bones
  90692. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90693. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90694. }
  90695. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  90696. // Alpha test
  90697. if (material && material.needAlphaTesting()) {
  90698. var alphaTexture = material.getAlphaTestTexture();
  90699. if (alphaTexture) {
  90700. this._effect.setTexture("diffuseSampler", alphaTexture);
  90701. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90702. }
  90703. }
  90704. engine.setZOffset(-this.zOffset);
  90705. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  90706. engine.setZOffset(0);
  90707. };
  90708. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  90709. var defines = [];
  90710. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  90711. var mesh = subMesh.getMesh();
  90712. var material = subMesh.getMaterial();
  90713. if (material) {
  90714. // Alpha test
  90715. if (material.needAlphaTesting()) {
  90716. defines.push("#define ALPHATEST");
  90717. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90718. attribs.push(BABYLON.VertexBuffer.UVKind);
  90719. defines.push("#define UV1");
  90720. }
  90721. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90722. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90723. defines.push("#define UV2");
  90724. }
  90725. }
  90726. //Logarithmic depth
  90727. if (material.useLogarithmicDepth) {
  90728. defines.push("#define LOGARITHMICDEPTH");
  90729. }
  90730. }
  90731. // Bones
  90732. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90733. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90734. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90735. if (mesh.numBoneInfluencers > 4) {
  90736. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90737. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90738. }
  90739. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90740. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  90741. }
  90742. else {
  90743. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90744. }
  90745. // Instances
  90746. if (useInstances) {
  90747. defines.push("#define INSTANCES");
  90748. attribs.push("world0");
  90749. attribs.push("world1");
  90750. attribs.push("world2");
  90751. attribs.push("world3");
  90752. }
  90753. // Get correct effect
  90754. var join = defines.join("\n");
  90755. if (this._cachedDefines !== join) {
  90756. this._cachedDefines = join;
  90757. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  90758. }
  90759. return this._effect.isReady();
  90760. };
  90761. return OutlineRenderer;
  90762. }());
  90763. BABYLON.OutlineRenderer = OutlineRenderer;
  90764. })(BABYLON || (BABYLON = {}));
  90765. //# sourceMappingURL=babylon.outlineRenderer.js.map
  90766. var BABYLON;
  90767. (function (BABYLON) {
  90768. var FaceAdjacencies = /** @class */ (function () {
  90769. function FaceAdjacencies() {
  90770. this.edges = new Array();
  90771. this.edgesConnectedCount = 0;
  90772. }
  90773. return FaceAdjacencies;
  90774. }());
  90775. var EdgesRenderer = /** @class */ (function () {
  90776. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  90777. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  90778. if (epsilon === void 0) { epsilon = 0.95; }
  90779. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  90780. this.edgesWidthScalerForOrthographic = 1000.0;
  90781. this.edgesWidthScalerForPerspective = 50.0;
  90782. this._linesPositions = new Array();
  90783. this._linesNormals = new Array();
  90784. this._linesIndices = new Array();
  90785. this._buffers = {};
  90786. this._checkVerticesInsteadOfIndices = false;
  90787. this._source = source;
  90788. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  90789. this._epsilon = epsilon;
  90790. this._prepareRessources();
  90791. this._generateEdgesLines();
  90792. }
  90793. EdgesRenderer.prototype._prepareRessources = function () {
  90794. if (this._lineShader) {
  90795. return;
  90796. }
  90797. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  90798. attributes: ["position", "normal"],
  90799. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  90800. });
  90801. this._lineShader.disableDepthWrite = true;
  90802. this._lineShader.backFaceCulling = false;
  90803. };
  90804. EdgesRenderer.prototype._rebuild = function () {
  90805. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90806. if (buffer) {
  90807. buffer._rebuild();
  90808. }
  90809. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90810. if (buffer) {
  90811. buffer._rebuild();
  90812. }
  90813. var scene = this._source.getScene();
  90814. var engine = scene.getEngine();
  90815. this._ib = engine.createIndexBuffer(this._linesIndices);
  90816. };
  90817. EdgesRenderer.prototype.dispose = function () {
  90818. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90819. if (buffer) {
  90820. buffer.dispose();
  90821. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  90822. }
  90823. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  90824. if (buffer) {
  90825. buffer.dispose();
  90826. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  90827. }
  90828. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  90829. this._lineShader.dispose();
  90830. };
  90831. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  90832. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  90833. return 0;
  90834. }
  90835. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  90836. return 1;
  90837. }
  90838. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  90839. return 2;
  90840. }
  90841. return -1;
  90842. };
  90843. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  90844. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  90845. return 0;
  90846. }
  90847. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  90848. return 1;
  90849. }
  90850. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  90851. return 2;
  90852. }
  90853. return -1;
  90854. };
  90855. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  90856. var needToCreateLine;
  90857. if (edge === undefined) {
  90858. needToCreateLine = true;
  90859. }
  90860. else {
  90861. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  90862. needToCreateLine = dotProduct < this._epsilon;
  90863. }
  90864. if (needToCreateLine) {
  90865. var offset = this._linesPositions.length / 3;
  90866. var normal = p0.subtract(p1);
  90867. normal.normalize();
  90868. // Positions
  90869. this._linesPositions.push(p0.x);
  90870. this._linesPositions.push(p0.y);
  90871. this._linesPositions.push(p0.z);
  90872. this._linesPositions.push(p0.x);
  90873. this._linesPositions.push(p0.y);
  90874. this._linesPositions.push(p0.z);
  90875. this._linesPositions.push(p1.x);
  90876. this._linesPositions.push(p1.y);
  90877. this._linesPositions.push(p1.z);
  90878. this._linesPositions.push(p1.x);
  90879. this._linesPositions.push(p1.y);
  90880. this._linesPositions.push(p1.z);
  90881. // Normals
  90882. this._linesNormals.push(p1.x);
  90883. this._linesNormals.push(p1.y);
  90884. this._linesNormals.push(p1.z);
  90885. this._linesNormals.push(-1);
  90886. this._linesNormals.push(p1.x);
  90887. this._linesNormals.push(p1.y);
  90888. this._linesNormals.push(p1.z);
  90889. this._linesNormals.push(1);
  90890. this._linesNormals.push(p0.x);
  90891. this._linesNormals.push(p0.y);
  90892. this._linesNormals.push(p0.z);
  90893. this._linesNormals.push(-1);
  90894. this._linesNormals.push(p0.x);
  90895. this._linesNormals.push(p0.y);
  90896. this._linesNormals.push(p0.z);
  90897. this._linesNormals.push(1);
  90898. // Indices
  90899. this._linesIndices.push(offset);
  90900. this._linesIndices.push(offset + 1);
  90901. this._linesIndices.push(offset + 2);
  90902. this._linesIndices.push(offset);
  90903. this._linesIndices.push(offset + 2);
  90904. this._linesIndices.push(offset + 3);
  90905. }
  90906. };
  90907. EdgesRenderer.prototype._generateEdgesLines = function () {
  90908. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  90909. var indices = this._source.getIndices();
  90910. if (!indices || !positions) {
  90911. return;
  90912. }
  90913. // First let's find adjacencies
  90914. var adjacencies = new Array();
  90915. var faceNormals = new Array();
  90916. var index;
  90917. var faceAdjacencies;
  90918. // Prepare faces
  90919. for (index = 0; index < indices.length; index += 3) {
  90920. faceAdjacencies = new FaceAdjacencies();
  90921. var p0Index = indices[index];
  90922. var p1Index = indices[index + 1];
  90923. var p2Index = indices[index + 2];
  90924. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  90925. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  90926. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  90927. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  90928. faceNormal.normalize();
  90929. faceNormals.push(faceNormal);
  90930. adjacencies.push(faceAdjacencies);
  90931. }
  90932. // Scan
  90933. for (index = 0; index < adjacencies.length; index++) {
  90934. faceAdjacencies = adjacencies[index];
  90935. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  90936. var otherFaceAdjacencies = adjacencies[otherIndex];
  90937. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  90938. break;
  90939. }
  90940. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  90941. continue;
  90942. }
  90943. var otherP0 = indices[otherIndex * 3];
  90944. var otherP1 = indices[otherIndex * 3 + 1];
  90945. var otherP2 = indices[otherIndex * 3 + 2];
  90946. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  90947. var otherEdgeIndex = 0;
  90948. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  90949. continue;
  90950. }
  90951. switch (edgeIndex) {
  90952. case 0:
  90953. if (this._checkVerticesInsteadOfIndices) {
  90954. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90955. }
  90956. else {
  90957. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  90958. }
  90959. break;
  90960. case 1:
  90961. if (this._checkVerticesInsteadOfIndices) {
  90962. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90963. }
  90964. else {
  90965. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  90966. }
  90967. break;
  90968. case 2:
  90969. if (this._checkVerticesInsteadOfIndices) {
  90970. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  90971. }
  90972. else {
  90973. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  90974. }
  90975. break;
  90976. }
  90977. if (otherEdgeIndex === -1) {
  90978. continue;
  90979. }
  90980. faceAdjacencies.edges[edgeIndex] = otherIndex;
  90981. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  90982. faceAdjacencies.edgesConnectedCount++;
  90983. otherFaceAdjacencies.edgesConnectedCount++;
  90984. if (faceAdjacencies.edgesConnectedCount === 3) {
  90985. break;
  90986. }
  90987. }
  90988. }
  90989. }
  90990. // Create lines
  90991. for (index = 0; index < adjacencies.length; index++) {
  90992. // 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
  90993. var current = adjacencies[index];
  90994. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  90995. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  90996. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  90997. }
  90998. // Merge into a single mesh
  90999. var engine = this._source.getScene().getEngine();
  91000. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  91001. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  91002. this._ib = engine.createIndexBuffer(this._linesIndices);
  91003. this._indicesCount = this._linesIndices.length;
  91004. };
  91005. EdgesRenderer.prototype.render = function () {
  91006. var scene = this._source.getScene();
  91007. if (!this._lineShader.isReady() || !scene.activeCamera) {
  91008. return;
  91009. }
  91010. var engine = scene.getEngine();
  91011. this._lineShader._preBind();
  91012. // VBOs
  91013. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  91014. scene.resetCachedMaterial();
  91015. this._lineShader.setColor4("color", this._source.edgesColor);
  91016. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  91017. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  91018. }
  91019. else {
  91020. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  91021. }
  91022. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  91023. this._lineShader.bind(this._source.getWorldMatrix());
  91024. // Draw order
  91025. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  91026. this._lineShader.unbind();
  91027. engine.setDepthWrite(true);
  91028. };
  91029. return EdgesRenderer;
  91030. }());
  91031. BABYLON.EdgesRenderer = EdgesRenderer;
  91032. })(BABYLON || (BABYLON = {}));
  91033. //# sourceMappingURL=babylon.edgesRenderer.js.map
  91034. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91035. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91036. s = arguments[i];
  91037. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91038. t[p] = s[p];
  91039. }
  91040. return t;
  91041. };
  91042. var BABYLON;
  91043. (function (BABYLON) {
  91044. /**
  91045. * The effect layer Helps adding post process effect blended with the main pass.
  91046. *
  91047. * This can be for instance use to generate glow or higlight effects on the scene.
  91048. *
  91049. * The effect layer class can not be used directly and is intented to inherited from to be
  91050. * customized per effects.
  91051. */
  91052. var EffectLayer = /** @class */ (function () {
  91053. /**
  91054. * Instantiates a new effect Layer and references it in the scene.
  91055. * @param name The name of the layer
  91056. * @param scene The scene to use the layer in
  91057. */
  91058. function EffectLayer(
  91059. /** The Friendly of the effect in the scene */
  91060. name, scene) {
  91061. this._vertexBuffers = {};
  91062. this._maxSize = 0;
  91063. this._mainTextureDesiredSize = { width: 0, height: 0 };
  91064. this._shouldRender = true;
  91065. this._postProcesses = [];
  91066. this._textures = [];
  91067. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  91068. /**
  91069. * The clear color of the texture used to generate the glow map.
  91070. */
  91071. this.neutralColor = new BABYLON.Color4();
  91072. /**
  91073. * Specifies wether the highlight layer is enabled or not.
  91074. */
  91075. this.isEnabled = true;
  91076. /**
  91077. * An event triggered when the effect layer has been disposed.
  91078. */
  91079. this.onDisposeObservable = new BABYLON.Observable();
  91080. /**
  91081. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  91082. */
  91083. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  91084. /**
  91085. * An event triggered when the generated texture is being merged in the scene.
  91086. */
  91087. this.onBeforeComposeObservable = new BABYLON.Observable();
  91088. /**
  91089. * An event triggered when the generated texture has been merged in the scene.
  91090. */
  91091. this.onAfterComposeObservable = new BABYLON.Observable();
  91092. /**
  91093. * An event triggered when the efffect layer changes its size.
  91094. */
  91095. this.onSizeChangedObservable = new BABYLON.Observable();
  91096. this.name = name;
  91097. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91098. this._engine = scene.getEngine();
  91099. this._maxSize = this._engine.getCaps().maxTextureSize;
  91100. this._scene.effectLayers.push(this);
  91101. // Generate Buffers
  91102. this._generateIndexBuffer();
  91103. this._genrateVertexBuffer();
  91104. }
  91105. Object.defineProperty(EffectLayer.prototype, "camera", {
  91106. /**
  91107. * Gets the camera attached to the layer.
  91108. */
  91109. get: function () {
  91110. return this._effectLayerOptions.camera;
  91111. },
  91112. enumerable: true,
  91113. configurable: true
  91114. });
  91115. /**
  91116. * Initializes the effect layer with the required options.
  91117. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  91118. */
  91119. EffectLayer.prototype._init = function (options) {
  91120. // Adapt options
  91121. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91122. this._setMainTextureSize();
  91123. this._createMainTexture();
  91124. this._createTextureAndPostProcesses();
  91125. this._mergeEffect = this._createMergeEffect();
  91126. };
  91127. /**
  91128. * Generates the index buffer of the full screen quad blending to the main canvas.
  91129. */
  91130. EffectLayer.prototype._generateIndexBuffer = function () {
  91131. // Indices
  91132. var indices = [];
  91133. indices.push(0);
  91134. indices.push(1);
  91135. indices.push(2);
  91136. indices.push(0);
  91137. indices.push(2);
  91138. indices.push(3);
  91139. this._indexBuffer = this._engine.createIndexBuffer(indices);
  91140. };
  91141. /**
  91142. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  91143. */
  91144. EffectLayer.prototype._genrateVertexBuffer = function () {
  91145. // VBO
  91146. var vertices = [];
  91147. vertices.push(1, 1);
  91148. vertices.push(-1, 1);
  91149. vertices.push(-1, -1);
  91150. vertices.push(1, -1);
  91151. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91152. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91153. };
  91154. /**
  91155. * Sets the main texture desired size which is the closest power of two
  91156. * of the engine canvas size.
  91157. */
  91158. EffectLayer.prototype._setMainTextureSize = function () {
  91159. if (this._effectLayerOptions.mainTextureFixedSize) {
  91160. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  91161. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  91162. }
  91163. else {
  91164. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  91165. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  91166. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  91167. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  91168. }
  91169. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  91170. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  91171. };
  91172. /**
  91173. * Creates the main texture for the effect layer.
  91174. */
  91175. EffectLayer.prototype._createMainTexture = function () {
  91176. var _this = this;
  91177. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  91178. width: this._mainTextureDesiredSize.width,
  91179. height: this._mainTextureDesiredSize.height
  91180. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91181. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  91182. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91183. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91184. this._mainTexture.anisotropicFilteringLevel = 1;
  91185. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91186. this._mainTexture.renderParticles = false;
  91187. this._mainTexture.renderList = null;
  91188. this._mainTexture.ignoreCameraViewport = true;
  91189. // Custom render function
  91190. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  91191. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  91192. var index;
  91193. var engine = _this._scene.getEngine();
  91194. if (depthOnlySubMeshes.length) {
  91195. engine.setColorWrite(false);
  91196. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  91197. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  91198. }
  91199. engine.setColorWrite(true);
  91200. }
  91201. for (index = 0; index < opaqueSubMeshes.length; index++) {
  91202. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  91203. }
  91204. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  91205. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  91206. }
  91207. for (index = 0; index < transparentSubMeshes.length; index++) {
  91208. _this._renderSubMesh(transparentSubMeshes.data[index]);
  91209. }
  91210. };
  91211. this._mainTexture.onClearObservable.add(function (engine) {
  91212. engine.clear(_this.neutralColor, true, true, true);
  91213. });
  91214. };
  91215. /**
  91216. * Checks for the readiness of the element composing the layer.
  91217. * @param subMesh the mesh to check for
  91218. * @param useInstances specify wether or not to use instances to render the mesh
  91219. * @param emissiveTexture the associated emissive texture used to generate the glow
  91220. * @return true if ready otherwise, false
  91221. */
  91222. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  91223. var material = subMesh.getMaterial();
  91224. if (!material) {
  91225. return false;
  91226. }
  91227. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  91228. return false;
  91229. }
  91230. var defines = [];
  91231. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91232. var mesh = subMesh.getMesh();
  91233. var uv1 = false;
  91234. var uv2 = false;
  91235. // Alpha test
  91236. if (material && material.needAlphaTesting()) {
  91237. var alphaTexture = material.getAlphaTestTexture();
  91238. if (alphaTexture) {
  91239. defines.push("#define ALPHATEST");
  91240. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91241. alphaTexture.coordinatesIndex === 1) {
  91242. defines.push("#define DIFFUSEUV2");
  91243. uv2 = true;
  91244. }
  91245. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91246. defines.push("#define DIFFUSEUV1");
  91247. uv1 = true;
  91248. }
  91249. }
  91250. }
  91251. // Emissive
  91252. if (emissiveTexture) {
  91253. defines.push("#define EMISSIVE");
  91254. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91255. emissiveTexture.coordinatesIndex === 1) {
  91256. defines.push("#define EMISSIVEUV2");
  91257. uv2 = true;
  91258. }
  91259. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91260. defines.push("#define EMISSIVEUV1");
  91261. uv1 = true;
  91262. }
  91263. }
  91264. if (uv1) {
  91265. attribs.push(BABYLON.VertexBuffer.UVKind);
  91266. defines.push("#define UV1");
  91267. }
  91268. if (uv2) {
  91269. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91270. defines.push("#define UV2");
  91271. }
  91272. // Bones
  91273. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91274. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91275. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91276. if (mesh.numBoneInfluencers > 4) {
  91277. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91278. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91279. }
  91280. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91281. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  91282. }
  91283. else {
  91284. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91285. }
  91286. // Morph targets
  91287. var manager = mesh.morphTargetManager;
  91288. var morphInfluencers = 0;
  91289. if (manager) {
  91290. if (manager.numInfluencers > 0) {
  91291. defines.push("#define MORPHTARGETS");
  91292. morphInfluencers = manager.numInfluencers;
  91293. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  91294. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  91295. }
  91296. }
  91297. // Instances
  91298. if (useInstances) {
  91299. defines.push("#define INSTANCES");
  91300. attribs.push("world0");
  91301. attribs.push("world1");
  91302. attribs.push("world2");
  91303. attribs.push("world3");
  91304. }
  91305. // Get correct effect
  91306. var join = defines.join("\n");
  91307. if (this._cachedDefines !== join) {
  91308. this._cachedDefines = join;
  91309. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  91310. }
  91311. return this._effectLayerMapGenerationEffect.isReady();
  91312. };
  91313. /**
  91314. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  91315. */
  91316. EffectLayer.prototype.render = function () {
  91317. var currentEffect = this._mergeEffect;
  91318. // Check
  91319. if (!currentEffect.isReady())
  91320. return;
  91321. for (var i = 0; i < this._postProcesses.length; i++) {
  91322. if (!this._postProcesses[i].isReady()) {
  91323. return;
  91324. }
  91325. }
  91326. var engine = this._scene.getEngine();
  91327. this.onBeforeComposeObservable.notifyObservers(this);
  91328. // Render
  91329. engine.enableEffect(currentEffect);
  91330. engine.setState(false);
  91331. // VBOs
  91332. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91333. // Cache
  91334. var previousAlphaMode = engine.getAlphaMode();
  91335. // Go Blend.
  91336. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  91337. // Blends the map on the main canvas.
  91338. this._internalRender(currentEffect);
  91339. // Restore Alpha
  91340. engine.setAlphaMode(previousAlphaMode);
  91341. this.onAfterComposeObservable.notifyObservers(this);
  91342. // Handle size changes.
  91343. var size = this._mainTexture.getSize();
  91344. this._setMainTextureSize();
  91345. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  91346. // Recreate RTT and post processes on size change.
  91347. this.onSizeChangedObservable.notifyObservers(this);
  91348. this._disposeTextureAndPostProcesses();
  91349. this._createMainTexture();
  91350. this._createTextureAndPostProcesses();
  91351. }
  91352. };
  91353. /**
  91354. * Determine if a given mesh will be used in the current effect.
  91355. * @param mesh mesh to test
  91356. * @returns true if the mesh will be used
  91357. */
  91358. EffectLayer.prototype.hasMesh = function (mesh) {
  91359. return true;
  91360. };
  91361. /**
  91362. * Returns true if the layer contains information to display, otherwise false.
  91363. * @returns true if the glow layer should be rendered
  91364. */
  91365. EffectLayer.prototype.shouldRender = function () {
  91366. return this.isEnabled && this._shouldRender;
  91367. };
  91368. /**
  91369. * Returns true if the mesh should render, otherwise false.
  91370. * @param mesh The mesh to render
  91371. * @returns true if it should render otherwise false
  91372. */
  91373. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  91374. return true;
  91375. };
  91376. /**
  91377. * Returns true if the mesh should render, otherwise false.
  91378. * @param mesh The mesh to render
  91379. * @returns true if it should render otherwise false
  91380. */
  91381. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  91382. return true;
  91383. };
  91384. /**
  91385. * Renders the submesh passed in parameter to the generation map.
  91386. */
  91387. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  91388. var _this = this;
  91389. if (!this.shouldRender()) {
  91390. return;
  91391. }
  91392. var material = subMesh.getMaterial();
  91393. var mesh = subMesh.getRenderingMesh();
  91394. var scene = this._scene;
  91395. var engine = scene.getEngine();
  91396. if (!material) {
  91397. return;
  91398. }
  91399. // Do not block in blend mode.
  91400. if (material.needAlphaBlendingForMesh(mesh)) {
  91401. return;
  91402. }
  91403. // Culling
  91404. engine.setState(material.backFaceCulling);
  91405. // Managing instances
  91406. var batch = mesh._getInstancesRenderList(subMesh._id);
  91407. if (batch.mustReturn) {
  91408. return;
  91409. }
  91410. // Early Exit per mesh
  91411. if (!this._shouldRenderMesh(mesh)) {
  91412. return;
  91413. }
  91414. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91415. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  91416. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  91417. engine.enableEffect(this._effectLayerMapGenerationEffect);
  91418. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  91419. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  91420. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  91421. // Alpha test
  91422. if (material && material.needAlphaTesting()) {
  91423. var alphaTexture = material.getAlphaTestTexture();
  91424. if (alphaTexture) {
  91425. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  91426. var textureMatrix = alphaTexture.getTextureMatrix();
  91427. if (textureMatrix) {
  91428. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  91429. }
  91430. }
  91431. }
  91432. // Glow emissive only
  91433. if (this._emissiveTextureAndColor.texture) {
  91434. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  91435. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  91436. }
  91437. // Bones
  91438. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91439. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91440. }
  91441. // Morph targets
  91442. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  91443. // Draw
  91444. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  91445. }
  91446. else {
  91447. // Need to reset refresh rate of the shadowMap
  91448. this._mainTexture.resetRefreshCounter();
  91449. }
  91450. };
  91451. /**
  91452. * Rebuild the required buffers.
  91453. * @hidden Internal use only.
  91454. */
  91455. EffectLayer.prototype._rebuild = function () {
  91456. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91457. if (vb) {
  91458. vb._rebuild();
  91459. }
  91460. this._generateIndexBuffer();
  91461. };
  91462. /**
  91463. * Dispose only the render target textures and post process.
  91464. */
  91465. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  91466. this._mainTexture.dispose();
  91467. for (var i = 0; i < this._postProcesses.length; i++) {
  91468. if (this._postProcesses[i]) {
  91469. this._postProcesses[i].dispose();
  91470. }
  91471. }
  91472. this._postProcesses = [];
  91473. for (var i = 0; i < this._textures.length; i++) {
  91474. if (this._textures[i]) {
  91475. this._textures[i].dispose();
  91476. }
  91477. }
  91478. this._textures = [];
  91479. };
  91480. /**
  91481. * Dispose the highlight layer and free resources.
  91482. */
  91483. EffectLayer.prototype.dispose = function () {
  91484. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91485. if (vertexBuffer) {
  91486. vertexBuffer.dispose();
  91487. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91488. }
  91489. if (this._indexBuffer) {
  91490. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91491. this._indexBuffer = null;
  91492. }
  91493. // Clean textures and post processes
  91494. this._disposeTextureAndPostProcesses();
  91495. // Remove from scene
  91496. var index = this._scene.effectLayers.indexOf(this, 0);
  91497. if (index > -1) {
  91498. this._scene.effectLayers.splice(index, 1);
  91499. }
  91500. // Callback
  91501. this.onDisposeObservable.notifyObservers(this);
  91502. this.onDisposeObservable.clear();
  91503. this.onBeforeRenderMainTextureObservable.clear();
  91504. this.onBeforeComposeObservable.clear();
  91505. this.onAfterComposeObservable.clear();
  91506. this.onSizeChangedObservable.clear();
  91507. };
  91508. /**
  91509. * Gets the class name of the effect layer
  91510. * @returns the string with the class name of the effect layer
  91511. */
  91512. EffectLayer.prototype.getClassName = function () {
  91513. return "EffectLayer";
  91514. };
  91515. /**
  91516. * Creates an effect layer from parsed effect layer data
  91517. * @param parsedEffectLayer defines effect layer data
  91518. * @param scene defines the current scene
  91519. * @param rootUrl defines the root URL containing the effect layer information
  91520. * @returns a parsed effect Layer
  91521. */
  91522. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  91523. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  91524. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  91525. };
  91526. __decorate([
  91527. BABYLON.serialize()
  91528. ], EffectLayer.prototype, "name", void 0);
  91529. __decorate([
  91530. BABYLON.serializeAsColor4()
  91531. ], EffectLayer.prototype, "neutralColor", void 0);
  91532. __decorate([
  91533. BABYLON.serialize()
  91534. ], EffectLayer.prototype, "isEnabled", void 0);
  91535. __decorate([
  91536. BABYLON.serializeAsCameraReference()
  91537. ], EffectLayer.prototype, "camera", null);
  91538. return EffectLayer;
  91539. }());
  91540. BABYLON.EffectLayer = EffectLayer;
  91541. })(BABYLON || (BABYLON = {}));
  91542. //# sourceMappingURL=babylon.effectLayer.js.map
  91543. var BABYLON;
  91544. (function (BABYLON) {
  91545. /**
  91546. * Special Glow Blur post process only blurring the alpha channel
  91547. * It enforces keeping the most luminous color in the color channel.
  91548. */
  91549. var GlowBlurPostProcess = /** @class */ (function (_super) {
  91550. __extends(GlowBlurPostProcess, _super);
  91551. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  91552. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91553. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  91554. _this.direction = direction;
  91555. _this.kernel = kernel;
  91556. _this.onApplyObservable.add(function (effect) {
  91557. effect.setFloat2("screenSize", _this.width, _this.height);
  91558. effect.setVector2("direction", _this.direction);
  91559. effect.setFloat("blurWidth", _this.kernel);
  91560. });
  91561. return _this;
  91562. }
  91563. return GlowBlurPostProcess;
  91564. }(BABYLON.PostProcess));
  91565. /**
  91566. * The highlight layer Helps adding a glow effect around a mesh.
  91567. *
  91568. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91569. * glowy meshes to your scene.
  91570. *
  91571. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  91572. */
  91573. var HighlightLayer = /** @class */ (function (_super) {
  91574. __extends(HighlightLayer, _super);
  91575. /**
  91576. * Instantiates a new highlight Layer and references it to the scene..
  91577. * @param name The name of the layer
  91578. * @param scene The scene to use the layer in
  91579. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  91580. */
  91581. function HighlightLayer(name, scene, options) {
  91582. var _this = _super.call(this, name, scene) || this;
  91583. _this.name = name;
  91584. /**
  91585. * Specifies whether or not the inner glow is ACTIVE in the layer.
  91586. */
  91587. _this.innerGlow = true;
  91588. /**
  91589. * Specifies whether or not the outer glow is ACTIVE in the layer.
  91590. */
  91591. _this.outerGlow = true;
  91592. /**
  91593. * An event triggered when the highlight layer is being blurred.
  91594. */
  91595. _this.onBeforeBlurObservable = new BABYLON.Observable();
  91596. /**
  91597. * An event triggered when the highlight layer has been blurred.
  91598. */
  91599. _this.onAfterBlurObservable = new BABYLON.Observable();
  91600. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  91601. _this._meshes = {};
  91602. _this._excludedMeshes = {};
  91603. _this.neutralColor = HighlightLayer.NeutralColor;
  91604. // Warn on stencil
  91605. if (!_this._engine.isStencilEnable) {
  91606. 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 }");
  91607. }
  91608. // Adapt options
  91609. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91610. // Initialize the layer
  91611. _this._init({
  91612. alphaBlendingMode: _this._options.alphaBlendingMode,
  91613. camera: _this._options.camera,
  91614. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91615. mainTextureRatio: _this._options.mainTextureRatio
  91616. });
  91617. // Do not render as long as no meshes have been added
  91618. _this._shouldRender = false;
  91619. return _this;
  91620. }
  91621. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  91622. /**
  91623. * Gets the horizontal size of the blur.
  91624. */
  91625. get: function () {
  91626. return this._horizontalBlurPostprocess.kernel;
  91627. },
  91628. /**
  91629. * Specifies the horizontal size of the blur.
  91630. */
  91631. set: function (value) {
  91632. this._horizontalBlurPostprocess.kernel = value;
  91633. },
  91634. enumerable: true,
  91635. configurable: true
  91636. });
  91637. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  91638. /**
  91639. * Gets the vertical size of the blur.
  91640. */
  91641. get: function () {
  91642. return this._verticalBlurPostprocess.kernel;
  91643. },
  91644. /**
  91645. * Specifies the vertical size of the blur.
  91646. */
  91647. set: function (value) {
  91648. this._verticalBlurPostprocess.kernel = value;
  91649. },
  91650. enumerable: true,
  91651. configurable: true
  91652. });
  91653. /**
  91654. * Get the effect name of the layer.
  91655. * @return The effect name
  91656. */
  91657. HighlightLayer.prototype.getEffectName = function () {
  91658. return HighlightLayer.EffectName;
  91659. };
  91660. /**
  91661. * Create the merge effect. This is the shader use to blit the information back
  91662. * to the main canvas at the end of the scene rendering.
  91663. */
  91664. HighlightLayer.prototype._createMergeEffect = function () {
  91665. // Effect
  91666. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  91667. };
  91668. /**
  91669. * Creates the render target textures and post processes used in the highlight layer.
  91670. */
  91671. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  91672. var _this = this;
  91673. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  91674. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  91675. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91676. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91677. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  91678. width: blurTextureWidth,
  91679. height: blurTextureHeight
  91680. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91681. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91682. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91683. this._blurTexture.anisotropicFilteringLevel = 16;
  91684. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  91685. this._blurTexture.renderParticles = false;
  91686. this._blurTexture.ignoreCameraViewport = true;
  91687. this._textures = [this._blurTexture];
  91688. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  91689. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91690. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  91691. effect.setTexture("textureSampler", _this._mainTexture);
  91692. });
  91693. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91694. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91695. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91696. });
  91697. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91698. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  91699. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91700. });
  91701. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91702. }
  91703. else {
  91704. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  91705. width: blurTextureWidth,
  91706. height: blurTextureHeight
  91707. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91708. this._horizontalBlurPostprocess.width = blurTextureWidth;
  91709. this._horizontalBlurPostprocess.height = blurTextureHeight;
  91710. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91711. effect.setTexture("textureSampler", _this._mainTexture);
  91712. });
  91713. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  91714. width: blurTextureWidth,
  91715. height: blurTextureHeight
  91716. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91717. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91718. }
  91719. this._mainTexture.onAfterUnbindObservable.add(function () {
  91720. _this.onBeforeBlurObservable.notifyObservers(_this);
  91721. var internalTexture = _this._blurTexture.getInternalTexture();
  91722. if (internalTexture) {
  91723. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  91724. }
  91725. _this.onAfterBlurObservable.notifyObservers(_this);
  91726. });
  91727. // Prevent autoClear.
  91728. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91729. };
  91730. /**
  91731. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91732. */
  91733. HighlightLayer.prototype.needStencil = function () {
  91734. return true;
  91735. };
  91736. /**
  91737. * Checks for the readiness of the element composing the layer.
  91738. * @param subMesh the mesh to check for
  91739. * @param useInstances specify wether or not to use instances to render the mesh
  91740. * @param emissiveTexture the associated emissive texture used to generate the glow
  91741. * @return true if ready otherwise, false
  91742. */
  91743. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  91744. var material = subMesh.getMaterial();
  91745. var mesh = subMesh.getRenderingMesh();
  91746. if (!material || !mesh || !this._meshes) {
  91747. return false;
  91748. }
  91749. var emissiveTexture = null;
  91750. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91751. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91752. emissiveTexture = material.emissiveTexture;
  91753. }
  91754. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91755. };
  91756. /**
  91757. * Implementation specific of rendering the generating effect on the main canvas.
  91758. * @param effect The effect used to render through
  91759. */
  91760. HighlightLayer.prototype._internalRender = function (effect) {
  91761. // Texture
  91762. effect.setTexture("textureSampler", this._blurTexture);
  91763. // Cache
  91764. var engine = this._engine;
  91765. var previousStencilBuffer = engine.getStencilBuffer();
  91766. var previousStencilFunction = engine.getStencilFunction();
  91767. var previousStencilMask = engine.getStencilMask();
  91768. var previousStencilOperationPass = engine.getStencilOperationPass();
  91769. var previousStencilOperationFail = engine.getStencilOperationFail();
  91770. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  91771. var previousStencilReference = engine.getStencilFunctionReference();
  91772. // Stencil operations
  91773. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  91774. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  91775. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  91776. // Draw order
  91777. engine.setStencilMask(0x00);
  91778. engine.setStencilBuffer(true);
  91779. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  91780. // 2 passes inner outer
  91781. if (this.outerGlow) {
  91782. effect.setFloat("offset", 0);
  91783. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  91784. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91785. }
  91786. if (this.innerGlow) {
  91787. effect.setFloat("offset", 1);
  91788. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  91789. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91790. }
  91791. // Restore Cache
  91792. engine.setStencilFunction(previousStencilFunction);
  91793. engine.setStencilMask(previousStencilMask);
  91794. engine.setStencilBuffer(previousStencilBuffer);
  91795. engine.setStencilOperationPass(previousStencilOperationPass);
  91796. engine.setStencilOperationFail(previousStencilOperationFail);
  91797. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  91798. engine.setStencilFunctionReference(previousStencilReference);
  91799. };
  91800. /**
  91801. * Returns true if the layer contains information to display, otherwise false.
  91802. */
  91803. HighlightLayer.prototype.shouldRender = function () {
  91804. if (_super.prototype.shouldRender.call(this)) {
  91805. return this._meshes ? true : false;
  91806. }
  91807. return false;
  91808. };
  91809. /**
  91810. * Returns true if the mesh should render, otherwise false.
  91811. * @param mesh The mesh to render
  91812. * @returns true if it should render otherwise false
  91813. */
  91814. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  91815. // Excluded Mesh
  91816. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  91817. return false;
  91818. }
  91819. ;
  91820. return true;
  91821. };
  91822. /**
  91823. * Sets the required values for both the emissive texture and and the main color.
  91824. */
  91825. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  91826. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91827. if (highlightLayerMesh) {
  91828. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  91829. }
  91830. else {
  91831. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  91832. }
  91833. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91834. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  91835. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  91836. }
  91837. else {
  91838. this._emissiveTextureAndColor.texture = null;
  91839. }
  91840. };
  91841. /**
  91842. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  91843. * @param mesh The mesh to exclude from the highlight layer
  91844. */
  91845. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  91846. if (!this._excludedMeshes) {
  91847. return;
  91848. }
  91849. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91850. if (!meshExcluded) {
  91851. this._excludedMeshes[mesh.uniqueId] = {
  91852. mesh: mesh,
  91853. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  91854. mesh.getEngine().setStencilBuffer(false);
  91855. }),
  91856. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  91857. mesh.getEngine().setStencilBuffer(true);
  91858. }),
  91859. };
  91860. }
  91861. };
  91862. /**
  91863. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  91864. * @param mesh The mesh to highlight
  91865. */
  91866. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  91867. if (!this._excludedMeshes) {
  91868. return;
  91869. }
  91870. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  91871. if (meshExcluded) {
  91872. if (meshExcluded.beforeRender) {
  91873. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  91874. }
  91875. if (meshExcluded.afterRender) {
  91876. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  91877. }
  91878. }
  91879. this._excludedMeshes[mesh.uniqueId] = null;
  91880. };
  91881. /**
  91882. * Determine if a given mesh will be highlighted by the current HighlightLayer
  91883. * @param mesh mesh to test
  91884. * @returns true if the mesh will be highlighted by the current HighlightLayer
  91885. */
  91886. HighlightLayer.prototype.hasMesh = function (mesh) {
  91887. if (!this._meshes) {
  91888. return false;
  91889. }
  91890. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  91891. };
  91892. /**
  91893. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  91894. * @param mesh The mesh to highlight
  91895. * @param color The color of the highlight
  91896. * @param glowEmissiveOnly Extract the glow from the emissive texture
  91897. */
  91898. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  91899. var _this = this;
  91900. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  91901. if (!this._meshes) {
  91902. return;
  91903. }
  91904. var meshHighlight = this._meshes[mesh.uniqueId];
  91905. if (meshHighlight) {
  91906. meshHighlight.color = color;
  91907. }
  91908. else {
  91909. this._meshes[mesh.uniqueId] = {
  91910. mesh: mesh,
  91911. color: color,
  91912. // Lambda required for capture due to Observable this context
  91913. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  91914. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  91915. _this._defaultStencilReference(mesh);
  91916. }
  91917. else {
  91918. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  91919. }
  91920. }),
  91921. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  91922. glowEmissiveOnly: glowEmissiveOnly
  91923. };
  91924. }
  91925. this._shouldRender = true;
  91926. };
  91927. /**
  91928. * Remove a mesh from the highlight layer in order to make it stop glowing.
  91929. * @param mesh The mesh to highlight
  91930. */
  91931. HighlightLayer.prototype.removeMesh = function (mesh) {
  91932. if (!this._meshes) {
  91933. return;
  91934. }
  91935. var meshHighlight = this._meshes[mesh.uniqueId];
  91936. if (meshHighlight) {
  91937. if (meshHighlight.observerHighlight) {
  91938. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  91939. }
  91940. if (meshHighlight.observerDefault) {
  91941. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  91942. }
  91943. delete this._meshes[mesh.uniqueId];
  91944. }
  91945. this._shouldRender = false;
  91946. for (var meshHighlightToCheck in this._meshes) {
  91947. if (this._meshes[meshHighlightToCheck]) {
  91948. this._shouldRender = true;
  91949. break;
  91950. }
  91951. }
  91952. };
  91953. /**
  91954. * Force the stencil to the normal expected value for none glowing parts
  91955. */
  91956. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  91957. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  91958. };
  91959. /**
  91960. * Free any resources and references associated to a mesh.
  91961. * Internal use
  91962. * @param mesh The mesh to free.
  91963. */
  91964. HighlightLayer.prototype._disposeMesh = function (mesh) {
  91965. this.removeMesh(mesh);
  91966. this.removeExcludedMesh(mesh);
  91967. };
  91968. /**
  91969. * Dispose the highlight layer and free resources.
  91970. */
  91971. HighlightLayer.prototype.dispose = function () {
  91972. if (this._meshes) {
  91973. // Clean mesh references
  91974. for (var id in this._meshes) {
  91975. var meshHighlight = this._meshes[id];
  91976. if (meshHighlight && meshHighlight.mesh) {
  91977. if (meshHighlight.observerHighlight) {
  91978. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  91979. }
  91980. if (meshHighlight.observerDefault) {
  91981. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  91982. }
  91983. }
  91984. }
  91985. this._meshes = null;
  91986. }
  91987. if (this._excludedMeshes) {
  91988. for (var id in this._excludedMeshes) {
  91989. var meshHighlight = this._excludedMeshes[id];
  91990. if (meshHighlight) {
  91991. if (meshHighlight.beforeRender) {
  91992. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  91993. }
  91994. if (meshHighlight.afterRender) {
  91995. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  91996. }
  91997. }
  91998. }
  91999. this._excludedMeshes = null;
  92000. }
  92001. _super.prototype.dispose.call(this);
  92002. };
  92003. /**
  92004. * Gets the class name of the effect layer
  92005. * @returns the string with the class name of the effect layer
  92006. */
  92007. HighlightLayer.prototype.getClassName = function () {
  92008. return "HighlightLayer";
  92009. };
  92010. /**
  92011. * Serializes this Highlight layer
  92012. * @returns a serialized Highlight layer object
  92013. */
  92014. HighlightLayer.prototype.serialize = function () {
  92015. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92016. serializationObject.customType = "BABYLON.HighlightLayer";
  92017. // Highlighted meshes
  92018. serializationObject.meshes = [];
  92019. if (this._meshes) {
  92020. for (var m in this._meshes) {
  92021. var mesh = this._meshes[m];
  92022. if (mesh) {
  92023. serializationObject.meshes.push({
  92024. glowEmissiveOnly: mesh.glowEmissiveOnly,
  92025. color: mesh.color.asArray(),
  92026. meshId: mesh.mesh.id
  92027. });
  92028. }
  92029. }
  92030. }
  92031. // Excluded meshes
  92032. serializationObject.excludedMeshes = [];
  92033. if (this._excludedMeshes) {
  92034. for (var e in this._excludedMeshes) {
  92035. var excludedMesh = this._excludedMeshes[e];
  92036. if (excludedMesh) {
  92037. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  92038. }
  92039. }
  92040. }
  92041. return serializationObject;
  92042. };
  92043. /**
  92044. * Creates a Highlight layer from parsed Highlight layer data
  92045. * @param parsedHightlightLayer defines the Highlight layer data
  92046. * @param scene defines the current scene
  92047. * @param rootUrl defines the root URL containing the Highlight layer information
  92048. * @returns a parsed Highlight layer
  92049. */
  92050. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  92051. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  92052. var index;
  92053. // Excluded meshes
  92054. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  92055. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  92056. if (mesh) {
  92057. hl.addExcludedMesh(mesh);
  92058. }
  92059. }
  92060. // Included meshes
  92061. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  92062. var highlightedMesh = parsedHightlightLayer.meshes[index];
  92063. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  92064. if (mesh) {
  92065. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  92066. }
  92067. }
  92068. return hl;
  92069. };
  92070. /**
  92071. * Effect Name of the highlight layer.
  92072. */
  92073. HighlightLayer.EffectName = "HighlightLayer";
  92074. /**
  92075. * The neutral color used during the preparation of the glow effect.
  92076. * This is black by default as the blend operation is a blend operation.
  92077. */
  92078. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  92079. /**
  92080. * Stencil value used for glowing meshes.
  92081. */
  92082. HighlightLayer.GlowingMeshStencilReference = 0x02;
  92083. /**
  92084. * Stencil value used for the other meshes in the scene.
  92085. */
  92086. HighlightLayer.NormalMeshStencilReference = 0x01;
  92087. __decorate([
  92088. BABYLON.serialize()
  92089. ], HighlightLayer.prototype, "innerGlow", void 0);
  92090. __decorate([
  92091. BABYLON.serialize()
  92092. ], HighlightLayer.prototype, "outerGlow", void 0);
  92093. __decorate([
  92094. BABYLON.serialize()
  92095. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  92096. __decorate([
  92097. BABYLON.serialize()
  92098. ], HighlightLayer.prototype, "blurVerticalSize", null);
  92099. __decorate([
  92100. BABYLON.serialize("options")
  92101. ], HighlightLayer.prototype, "_options", void 0);
  92102. return HighlightLayer;
  92103. }(BABYLON.EffectLayer));
  92104. BABYLON.HighlightLayer = HighlightLayer;
  92105. })(BABYLON || (BABYLON = {}));
  92106. //# sourceMappingURL=babylon.highlightLayer.js.map
  92107. var BABYLON;
  92108. (function (BABYLON) {
  92109. /**
  92110. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  92111. *
  92112. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92113. * glowy meshes to your scene.
  92114. *
  92115. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  92116. */
  92117. var GlowLayer = /** @class */ (function (_super) {
  92118. __extends(GlowLayer, _super);
  92119. /**
  92120. * Instantiates a new glow Layer and references it to the scene.
  92121. * @param name The name of the layer
  92122. * @param scene The scene to use the layer in
  92123. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  92124. */
  92125. function GlowLayer(name, scene, options) {
  92126. var _this = _super.call(this, name, scene) || this;
  92127. _this._intensity = 1.0;
  92128. _this._includedOnlyMeshes = [];
  92129. _this._excludedMeshes = [];
  92130. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  92131. // Adapt options
  92132. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  92133. // Initialize the layer
  92134. _this._init({
  92135. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  92136. camera: _this._options.camera,
  92137. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92138. mainTextureRatio: _this._options.mainTextureRatio
  92139. });
  92140. return _this;
  92141. }
  92142. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  92143. /**
  92144. * Gets the kernel size of the blur.
  92145. */
  92146. get: function () {
  92147. return this._horizontalBlurPostprocess1.kernel;
  92148. },
  92149. /**
  92150. * Sets the kernel size of the blur.
  92151. */
  92152. set: function (value) {
  92153. this._horizontalBlurPostprocess1.kernel = value;
  92154. this._verticalBlurPostprocess1.kernel = value;
  92155. this._horizontalBlurPostprocess2.kernel = value;
  92156. this._verticalBlurPostprocess2.kernel = value;
  92157. },
  92158. enumerable: true,
  92159. configurable: true
  92160. });
  92161. Object.defineProperty(GlowLayer.prototype, "intensity", {
  92162. /**
  92163. * Gets the glow intensity.
  92164. */
  92165. get: function () {
  92166. return this._intensity;
  92167. },
  92168. /**
  92169. * Sets the glow intensity.
  92170. */
  92171. set: function (value) {
  92172. this._intensity = value;
  92173. },
  92174. enumerable: true,
  92175. configurable: true
  92176. });
  92177. /**
  92178. * Get the effect name of the layer.
  92179. * @return The effect name
  92180. */
  92181. GlowLayer.prototype.getEffectName = function () {
  92182. return GlowLayer.EffectName;
  92183. };
  92184. /**
  92185. * Create the merge effect. This is the shader use to blit the information back
  92186. * to the main canvas at the end of the scene rendering.
  92187. */
  92188. GlowLayer.prototype._createMergeEffect = function () {
  92189. // Effect
  92190. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  92191. };
  92192. /**
  92193. * Creates the render target textures and post processes used in the glow layer.
  92194. */
  92195. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  92196. var _this = this;
  92197. var blurTextureWidth = this._mainTextureDesiredSize.width;
  92198. var blurTextureHeight = this._mainTextureDesiredSize.height;
  92199. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92200. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92201. var textureType = 0;
  92202. if (this._engine.getCaps().textureHalfFloatRender) {
  92203. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92204. }
  92205. else {
  92206. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92207. }
  92208. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  92209. width: blurTextureWidth,
  92210. height: blurTextureHeight
  92211. }, this._scene, false, true, textureType);
  92212. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92213. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92214. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92215. this._blurTexture1.renderParticles = false;
  92216. this._blurTexture1.ignoreCameraViewport = true;
  92217. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  92218. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  92219. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  92220. width: blurTextureWidth2,
  92221. height: blurTextureHeight2
  92222. }, this._scene, false, true, textureType);
  92223. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92224. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92225. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92226. this._blurTexture2.renderParticles = false;
  92227. this._blurTexture2.ignoreCameraViewport = true;
  92228. this._textures = [this._blurTexture1, this._blurTexture2];
  92229. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92230. width: blurTextureWidth,
  92231. height: blurTextureHeight
  92232. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92233. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  92234. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  92235. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  92236. effect.setTexture("textureSampler", _this._mainTexture);
  92237. });
  92238. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92239. width: blurTextureWidth,
  92240. height: blurTextureHeight
  92241. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92242. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92243. width: blurTextureWidth2,
  92244. height: blurTextureHeight2
  92245. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92246. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  92247. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  92248. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  92249. effect.setTexture("textureSampler", _this._blurTexture1);
  92250. });
  92251. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92252. width: blurTextureWidth2,
  92253. height: blurTextureHeight2
  92254. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92255. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92256. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  92257. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92258. this._mainTexture.samples = this._options.mainTextureSamples;
  92259. this._mainTexture.onAfterUnbindObservable.add(function () {
  92260. var internalTexture = _this._blurTexture1.getInternalTexture();
  92261. if (internalTexture) {
  92262. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  92263. internalTexture = _this._blurTexture2.getInternalTexture();
  92264. if (internalTexture) {
  92265. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  92266. }
  92267. }
  92268. });
  92269. // Prevent autoClear.
  92270. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92271. };
  92272. /**
  92273. * Checks for the readiness of the element composing the layer.
  92274. * @param subMesh the mesh to check for
  92275. * @param useInstances specify wether or not to use instances to render the mesh
  92276. * @param emissiveTexture the associated emissive texture used to generate the glow
  92277. * @return true if ready otherwise, false
  92278. */
  92279. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  92280. var material = subMesh.getMaterial();
  92281. var mesh = subMesh.getRenderingMesh();
  92282. if (!material || !mesh) {
  92283. return false;
  92284. }
  92285. var emissiveTexture = material.emissiveTexture;
  92286. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92287. };
  92288. /**
  92289. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92290. */
  92291. GlowLayer.prototype.needStencil = function () {
  92292. return false;
  92293. };
  92294. /**
  92295. * Implementation specific of rendering the generating effect on the main canvas.
  92296. * @param effect The effect used to render through
  92297. */
  92298. GlowLayer.prototype._internalRender = function (effect) {
  92299. // Texture
  92300. effect.setTexture("textureSampler", this._blurTexture1);
  92301. effect.setTexture("textureSampler2", this._blurTexture2);
  92302. effect.setFloat("offset", this._intensity);
  92303. // Cache
  92304. var engine = this._engine;
  92305. var previousStencilBuffer = engine.getStencilBuffer();
  92306. // Draw order
  92307. engine.setStencilBuffer(false);
  92308. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92309. // Draw order
  92310. engine.setStencilBuffer(previousStencilBuffer);
  92311. };
  92312. /**
  92313. * Sets the required values for both the emissive texture and and the main color.
  92314. */
  92315. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92316. var textureLevel = 1.0;
  92317. if (this.customEmissiveTextureSelector) {
  92318. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  92319. }
  92320. else {
  92321. if (material) {
  92322. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92323. if (this._emissiveTextureAndColor.texture) {
  92324. textureLevel = this._emissiveTextureAndColor.texture.level;
  92325. }
  92326. }
  92327. else {
  92328. this._emissiveTextureAndColor.texture = null;
  92329. }
  92330. }
  92331. if (this.customEmissiveColorSelector) {
  92332. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  92333. }
  92334. else {
  92335. if (material.emissiveColor) {
  92336. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  92337. }
  92338. else {
  92339. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92340. }
  92341. }
  92342. };
  92343. /**
  92344. * Returns true if the mesh should render, otherwise false.
  92345. * @param mesh The mesh to render
  92346. * @returns true if it should render otherwise false
  92347. */
  92348. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  92349. return this.hasMesh(mesh);
  92350. };
  92351. /**
  92352. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  92353. * @param mesh The mesh to exclude from the glow layer
  92354. */
  92355. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  92356. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  92357. this._excludedMeshes.push(mesh.uniqueId);
  92358. }
  92359. };
  92360. /**
  92361. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  92362. * @param mesh The mesh to remove
  92363. */
  92364. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  92365. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  92366. if (index !== -1) {
  92367. this._excludedMeshes.splice(index, 1);
  92368. }
  92369. };
  92370. /**
  92371. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  92372. * @param mesh The mesh to include in the glow layer
  92373. */
  92374. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  92375. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  92376. this._includedOnlyMeshes.push(mesh.uniqueId);
  92377. }
  92378. };
  92379. /**
  92380. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  92381. * @param mesh The mesh to remove
  92382. */
  92383. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  92384. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  92385. if (index !== -1) {
  92386. this._includedOnlyMeshes.splice(index, 1);
  92387. }
  92388. };
  92389. /**
  92390. * Determine if a given mesh will be used in the glow layer
  92391. * @param mesh The mesh to test
  92392. * @returns true if the mesh will be highlighted by the current glow layer
  92393. */
  92394. GlowLayer.prototype.hasMesh = function (mesh) {
  92395. // Included Mesh
  92396. if (this._includedOnlyMeshes.length) {
  92397. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  92398. }
  92399. ;
  92400. // Excluded Mesh
  92401. if (this._excludedMeshes.length) {
  92402. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  92403. }
  92404. ;
  92405. return true;
  92406. };
  92407. /**
  92408. * Free any resources and references associated to a mesh.
  92409. * Internal use
  92410. * @param mesh The mesh to free.
  92411. */
  92412. GlowLayer.prototype._disposeMesh = function (mesh) {
  92413. this.removeIncludedOnlyMesh(mesh);
  92414. this.removeExcludedMesh(mesh);
  92415. };
  92416. /**
  92417. * Gets the class name of the effect layer
  92418. * @returns the string with the class name of the effect layer
  92419. */
  92420. GlowLayer.prototype.getClassName = function () {
  92421. return "GlowLayer";
  92422. };
  92423. /**
  92424. * Serializes this glow layer
  92425. * @returns a serialized glow layer object
  92426. */
  92427. GlowLayer.prototype.serialize = function () {
  92428. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92429. serializationObject.customType = "BABYLON.GlowLayer";
  92430. var index;
  92431. // Included meshes
  92432. serializationObject.includedMeshes = [];
  92433. if (this._includedOnlyMeshes.length) {
  92434. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  92435. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  92436. if (mesh) {
  92437. serializationObject.includedMeshes.push(mesh.id);
  92438. }
  92439. }
  92440. }
  92441. // Excluded meshes
  92442. serializationObject.excludedMeshes = [];
  92443. if (this._excludedMeshes.length) {
  92444. for (index = 0; index < this._excludedMeshes.length; index++) {
  92445. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  92446. if (mesh) {
  92447. serializationObject.excludedMeshes.push(mesh.id);
  92448. }
  92449. }
  92450. }
  92451. return serializationObject;
  92452. };
  92453. /**
  92454. * Creates a Glow Layer from parsed glow layer data
  92455. * @param parsedGlowLayer defines glow layer data
  92456. * @param scene defines the current scene
  92457. * @param rootUrl defines the root URL containing the glow layer information
  92458. * @returns a parsed Glow Layer
  92459. */
  92460. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  92461. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  92462. var index;
  92463. // Excluded meshes
  92464. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  92465. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  92466. if (mesh) {
  92467. gl.addExcludedMesh(mesh);
  92468. }
  92469. }
  92470. // Included meshes
  92471. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  92472. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  92473. if (mesh) {
  92474. gl.addIncludedOnlyMesh(mesh);
  92475. }
  92476. }
  92477. return gl;
  92478. };
  92479. /**
  92480. * Effect Name of the layer.
  92481. */
  92482. GlowLayer.EffectName = "GlowLayer";
  92483. /**
  92484. * The default blur kernel size used for the glow.
  92485. */
  92486. GlowLayer.DefaultBlurKernelSize = 32;
  92487. /**
  92488. * The default texture size ratio used for the glow.
  92489. */
  92490. GlowLayer.DefaultTextureRatio = 0.5;
  92491. __decorate([
  92492. BABYLON.serialize()
  92493. ], GlowLayer.prototype, "blurKernelSize", null);
  92494. __decorate([
  92495. BABYLON.serialize()
  92496. ], GlowLayer.prototype, "intensity", null);
  92497. __decorate([
  92498. BABYLON.serialize("options")
  92499. ], GlowLayer.prototype, "_options", void 0);
  92500. return GlowLayer;
  92501. }(BABYLON.EffectLayer));
  92502. BABYLON.GlowLayer = GlowLayer;
  92503. })(BABYLON || (BABYLON = {}));
  92504. //# sourceMappingURL=babylon.glowLayer.js.map
  92505. var BABYLON;
  92506. (function (BABYLON) {
  92507. /**
  92508. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  92509. */
  92510. var AssetTaskState;
  92511. (function (AssetTaskState) {
  92512. /**
  92513. * Initialization
  92514. */
  92515. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  92516. /**
  92517. * Running
  92518. */
  92519. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  92520. /**
  92521. * Done
  92522. */
  92523. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  92524. /**
  92525. * Error
  92526. */
  92527. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  92528. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  92529. /**
  92530. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  92531. */
  92532. var AbstractAssetTask = /** @class */ (function () {
  92533. /**
  92534. * Creates a new {BABYLON.AssetsManager}
  92535. * @param name defines the name of the task
  92536. */
  92537. function AbstractAssetTask(
  92538. /**
  92539. * Task name
  92540. */ name) {
  92541. this.name = name;
  92542. this._isCompleted = false;
  92543. this._taskState = AssetTaskState.INIT;
  92544. }
  92545. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  92546. /**
  92547. * Get if the task is completed
  92548. */
  92549. get: function () {
  92550. return this._isCompleted;
  92551. },
  92552. enumerable: true,
  92553. configurable: true
  92554. });
  92555. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  92556. /**
  92557. * Gets the current state of the task
  92558. */
  92559. get: function () {
  92560. return this._taskState;
  92561. },
  92562. enumerable: true,
  92563. configurable: true
  92564. });
  92565. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  92566. /**
  92567. * Gets the current error object (if task is in error)
  92568. */
  92569. get: function () {
  92570. return this._errorObject;
  92571. },
  92572. enumerable: true,
  92573. configurable: true
  92574. });
  92575. /**
  92576. * Internal only
  92577. * @hidden
  92578. */
  92579. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  92580. if (this._errorObject) {
  92581. return;
  92582. }
  92583. this._errorObject = {
  92584. message: message,
  92585. exception: exception
  92586. };
  92587. };
  92588. /**
  92589. * Execute the current task
  92590. * @param scene defines the scene where you want your assets to be loaded
  92591. * @param onSuccess is a callback called when the task is successfully executed
  92592. * @param onError is a callback called if an error occurs
  92593. */
  92594. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92595. var _this = this;
  92596. this._taskState = AssetTaskState.RUNNING;
  92597. this.runTask(scene, function () {
  92598. _this.onDoneCallback(onSuccess, onError);
  92599. }, function (msg, exception) {
  92600. _this.onErrorCallback(onError, msg, exception);
  92601. });
  92602. };
  92603. /**
  92604. * Execute the current task
  92605. * @param scene defines the scene where you want your assets to be loaded
  92606. * @param onSuccess is a callback called when the task is successfully executed
  92607. * @param onError is a callback called if an error occurs
  92608. */
  92609. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92610. throw new Error("runTask is not implemented");
  92611. };
  92612. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  92613. this._taskState = AssetTaskState.ERROR;
  92614. this._errorObject = {
  92615. message: message,
  92616. exception: exception
  92617. };
  92618. if (this.onError) {
  92619. this.onError(this, message, exception);
  92620. }
  92621. onError();
  92622. };
  92623. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  92624. try {
  92625. this._taskState = AssetTaskState.DONE;
  92626. this._isCompleted = true;
  92627. if (this.onSuccess) {
  92628. this.onSuccess(this);
  92629. }
  92630. onSuccess();
  92631. }
  92632. catch (e) {
  92633. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  92634. }
  92635. };
  92636. return AbstractAssetTask;
  92637. }());
  92638. BABYLON.AbstractAssetTask = AbstractAssetTask;
  92639. /**
  92640. * Class used to share progress information about assets loading
  92641. */
  92642. var AssetsProgressEvent = /** @class */ (function () {
  92643. /**
  92644. * Creates a {BABYLON.AssetsProgressEvent}
  92645. * @param remainingCount defines the number of remaining tasks to process
  92646. * @param totalCount defines the total number of tasks
  92647. * @param task defines the task that was just processed
  92648. */
  92649. function AssetsProgressEvent(remainingCount, totalCount, task) {
  92650. this.remainingCount = remainingCount;
  92651. this.totalCount = totalCount;
  92652. this.task = task;
  92653. }
  92654. return AssetsProgressEvent;
  92655. }());
  92656. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  92657. /**
  92658. * Define a task used by {BABYLON.AssetsManager} to load meshes
  92659. */
  92660. var MeshAssetTask = /** @class */ (function (_super) {
  92661. __extends(MeshAssetTask, _super);
  92662. /**
  92663. * Creates a new {BABYLON.MeshAssetTask}
  92664. * @param name defines the name of the task
  92665. * @param meshesNames defines the list of mesh's names you want to load
  92666. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  92667. * @param sceneFilename defines the filename of the scene to load from
  92668. */
  92669. function MeshAssetTask(
  92670. /**
  92671. * Defines the name of the task
  92672. */
  92673. name,
  92674. /**
  92675. * Defines the list of mesh's names you want to load
  92676. */
  92677. meshesNames,
  92678. /**
  92679. * Defines the root url to use as a base to load your meshes and associated resources
  92680. */
  92681. rootUrl,
  92682. /**
  92683. * Defines the filename of the scene to load from
  92684. */
  92685. sceneFilename) {
  92686. var _this = _super.call(this, name) || this;
  92687. _this.name = name;
  92688. _this.meshesNames = meshesNames;
  92689. _this.rootUrl = rootUrl;
  92690. _this.sceneFilename = sceneFilename;
  92691. return _this;
  92692. }
  92693. /**
  92694. * Execute the current task
  92695. * @param scene defines the scene where you want your assets to be loaded
  92696. * @param onSuccess is a callback called when the task is successfully executed
  92697. * @param onError is a callback called if an error occurs
  92698. */
  92699. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92700. var _this = this;
  92701. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  92702. _this.loadedMeshes = meshes;
  92703. _this.loadedParticleSystems = particleSystems;
  92704. _this.loadedSkeletons = skeletons;
  92705. onSuccess();
  92706. }, null, function (scene, message, exception) {
  92707. onError(message, exception);
  92708. });
  92709. };
  92710. return MeshAssetTask;
  92711. }(AbstractAssetTask));
  92712. BABYLON.MeshAssetTask = MeshAssetTask;
  92713. /**
  92714. * Define a task used by {BABYLON.AssetsManager} to load text content
  92715. */
  92716. var TextFileAssetTask = /** @class */ (function (_super) {
  92717. __extends(TextFileAssetTask, _super);
  92718. /**
  92719. * Creates a new TextFileAssetTask object
  92720. * @param name defines the name of the task
  92721. * @param url defines the location of the file to load
  92722. */
  92723. function TextFileAssetTask(
  92724. /**
  92725. * Defines the name of the task
  92726. */
  92727. name,
  92728. /**
  92729. * Defines the location of the file to load
  92730. */
  92731. url) {
  92732. var _this = _super.call(this, name) || this;
  92733. _this.name = name;
  92734. _this.url = url;
  92735. return _this;
  92736. }
  92737. /**
  92738. * Execute the current task
  92739. * @param scene defines the scene where you want your assets to be loaded
  92740. * @param onSuccess is a callback called when the task is successfully executed
  92741. * @param onError is a callback called if an error occurs
  92742. */
  92743. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92744. var _this = this;
  92745. scene._loadFile(this.url, function (data) {
  92746. _this.text = data;
  92747. onSuccess();
  92748. }, undefined, false, false, function (request, exception) {
  92749. if (request) {
  92750. onError(request.status + " " + request.statusText, exception);
  92751. }
  92752. });
  92753. };
  92754. return TextFileAssetTask;
  92755. }(AbstractAssetTask));
  92756. BABYLON.TextFileAssetTask = TextFileAssetTask;
  92757. /**
  92758. * Define a task used by {BABYLON.AssetsManager} to load binary data
  92759. */
  92760. var BinaryFileAssetTask = /** @class */ (function (_super) {
  92761. __extends(BinaryFileAssetTask, _super);
  92762. /**
  92763. * Creates a new BinaryFileAssetTask object
  92764. * @param name defines the name of the new task
  92765. * @param url defines the location of the file to load
  92766. */
  92767. function BinaryFileAssetTask(
  92768. /**
  92769. * Defines the name of the task
  92770. */
  92771. name,
  92772. /**
  92773. * Defines the location of the file to load
  92774. */
  92775. url) {
  92776. var _this = _super.call(this, name) || this;
  92777. _this.name = name;
  92778. _this.url = url;
  92779. return _this;
  92780. }
  92781. /**
  92782. * Execute the current task
  92783. * @param scene defines the scene where you want your assets to be loaded
  92784. * @param onSuccess is a callback called when the task is successfully executed
  92785. * @param onError is a callback called if an error occurs
  92786. */
  92787. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92788. var _this = this;
  92789. scene._loadFile(this.url, function (data) {
  92790. _this.data = data;
  92791. onSuccess();
  92792. }, undefined, true, true, function (request, exception) {
  92793. if (request) {
  92794. onError(request.status + " " + request.statusText, exception);
  92795. }
  92796. });
  92797. };
  92798. return BinaryFileAssetTask;
  92799. }(AbstractAssetTask));
  92800. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  92801. /**
  92802. * Define a task used by {BABYLON.AssetsManager} to load images
  92803. */
  92804. var ImageAssetTask = /** @class */ (function (_super) {
  92805. __extends(ImageAssetTask, _super);
  92806. /**
  92807. * Creates a new ImageAssetTask
  92808. * @param name defines the name of the task
  92809. * @param url defines the location of the image to load
  92810. */
  92811. function ImageAssetTask(
  92812. /**
  92813. * Defines the name of the task
  92814. */
  92815. name,
  92816. /**
  92817. * Defines the location of the image to load
  92818. */
  92819. url) {
  92820. var _this = _super.call(this, name) || this;
  92821. _this.name = name;
  92822. _this.url = url;
  92823. return _this;
  92824. }
  92825. /**
  92826. * Execute the current task
  92827. * @param scene defines the scene where you want your assets to be loaded
  92828. * @param onSuccess is a callback called when the task is successfully executed
  92829. * @param onError is a callback called if an error occurs
  92830. */
  92831. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92832. var _this = this;
  92833. var img = new Image();
  92834. BABYLON.Tools.SetCorsBehavior(this.url, img);
  92835. img.onload = function () {
  92836. _this.image = img;
  92837. onSuccess();
  92838. };
  92839. img.onerror = function (err) {
  92840. onError("Error loading image", err);
  92841. };
  92842. img.src = this.url;
  92843. };
  92844. return ImageAssetTask;
  92845. }(AbstractAssetTask));
  92846. BABYLON.ImageAssetTask = ImageAssetTask;
  92847. /**
  92848. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  92849. */
  92850. var TextureAssetTask = /** @class */ (function (_super) {
  92851. __extends(TextureAssetTask, _super);
  92852. /**
  92853. * Creates a new TextureAssetTask object
  92854. * @param name defines the name of the task
  92855. * @param url defines the location of the file to load
  92856. * @param noMipmap defines if mipmap should not be generated (default is false)
  92857. * @param invertY defines if texture must be inverted on Y axis (default is false)
  92858. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92859. */
  92860. function TextureAssetTask(
  92861. /**
  92862. * Defines the name of the task
  92863. */
  92864. name,
  92865. /**
  92866. * Defines the location of the file to load
  92867. */
  92868. url,
  92869. /**
  92870. * Defines if mipmap should not be generated (default is false)
  92871. */
  92872. noMipmap,
  92873. /**
  92874. * Defines if texture must be inverted on Y axis (default is false)
  92875. */
  92876. invertY,
  92877. /**
  92878. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  92879. */
  92880. samplingMode) {
  92881. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  92882. var _this = _super.call(this, name) || this;
  92883. _this.name = name;
  92884. _this.url = url;
  92885. _this.noMipmap = noMipmap;
  92886. _this.invertY = invertY;
  92887. _this.samplingMode = samplingMode;
  92888. return _this;
  92889. }
  92890. /**
  92891. * Execute the current task
  92892. * @param scene defines the scene where you want your assets to be loaded
  92893. * @param onSuccess is a callback called when the task is successfully executed
  92894. * @param onError is a callback called if an error occurs
  92895. */
  92896. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92897. var onload = function () {
  92898. onSuccess();
  92899. };
  92900. var onerror = function (message, exception) {
  92901. onError(message, exception);
  92902. };
  92903. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  92904. };
  92905. return TextureAssetTask;
  92906. }(AbstractAssetTask));
  92907. BABYLON.TextureAssetTask = TextureAssetTask;
  92908. /**
  92909. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  92910. */
  92911. var CubeTextureAssetTask = /** @class */ (function (_super) {
  92912. __extends(CubeTextureAssetTask, _super);
  92913. /**
  92914. * Creates a new CubeTextureAssetTask
  92915. * @param name defines the name of the task
  92916. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  92917. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  92918. * @param noMipmap defines if mipmaps should not be generated (default is false)
  92919. * @param files defines the explicit list of files (undefined by default)
  92920. */
  92921. function CubeTextureAssetTask(
  92922. /**
  92923. * Defines the name of the task
  92924. */
  92925. name,
  92926. /**
  92927. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  92928. */
  92929. url,
  92930. /**
  92931. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  92932. */
  92933. extensions,
  92934. /**
  92935. * Defines if mipmaps should not be generated (default is false)
  92936. */
  92937. noMipmap,
  92938. /**
  92939. * Defines the explicit list of files (undefined by default)
  92940. */
  92941. files) {
  92942. var _this = _super.call(this, name) || this;
  92943. _this.name = name;
  92944. _this.url = url;
  92945. _this.extensions = extensions;
  92946. _this.noMipmap = noMipmap;
  92947. _this.files = files;
  92948. return _this;
  92949. }
  92950. /**
  92951. * Execute the current task
  92952. * @param scene defines the scene where you want your assets to be loaded
  92953. * @param onSuccess is a callback called when the task is successfully executed
  92954. * @param onError is a callback called if an error occurs
  92955. */
  92956. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92957. var onload = function () {
  92958. onSuccess();
  92959. };
  92960. var onerror = function (message, exception) {
  92961. onError(message, exception);
  92962. };
  92963. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  92964. };
  92965. return CubeTextureAssetTask;
  92966. }(AbstractAssetTask));
  92967. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  92968. /**
  92969. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  92970. */
  92971. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  92972. __extends(HDRCubeTextureAssetTask, _super);
  92973. /**
  92974. * Creates a new HDRCubeTextureAssetTask object
  92975. * @param name defines the name of the task
  92976. * @param url defines the location of the file to load
  92977. * @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.
  92978. * @param noMipmap defines if mipmaps should not be generated (default is false)
  92979. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  92980. * @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)
  92981. * @param reserved Internal use only
  92982. */
  92983. function HDRCubeTextureAssetTask(
  92984. /**
  92985. * Defines the name of the task
  92986. */
  92987. name,
  92988. /**
  92989. * Defines the location of the file to load
  92990. */
  92991. url,
  92992. /**
  92993. * Defines the desired size (the more it increases the longer the generation will be)
  92994. */
  92995. size,
  92996. /**
  92997. * Defines if mipmaps should not be generated (default is false)
  92998. */
  92999. noMipmap,
  93000. /**
  93001. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93002. */
  93003. generateHarmonics,
  93004. /**
  93005. * 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)
  93006. */
  93007. gammaSpace,
  93008. /**
  93009. * Internal Use Only
  93010. */
  93011. reserved) {
  93012. if (noMipmap === void 0) { noMipmap = false; }
  93013. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93014. if (gammaSpace === void 0) { gammaSpace = false; }
  93015. if (reserved === void 0) { reserved = false; }
  93016. var _this = _super.call(this, name) || this;
  93017. _this.name = name;
  93018. _this.url = url;
  93019. _this.size = size;
  93020. _this.noMipmap = noMipmap;
  93021. _this.generateHarmonics = generateHarmonics;
  93022. _this.gammaSpace = gammaSpace;
  93023. _this.reserved = reserved;
  93024. return _this;
  93025. }
  93026. /**
  93027. * Execute the current task
  93028. * @param scene defines the scene where you want your assets to be loaded
  93029. * @param onSuccess is a callback called when the task is successfully executed
  93030. * @param onError is a callback called if an error occurs
  93031. */
  93032. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93033. var onload = function () {
  93034. onSuccess();
  93035. };
  93036. var onerror = function (message, exception) {
  93037. onError(message, exception);
  93038. };
  93039. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  93040. };
  93041. return HDRCubeTextureAssetTask;
  93042. }(AbstractAssetTask));
  93043. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  93044. /**
  93045. * This class can be used to easily import assets into a scene
  93046. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  93047. */
  93048. var AssetsManager = /** @class */ (function () {
  93049. /**
  93050. * Creates a new AssetsManager
  93051. * @param scene defines the scene to work on
  93052. */
  93053. function AssetsManager(scene) {
  93054. this._isLoading = false;
  93055. this._tasks = new Array();
  93056. this._waitingTasksCount = 0;
  93057. this._totalTasksCount = 0;
  93058. /**
  93059. * Observable called when all tasks are processed
  93060. */
  93061. this.onTaskSuccessObservable = new BABYLON.Observable();
  93062. /**
  93063. * Observable called when a task had an error
  93064. */
  93065. this.onTaskErrorObservable = new BABYLON.Observable();
  93066. /**
  93067. * Observable called when a task is successful
  93068. */
  93069. this.onTasksDoneObservable = new BABYLON.Observable();
  93070. /**
  93071. * Observable called when a task is done (whatever the result is)
  93072. */
  93073. this.onProgressObservable = new BABYLON.Observable();
  93074. /**
  93075. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  93076. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  93077. */
  93078. this.useDefaultLoadingScreen = true;
  93079. this._scene = scene;
  93080. }
  93081. /**
  93082. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  93083. * @param taskName defines the name of the new task
  93084. * @param meshesNames defines the name of meshes to load
  93085. * @param rootUrl defines the root url to use to locate files
  93086. * @param sceneFilename defines the filename of the scene file
  93087. * @returns a new {BABYLON.MeshAssetTask} object
  93088. */
  93089. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  93090. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  93091. this._tasks.push(task);
  93092. return task;
  93093. };
  93094. /**
  93095. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  93096. * @param taskName defines the name of the new task
  93097. * @param url defines the url of the file to load
  93098. * @returns a new {BABYLON.TextFileAssetTask} object
  93099. */
  93100. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  93101. var task = new TextFileAssetTask(taskName, url);
  93102. this._tasks.push(task);
  93103. return task;
  93104. };
  93105. /**
  93106. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  93107. * @param taskName defines the name of the new task
  93108. * @param url defines the url of the file to load
  93109. * @returns a new {BABYLON.BinaryFileAssetTask} object
  93110. */
  93111. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  93112. var task = new BinaryFileAssetTask(taskName, url);
  93113. this._tasks.push(task);
  93114. return task;
  93115. };
  93116. /**
  93117. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  93118. * @param taskName defines the name of the new task
  93119. * @param url defines the url of the file to load
  93120. * @returns a new {BABYLON.ImageAssetTask} object
  93121. */
  93122. AssetsManager.prototype.addImageTask = function (taskName, url) {
  93123. var task = new ImageAssetTask(taskName, url);
  93124. this._tasks.push(task);
  93125. return task;
  93126. };
  93127. /**
  93128. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  93129. * @param taskName defines the name of the new task
  93130. * @param url defines the url of the file to load
  93131. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93132. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  93133. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  93134. * @returns a new {BABYLON.TextureAssetTask} object
  93135. */
  93136. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  93137. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93138. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  93139. this._tasks.push(task);
  93140. return task;
  93141. };
  93142. /**
  93143. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  93144. * @param taskName defines the name of the new task
  93145. * @param url defines the url of the file to load
  93146. * @param extensions defines the extension to use to load the cube map (can be null)
  93147. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93148. * @param files defines the list of files to load (can be null)
  93149. * @returns a new {BABYLON.CubeTextureAssetTask} object
  93150. */
  93151. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  93152. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  93153. this._tasks.push(task);
  93154. return task;
  93155. };
  93156. /**
  93157. *
  93158. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  93159. * @param taskName defines the name of the new task
  93160. * @param url defines the url of the file to load
  93161. * @param size defines the size you want for the cubemap (can be null)
  93162. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93163. * @param generateHarmonics defines if you want to automatically generate (true by default)
  93164. * @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)
  93165. * @param reserved Internal use only
  93166. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  93167. */
  93168. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  93169. if (noMipmap === void 0) { noMipmap = false; }
  93170. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93171. if (gammaSpace === void 0) { gammaSpace = false; }
  93172. if (reserved === void 0) { reserved = false; }
  93173. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  93174. this._tasks.push(task);
  93175. return task;
  93176. };
  93177. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  93178. var _this = this;
  93179. this._waitingTasksCount--;
  93180. try {
  93181. if (task.taskState === AssetTaskState.DONE) {
  93182. // Let's remove successfull tasks
  93183. BABYLON.Tools.SetImmediate(function () {
  93184. var index = _this._tasks.indexOf(task);
  93185. if (index > -1) {
  93186. _this._tasks.splice(index, 1);
  93187. }
  93188. });
  93189. }
  93190. if (this.onProgress) {
  93191. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  93192. }
  93193. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  93194. }
  93195. catch (e) {
  93196. BABYLON.Tools.Error("Error running progress callbacks.");
  93197. console.log(e);
  93198. }
  93199. if (this._waitingTasksCount === 0) {
  93200. try {
  93201. if (this.onFinish) {
  93202. this.onFinish(this._tasks);
  93203. }
  93204. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93205. }
  93206. catch (e) {
  93207. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  93208. console.log(e);
  93209. }
  93210. this._isLoading = false;
  93211. this._scene.getEngine().hideLoadingUI();
  93212. }
  93213. };
  93214. AssetsManager.prototype._runTask = function (task) {
  93215. var _this = this;
  93216. var done = function () {
  93217. try {
  93218. if (_this.onTaskSuccess) {
  93219. _this.onTaskSuccess(task);
  93220. }
  93221. _this.onTaskSuccessObservable.notifyObservers(task);
  93222. _this._decreaseWaitingTasksCount(task);
  93223. }
  93224. catch (e) {
  93225. error("Error executing task success callbacks", e);
  93226. }
  93227. };
  93228. var error = function (message, exception) {
  93229. task._setErrorObject(message, exception);
  93230. if (_this.onTaskError) {
  93231. _this.onTaskError(task);
  93232. }
  93233. _this.onTaskErrorObservable.notifyObservers(task);
  93234. _this._decreaseWaitingTasksCount(task);
  93235. };
  93236. task.run(this._scene, done, error);
  93237. };
  93238. /**
  93239. * Reset the {BABYLON.AssetsManager} and remove all tasks
  93240. * @return the current instance of the {BABYLON.AssetsManager}
  93241. */
  93242. AssetsManager.prototype.reset = function () {
  93243. this._isLoading = false;
  93244. this._tasks = new Array();
  93245. return this;
  93246. };
  93247. /**
  93248. * Start the loading process
  93249. * @return the current instance of the {BABYLON.AssetsManager}
  93250. */
  93251. AssetsManager.prototype.load = function () {
  93252. if (this._isLoading) {
  93253. return this;
  93254. }
  93255. this._isLoading = true;
  93256. this._waitingTasksCount = this._tasks.length;
  93257. this._totalTasksCount = this._tasks.length;
  93258. if (this._waitingTasksCount === 0) {
  93259. this._isLoading = false;
  93260. if (this.onFinish) {
  93261. this.onFinish(this._tasks);
  93262. }
  93263. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93264. return this;
  93265. }
  93266. if (this.useDefaultLoadingScreen) {
  93267. this._scene.getEngine().displayLoadingUI();
  93268. }
  93269. for (var index = 0; index < this._tasks.length; index++) {
  93270. var task = this._tasks[index];
  93271. this._runTask(task);
  93272. }
  93273. return this;
  93274. };
  93275. return AssetsManager;
  93276. }());
  93277. BABYLON.AssetsManager = AssetsManager;
  93278. })(BABYLON || (BABYLON = {}));
  93279. //# sourceMappingURL=babylon.assetsManager.js.map
  93280. var BABYLON;
  93281. (function (BABYLON) {
  93282. var serializedGeometries = [];
  93283. var serializeGeometry = function (geometry, serializationGeometries) {
  93284. if (serializedGeometries[geometry.id]) {
  93285. return;
  93286. }
  93287. if (geometry.doNotSerialize) {
  93288. return;
  93289. }
  93290. if (geometry instanceof BABYLON.BoxGeometry) {
  93291. serializationGeometries.boxes.push(geometry.serialize());
  93292. }
  93293. else if (geometry instanceof BABYLON.SphereGeometry) {
  93294. serializationGeometries.spheres.push(geometry.serialize());
  93295. }
  93296. else if (geometry instanceof BABYLON.CylinderGeometry) {
  93297. serializationGeometries.cylinders.push(geometry.serialize());
  93298. }
  93299. else if (geometry instanceof BABYLON.TorusGeometry) {
  93300. serializationGeometries.toruses.push(geometry.serialize());
  93301. }
  93302. else if (geometry instanceof BABYLON.GroundGeometry) {
  93303. serializationGeometries.grounds.push(geometry.serialize());
  93304. }
  93305. else if (geometry instanceof BABYLON.Plane) {
  93306. serializationGeometries.planes.push(geometry.serialize());
  93307. }
  93308. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  93309. serializationGeometries.torusKnots.push(geometry.serialize());
  93310. }
  93311. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  93312. throw new Error("Unknown primitive type");
  93313. }
  93314. else {
  93315. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  93316. }
  93317. serializedGeometries[geometry.id] = true;
  93318. };
  93319. var serializeMesh = function (mesh, serializationScene) {
  93320. var serializationObject = {};
  93321. // Geometry
  93322. var geometry = mesh._geometry;
  93323. if (geometry) {
  93324. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  93325. // 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
  93326. serializeGeometry(geometry, serializationScene.geometries);
  93327. }
  93328. }
  93329. // Custom
  93330. if (mesh.serialize) {
  93331. mesh.serialize(serializationObject);
  93332. }
  93333. return serializationObject;
  93334. };
  93335. var finalizeSingleMesh = function (mesh, serializationObject) {
  93336. //only works if the mesh is already loaded
  93337. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93338. //serialize material
  93339. if (mesh.material) {
  93340. if (mesh.material instanceof BABYLON.StandardMaterial) {
  93341. serializationObject.materials = serializationObject.materials || [];
  93342. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93343. serializationObject.materials.push(mesh.material.serialize());
  93344. }
  93345. }
  93346. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  93347. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  93348. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93349. serializationObject.multiMaterials.push(mesh.material.serialize());
  93350. }
  93351. }
  93352. }
  93353. //serialize geometry
  93354. var geometry = mesh._geometry;
  93355. if (geometry) {
  93356. if (!serializationObject.geometries) {
  93357. serializationObject.geometries = {};
  93358. serializationObject.geometries.boxes = [];
  93359. serializationObject.geometries.spheres = [];
  93360. serializationObject.geometries.cylinders = [];
  93361. serializationObject.geometries.toruses = [];
  93362. serializationObject.geometries.grounds = [];
  93363. serializationObject.geometries.planes = [];
  93364. serializationObject.geometries.torusKnots = [];
  93365. serializationObject.geometries.vertexData = [];
  93366. }
  93367. serializeGeometry(geometry, serializationObject.geometries);
  93368. }
  93369. // Skeletons
  93370. if (mesh.skeleton) {
  93371. serializationObject.skeletons = serializationObject.skeletons || [];
  93372. serializationObject.skeletons.push(mesh.skeleton.serialize());
  93373. }
  93374. //serialize the actual mesh
  93375. serializationObject.meshes = serializationObject.meshes || [];
  93376. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93377. }
  93378. };
  93379. var SceneSerializer = /** @class */ (function () {
  93380. function SceneSerializer() {
  93381. }
  93382. SceneSerializer.ClearCache = function () {
  93383. serializedGeometries = [];
  93384. };
  93385. SceneSerializer.Serialize = function (scene) {
  93386. var serializationObject = {};
  93387. SceneSerializer.ClearCache();
  93388. // Scene
  93389. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  93390. serializationObject.autoClear = scene.autoClear;
  93391. serializationObject.clearColor = scene.clearColor.asArray();
  93392. serializationObject.ambientColor = scene.ambientColor.asArray();
  93393. serializationObject.gravity = scene.gravity.asArray();
  93394. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  93395. serializationObject.workerCollisions = scene.workerCollisions;
  93396. // Fog
  93397. if (scene.fogMode && scene.fogMode !== 0) {
  93398. serializationObject.fogMode = scene.fogMode;
  93399. serializationObject.fogColor = scene.fogColor.asArray();
  93400. serializationObject.fogStart = scene.fogStart;
  93401. serializationObject.fogEnd = scene.fogEnd;
  93402. serializationObject.fogDensity = scene.fogDensity;
  93403. }
  93404. //Physics
  93405. if (scene.isPhysicsEnabled()) {
  93406. var physicEngine = scene.getPhysicsEngine();
  93407. if (physicEngine) {
  93408. serializationObject.physicsEnabled = true;
  93409. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  93410. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  93411. }
  93412. }
  93413. // Metadata
  93414. if (scene.metadata) {
  93415. serializationObject.metadata = scene.metadata;
  93416. }
  93417. // Morph targets
  93418. serializationObject.morphTargetManagers = [];
  93419. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  93420. var abstractMesh = _a[_i];
  93421. var manager = abstractMesh.morphTargetManager;
  93422. if (manager) {
  93423. serializationObject.morphTargetManagers.push(manager.serialize());
  93424. }
  93425. }
  93426. // Lights
  93427. serializationObject.lights = [];
  93428. var index;
  93429. var light;
  93430. for (index = 0; index < scene.lights.length; index++) {
  93431. light = scene.lights[index];
  93432. if (!light.doNotSerialize) {
  93433. serializationObject.lights.push(light.serialize());
  93434. }
  93435. }
  93436. // Cameras
  93437. serializationObject.cameras = [];
  93438. for (index = 0; index < scene.cameras.length; index++) {
  93439. var camera = scene.cameras[index];
  93440. if (!camera.doNotSerialize) {
  93441. serializationObject.cameras.push(camera.serialize());
  93442. }
  93443. }
  93444. if (scene.activeCamera) {
  93445. serializationObject.activeCameraID = scene.activeCamera.id;
  93446. }
  93447. // Animations
  93448. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  93449. // Materials
  93450. serializationObject.materials = [];
  93451. serializationObject.multiMaterials = [];
  93452. var material;
  93453. for (index = 0; index < scene.materials.length; index++) {
  93454. material = scene.materials[index];
  93455. if (!material.doNotSerialize) {
  93456. serializationObject.materials.push(material.serialize());
  93457. }
  93458. }
  93459. // MultiMaterials
  93460. serializationObject.multiMaterials = [];
  93461. for (index = 0; index < scene.multiMaterials.length; index++) {
  93462. var multiMaterial = scene.multiMaterials[index];
  93463. serializationObject.multiMaterials.push(multiMaterial.serialize());
  93464. }
  93465. // Environment texture
  93466. if (scene.environmentTexture) {
  93467. serializationObject.environmentTexture = scene.environmentTexture.name;
  93468. }
  93469. // Skeletons
  93470. serializationObject.skeletons = [];
  93471. for (index = 0; index < scene.skeletons.length; index++) {
  93472. var skeleton = scene.skeletons[index];
  93473. if (!skeleton.doNotSerialize) {
  93474. serializationObject.skeletons.push(skeleton.serialize());
  93475. }
  93476. }
  93477. // Transform nodes
  93478. serializationObject.transformNodes = [];
  93479. for (index = 0; index < scene.transformNodes.length; index++) {
  93480. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  93481. }
  93482. // Geometries
  93483. serializationObject.geometries = {};
  93484. serializationObject.geometries.boxes = [];
  93485. serializationObject.geometries.spheres = [];
  93486. serializationObject.geometries.cylinders = [];
  93487. serializationObject.geometries.toruses = [];
  93488. serializationObject.geometries.grounds = [];
  93489. serializationObject.geometries.planes = [];
  93490. serializationObject.geometries.torusKnots = [];
  93491. serializationObject.geometries.vertexData = [];
  93492. serializedGeometries = [];
  93493. var geometries = scene.getGeometries();
  93494. for (index = 0; index < geometries.length; index++) {
  93495. var geometry = geometries[index];
  93496. if (geometry.isReady()) {
  93497. serializeGeometry(geometry, serializationObject.geometries);
  93498. }
  93499. }
  93500. // Meshes
  93501. serializationObject.meshes = [];
  93502. for (index = 0; index < scene.meshes.length; index++) {
  93503. var abstractMesh = scene.meshes[index];
  93504. if (abstractMesh instanceof BABYLON.Mesh) {
  93505. var mesh = abstractMesh;
  93506. if (!mesh.doNotSerialize) {
  93507. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93508. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93509. }
  93510. }
  93511. }
  93512. }
  93513. // Particles Systems
  93514. serializationObject.particleSystems = [];
  93515. for (index = 0; index < scene.particleSystems.length; index++) {
  93516. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  93517. }
  93518. // Lens flares
  93519. serializationObject.lensFlareSystems = [];
  93520. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  93521. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  93522. }
  93523. // Shadows
  93524. serializationObject.shadowGenerators = [];
  93525. for (index = 0; index < scene.lights.length; index++) {
  93526. light = scene.lights[index];
  93527. var shadowGenerator = light.getShadowGenerator();
  93528. if (shadowGenerator) {
  93529. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  93530. }
  93531. }
  93532. // Action Manager
  93533. if (scene.actionManager) {
  93534. serializationObject.actions = scene.actionManager.serialize("scene");
  93535. }
  93536. // Audio
  93537. serializationObject.sounds = [];
  93538. for (index = 0; index < scene.soundTracks.length; index++) {
  93539. var soundtrack = scene.soundTracks[index];
  93540. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  93541. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  93542. }
  93543. }
  93544. // Effect layers
  93545. serializationObject.effectLayers = [];
  93546. for (index = 0; index < scene.effectLayers.length; index++) {
  93547. var layer = scene.effectLayers[index];
  93548. if (layer.serialize) {
  93549. serializationObject.effectLayers.push(layer.serialize());
  93550. }
  93551. }
  93552. return serializationObject;
  93553. };
  93554. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  93555. if (withParents === void 0) { withParents = false; }
  93556. if (withChildren === void 0) { withChildren = false; }
  93557. var serializationObject = {};
  93558. SceneSerializer.ClearCache();
  93559. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  93560. if (withParents || withChildren) {
  93561. //deliberate for loop! not for each, appended should be processed as well.
  93562. for (var i = 0; i < toSerialize.length; ++i) {
  93563. if (withChildren) {
  93564. toSerialize[i].getDescendants().forEach(function (node) {
  93565. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  93566. toSerialize.push(node);
  93567. }
  93568. });
  93569. }
  93570. //make sure the array doesn't contain the object already
  93571. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  93572. toSerialize.push(toSerialize[i].parent);
  93573. }
  93574. }
  93575. }
  93576. toSerialize.forEach(function (mesh) {
  93577. finalizeSingleMesh(mesh, serializationObject);
  93578. });
  93579. return serializationObject;
  93580. };
  93581. return SceneSerializer;
  93582. }());
  93583. BABYLON.SceneSerializer = SceneSerializer;
  93584. })(BABYLON || (BABYLON = {}));
  93585. //# sourceMappingURL=babylon.sceneSerializer.js.map
  93586. var BABYLON;
  93587. (function (BABYLON) {
  93588. var ReflectionProbe = /** @class */ (function () {
  93589. function ReflectionProbe(name, size, scene, generateMipMaps) {
  93590. if (generateMipMaps === void 0) { generateMipMaps = true; }
  93591. var _this = this;
  93592. this.name = name;
  93593. this._viewMatrix = BABYLON.Matrix.Identity();
  93594. this._target = BABYLON.Vector3.Zero();
  93595. this._add = BABYLON.Vector3.Zero();
  93596. this._invertYAxis = false;
  93597. this.position = BABYLON.Vector3.Zero();
  93598. this._scene = scene;
  93599. this._scene.reflectionProbes.push(this);
  93600. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  93601. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  93602. switch (faceIndex) {
  93603. case 0:
  93604. _this._add.copyFromFloats(1, 0, 0);
  93605. break;
  93606. case 1:
  93607. _this._add.copyFromFloats(-1, 0, 0);
  93608. break;
  93609. case 2:
  93610. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  93611. break;
  93612. case 3:
  93613. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  93614. break;
  93615. case 4:
  93616. _this._add.copyFromFloats(0, 0, 1);
  93617. break;
  93618. case 5:
  93619. _this._add.copyFromFloats(0, 0, -1);
  93620. break;
  93621. }
  93622. if (_this._attachedMesh) {
  93623. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  93624. }
  93625. _this.position.addToRef(_this._add, _this._target);
  93626. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  93627. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  93628. scene._forcedViewPosition = _this.position;
  93629. });
  93630. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  93631. scene._forcedViewPosition = null;
  93632. scene.updateTransformMatrix(true);
  93633. });
  93634. if (scene.activeCamera) {
  93635. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  93636. }
  93637. }
  93638. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  93639. get: function () {
  93640. return this._renderTargetTexture.samples;
  93641. },
  93642. set: function (value) {
  93643. this._renderTargetTexture.samples = value;
  93644. },
  93645. enumerable: true,
  93646. configurable: true
  93647. });
  93648. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  93649. get: function () {
  93650. return this._renderTargetTexture.refreshRate;
  93651. },
  93652. set: function (value) {
  93653. this._renderTargetTexture.refreshRate = value;
  93654. },
  93655. enumerable: true,
  93656. configurable: true
  93657. });
  93658. ReflectionProbe.prototype.getScene = function () {
  93659. return this._scene;
  93660. };
  93661. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  93662. get: function () {
  93663. return this._renderTargetTexture;
  93664. },
  93665. enumerable: true,
  93666. configurable: true
  93667. });
  93668. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  93669. get: function () {
  93670. return this._renderTargetTexture.renderList;
  93671. },
  93672. enumerable: true,
  93673. configurable: true
  93674. });
  93675. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  93676. this._attachedMesh = mesh;
  93677. };
  93678. /**
  93679. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  93680. *
  93681. * @param renderingGroupId The rendering group id corresponding to its index
  93682. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  93683. */
  93684. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  93685. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  93686. };
  93687. ReflectionProbe.prototype.dispose = function () {
  93688. var index = this._scene.reflectionProbes.indexOf(this);
  93689. if (index !== -1) {
  93690. // Remove from the scene if found
  93691. this._scene.reflectionProbes.splice(index, 1);
  93692. }
  93693. if (this._renderTargetTexture) {
  93694. this._renderTargetTexture.dispose();
  93695. this._renderTargetTexture = null;
  93696. }
  93697. };
  93698. return ReflectionProbe;
  93699. }());
  93700. BABYLON.ReflectionProbe = ReflectionProbe;
  93701. })(BABYLON || (BABYLON = {}));
  93702. //# sourceMappingURL=babylon.reflectionProbe.js.map
  93703. var BABYLON;
  93704. (function (BABYLON) {
  93705. var Layer = /** @class */ (function () {
  93706. function Layer(name, imgUrl, scene, isBackground, color) {
  93707. this.name = name;
  93708. this.scale = new BABYLON.Vector2(1, 1);
  93709. this.offset = new BABYLON.Vector2(0, 0);
  93710. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  93711. this.layerMask = 0x0FFFFFFF;
  93712. this._vertexBuffers = {};
  93713. // Events
  93714. /**
  93715. * An event triggered when the layer is disposed.
  93716. */
  93717. this.onDisposeObservable = new BABYLON.Observable();
  93718. /**
  93719. * An event triggered before rendering the scene
  93720. */
  93721. this.onBeforeRenderObservable = new BABYLON.Observable();
  93722. /**
  93723. * An event triggered after rendering the scene
  93724. */
  93725. this.onAfterRenderObservable = new BABYLON.Observable();
  93726. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  93727. this.isBackground = isBackground === undefined ? true : isBackground;
  93728. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  93729. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  93730. this._scene.layers.push(this);
  93731. var engine = this._scene.getEngine();
  93732. // VBO
  93733. var vertices = [];
  93734. vertices.push(1, 1);
  93735. vertices.push(-1, 1);
  93736. vertices.push(-1, -1);
  93737. vertices.push(1, -1);
  93738. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93739. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93740. this._createIndexBuffer();
  93741. // Effects
  93742. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  93743. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  93744. }
  93745. Object.defineProperty(Layer.prototype, "onDispose", {
  93746. set: function (callback) {
  93747. if (this._onDisposeObserver) {
  93748. this.onDisposeObservable.remove(this._onDisposeObserver);
  93749. }
  93750. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  93751. },
  93752. enumerable: true,
  93753. configurable: true
  93754. });
  93755. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  93756. set: function (callback) {
  93757. if (this._onBeforeRenderObserver) {
  93758. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  93759. }
  93760. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  93761. },
  93762. enumerable: true,
  93763. configurable: true
  93764. });
  93765. Object.defineProperty(Layer.prototype, "onAfterRender", {
  93766. set: function (callback) {
  93767. if (this._onAfterRenderObserver) {
  93768. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  93769. }
  93770. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  93771. },
  93772. enumerable: true,
  93773. configurable: true
  93774. });
  93775. Layer.prototype._createIndexBuffer = function () {
  93776. var engine = this._scene.getEngine();
  93777. // Indices
  93778. var indices = [];
  93779. indices.push(0);
  93780. indices.push(1);
  93781. indices.push(2);
  93782. indices.push(0);
  93783. indices.push(2);
  93784. indices.push(3);
  93785. this._indexBuffer = engine.createIndexBuffer(indices);
  93786. };
  93787. Layer.prototype._rebuild = function () {
  93788. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93789. if (vb) {
  93790. vb._rebuild();
  93791. }
  93792. this._createIndexBuffer();
  93793. };
  93794. Layer.prototype.render = function () {
  93795. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  93796. // Check
  93797. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  93798. return;
  93799. var engine = this._scene.getEngine();
  93800. this.onBeforeRenderObservable.notifyObservers(this);
  93801. // Render
  93802. engine.enableEffect(currentEffect);
  93803. engine.setState(false);
  93804. // Texture
  93805. currentEffect.setTexture("textureSampler", this.texture);
  93806. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  93807. // Color
  93808. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  93809. // Scale / offset
  93810. currentEffect.setVector2("offset", this.offset);
  93811. currentEffect.setVector2("scale", this.scale);
  93812. // VBOs
  93813. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  93814. // Draw order
  93815. if (!this.alphaTest) {
  93816. engine.setAlphaMode(this.alphaBlendingMode);
  93817. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93818. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  93819. }
  93820. else {
  93821. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  93822. }
  93823. this.onAfterRenderObservable.notifyObservers(this);
  93824. };
  93825. Layer.prototype.dispose = function () {
  93826. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93827. if (vertexBuffer) {
  93828. vertexBuffer.dispose();
  93829. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  93830. }
  93831. if (this._indexBuffer) {
  93832. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  93833. this._indexBuffer = null;
  93834. }
  93835. if (this.texture) {
  93836. this.texture.dispose();
  93837. this.texture = null;
  93838. }
  93839. // Remove from scene
  93840. var index = this._scene.layers.indexOf(this);
  93841. this._scene.layers.splice(index, 1);
  93842. // Callback
  93843. this.onDisposeObservable.notifyObservers(this);
  93844. this.onDisposeObservable.clear();
  93845. this.onAfterRenderObservable.clear();
  93846. this.onBeforeRenderObservable.clear();
  93847. };
  93848. return Layer;
  93849. }());
  93850. BABYLON.Layer = Layer;
  93851. })(BABYLON || (BABYLON = {}));
  93852. //# sourceMappingURL=babylon.layer.js.map
  93853. var BABYLON;
  93854. (function (BABYLON) {
  93855. var TextureTools = /** @class */ (function () {
  93856. function TextureTools() {
  93857. }
  93858. /**
  93859. * Uses the GPU to create a copy texture rescaled at a given size
  93860. * @param texture Texture to copy from
  93861. * @param width Desired width
  93862. * @param height Desired height
  93863. * @return Generated texture
  93864. */
  93865. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  93866. if (useBilinearMode === void 0) { useBilinearMode = true; }
  93867. var scene = texture.getScene();
  93868. var engine = scene.getEngine();
  93869. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  93870. rtt.wrapU = texture.wrapU;
  93871. rtt.wrapV = texture.wrapV;
  93872. rtt.uOffset = texture.uOffset;
  93873. rtt.vOffset = texture.vOffset;
  93874. rtt.uScale = texture.uScale;
  93875. rtt.vScale = texture.vScale;
  93876. rtt.uAng = texture.uAng;
  93877. rtt.vAng = texture.vAng;
  93878. rtt.wAng = texture.wAng;
  93879. rtt.coordinatesIndex = texture.coordinatesIndex;
  93880. rtt.level = texture.level;
  93881. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  93882. rtt._texture.isReady = false;
  93883. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93884. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93885. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  93886. passPostProcess.getEffect().executeWhenCompiled(function () {
  93887. passPostProcess.onApply = function (effect) {
  93888. effect.setTexture("textureSampler", texture);
  93889. };
  93890. var internalTexture = rtt.getInternalTexture();
  93891. if (internalTexture) {
  93892. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  93893. engine.unBindFramebuffer(internalTexture);
  93894. rtt.disposeFramebufferObjects();
  93895. passPostProcess.dispose();
  93896. internalTexture.isReady = true;
  93897. }
  93898. });
  93899. return rtt;
  93900. };
  93901. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  93902. if (!scene._environmentBRDFTexture) {
  93903. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  93904. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93905. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  93906. scene._environmentBRDFTexture = texture;
  93907. }
  93908. return scene._environmentBRDFTexture;
  93909. };
  93910. 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=";
  93911. return TextureTools;
  93912. }());
  93913. BABYLON.TextureTools = TextureTools;
  93914. })(BABYLON || (BABYLON = {}));
  93915. //# sourceMappingURL=babylon.textureTools.js.map
  93916. var BABYLON;
  93917. (function (BABYLON) {
  93918. var FramingBehavior = /** @class */ (function () {
  93919. function FramingBehavior() {
  93920. this._mode = FramingBehavior.FitFrustumSidesMode;
  93921. this._radiusScale = 1.0;
  93922. this._positionScale = 0.5;
  93923. this._defaultElevation = 0.3;
  93924. this._elevationReturnTime = 1500;
  93925. this._elevationReturnWaitTime = 1000;
  93926. this._zoomStopsAnimation = false;
  93927. this._framingTime = 1500;
  93928. this._isPointerDown = false;
  93929. this._lastInteractionTime = -Infinity;
  93930. // Framing control
  93931. this._animatables = new Array();
  93932. this._betaIsAnimating = false;
  93933. }
  93934. Object.defineProperty(FramingBehavior.prototype, "name", {
  93935. get: function () {
  93936. return "Framing";
  93937. },
  93938. enumerable: true,
  93939. configurable: true
  93940. });
  93941. Object.defineProperty(FramingBehavior.prototype, "mode", {
  93942. /**
  93943. * Gets current mode used by the behavior.
  93944. */
  93945. get: function () {
  93946. return this._mode;
  93947. },
  93948. /**
  93949. * Sets the current mode used by the behavior
  93950. */
  93951. set: function (mode) {
  93952. this._mode = mode;
  93953. },
  93954. enumerable: true,
  93955. configurable: true
  93956. });
  93957. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  93958. /**
  93959. * Gets the scale applied to the radius
  93960. */
  93961. get: function () {
  93962. return this._radiusScale;
  93963. },
  93964. /**
  93965. * Sets the scale applied to the radius (1 by default)
  93966. */
  93967. set: function (radius) {
  93968. this._radiusScale = radius;
  93969. },
  93970. enumerable: true,
  93971. configurable: true
  93972. });
  93973. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  93974. /**
  93975. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  93976. */
  93977. get: function () {
  93978. return this._positionScale;
  93979. },
  93980. /**
  93981. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  93982. */
  93983. set: function (scale) {
  93984. this._positionScale = scale;
  93985. },
  93986. enumerable: true,
  93987. configurable: true
  93988. });
  93989. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  93990. /**
  93991. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  93992. * behaviour is triggered, in radians.
  93993. */
  93994. get: function () {
  93995. return this._defaultElevation;
  93996. },
  93997. /**
  93998. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  93999. * behaviour is triggered, in radians.
  94000. */
  94001. set: function (elevation) {
  94002. this._defaultElevation = elevation;
  94003. },
  94004. enumerable: true,
  94005. configurable: true
  94006. });
  94007. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  94008. /**
  94009. * Gets the time (in milliseconds) taken to return to the default beta position.
  94010. * Negative value indicates camera should not return to default.
  94011. */
  94012. get: function () {
  94013. return this._elevationReturnTime;
  94014. },
  94015. /**
  94016. * Sets the time (in milliseconds) taken to return to the default beta position.
  94017. * Negative value indicates camera should not return to default.
  94018. */
  94019. set: function (speed) {
  94020. this._elevationReturnTime = speed;
  94021. },
  94022. enumerable: true,
  94023. configurable: true
  94024. });
  94025. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  94026. /**
  94027. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94028. */
  94029. get: function () {
  94030. return this._elevationReturnWaitTime;
  94031. },
  94032. /**
  94033. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94034. */
  94035. set: function (time) {
  94036. this._elevationReturnWaitTime = time;
  94037. },
  94038. enumerable: true,
  94039. configurable: true
  94040. });
  94041. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  94042. /**
  94043. * Gets the flag that indicates if user zooming should stop animation.
  94044. */
  94045. get: function () {
  94046. return this._zoomStopsAnimation;
  94047. },
  94048. /**
  94049. * Sets the flag that indicates if user zooming should stop animation.
  94050. */
  94051. set: function (flag) {
  94052. this._zoomStopsAnimation = flag;
  94053. },
  94054. enumerable: true,
  94055. configurable: true
  94056. });
  94057. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  94058. /**
  94059. * Gets the transition time when framing the mesh, in milliseconds
  94060. */
  94061. get: function () {
  94062. return this._framingTime;
  94063. },
  94064. /**
  94065. * Sets the transition time when framing the mesh, in milliseconds
  94066. */
  94067. set: function (time) {
  94068. this._framingTime = time;
  94069. },
  94070. enumerable: true,
  94071. configurable: true
  94072. });
  94073. FramingBehavior.prototype.init = function () {
  94074. // Do notihng
  94075. };
  94076. FramingBehavior.prototype.attach = function (camera) {
  94077. var _this = this;
  94078. this._attachedCamera = camera;
  94079. var scene = this._attachedCamera.getScene();
  94080. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  94081. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94082. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94083. _this._isPointerDown = true;
  94084. return;
  94085. }
  94086. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94087. _this._isPointerDown = false;
  94088. }
  94089. });
  94090. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94091. if (mesh) {
  94092. _this.zoomOnMesh(mesh);
  94093. }
  94094. });
  94095. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94096. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94097. _this._applyUserInteraction();
  94098. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  94099. // back to the default position after a given timeout
  94100. _this._maintainCameraAboveGround();
  94101. });
  94102. };
  94103. FramingBehavior.prototype.detach = function () {
  94104. if (!this._attachedCamera) {
  94105. return;
  94106. }
  94107. var scene = this._attachedCamera.getScene();
  94108. if (this._onPrePointerObservableObserver) {
  94109. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94110. }
  94111. if (this._onAfterCheckInputsObserver) {
  94112. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94113. }
  94114. if (this._onMeshTargetChangedObserver) {
  94115. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94116. }
  94117. this._attachedCamera = null;
  94118. };
  94119. /**
  94120. * Targets the given mesh and updates zoom level accordingly.
  94121. * @param mesh The mesh to target.
  94122. * @param radius Optional. If a cached radius position already exists, overrides default.
  94123. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94124. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94125. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94126. */
  94127. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94128. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94129. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94130. mesh.computeWorldMatrix(true);
  94131. var boundingBox = mesh.getBoundingInfo().boundingBox;
  94132. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  94133. };
  94134. /**
  94135. * Targets the given mesh with its children and updates zoom level accordingly.
  94136. * @param mesh The mesh to target.
  94137. * @param radius Optional. If a cached radius position already exists, overrides default.
  94138. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94139. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94140. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94141. */
  94142. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94143. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94144. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94145. mesh.computeWorldMatrix(true);
  94146. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  94147. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  94148. };
  94149. /**
  94150. * Targets the given meshes with their children and updates zoom level accordingly.
  94151. * @param meshes The mesh to target.
  94152. * @param radius Optional. If a cached radius position already exists, overrides default.
  94153. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94154. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94155. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94156. */
  94157. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  94158. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94159. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94160. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  94161. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  94162. for (var i = 0; i < meshes.length; i++) {
  94163. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  94164. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  94165. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  94166. }
  94167. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  94168. };
  94169. /**
  94170. * Targets the given mesh and updates zoom level accordingly.
  94171. * @param mesh The mesh to target.
  94172. * @param radius Optional. If a cached radius position already exists, overrides default.
  94173. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94174. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94175. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94176. */
  94177. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  94178. var _this = this;
  94179. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94180. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94181. var zoomTarget;
  94182. if (!this._attachedCamera) {
  94183. return;
  94184. }
  94185. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  94186. var bottom = minimumWorld.y;
  94187. var top = maximumWorld.y;
  94188. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  94189. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  94190. if (focusOnOriginXZ) {
  94191. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  94192. }
  94193. else {
  94194. var centerWorld = minimumWorld.add(radiusWorld);
  94195. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  94196. }
  94197. if (!this._vectorTransition) {
  94198. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  94199. }
  94200. this._betaIsAnimating = true;
  94201. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  94202. if (animatable) {
  94203. this._animatables.push(animatable);
  94204. }
  94205. // sets the radius and lower radius bounds
  94206. // Small delta ensures camera is not always at lower zoom limit.
  94207. var radius = 0;
  94208. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  94209. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94210. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  94211. radius = position;
  94212. }
  94213. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94214. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94215. if (this._attachedCamera.lowerRadiusLimit === null) {
  94216. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  94217. }
  94218. }
  94219. // Set sensibilities
  94220. var extend = maximumWorld.subtract(minimumWorld).length();
  94221. this._attachedCamera.panningSensibility = 5000 / extend;
  94222. this._attachedCamera.wheelPrecision = 100 / radius;
  94223. // transition to new radius
  94224. if (!this._radiusTransition) {
  94225. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94226. }
  94227. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  94228. _this.stopAllAnimations();
  94229. if (onAnimationEnd) {
  94230. onAnimationEnd();
  94231. }
  94232. if (_this._attachedCamera) {
  94233. _this._attachedCamera.storeState();
  94234. }
  94235. });
  94236. if (animatable) {
  94237. this._animatables.push(animatable);
  94238. }
  94239. };
  94240. /**
  94241. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  94242. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  94243. * frustum width.
  94244. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  94245. * to fully enclose the mesh in the viewing frustum.
  94246. */
  94247. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  94248. var size = maximumWorld.subtract(minimumWorld);
  94249. var boxVectorGlobalDiagonal = size.length();
  94250. var frustumSlope = this._getFrustumSlope();
  94251. // Formula for setting distance
  94252. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  94253. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  94254. // Horizon distance
  94255. var radius = radiusWithoutFraming * this._radiusScale;
  94256. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  94257. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  94258. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  94259. var camera = this._attachedCamera;
  94260. if (!camera) {
  94261. return 0;
  94262. }
  94263. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94264. // Don't exceed the requested limit
  94265. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  94266. }
  94267. // Don't exceed the upper radius limit
  94268. if (camera.upperRadiusLimit) {
  94269. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  94270. }
  94271. return distance;
  94272. };
  94273. /**
  94274. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  94275. * is automatically returned to its default position (expected to be above ground plane).
  94276. */
  94277. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  94278. var _this = this;
  94279. if (this._elevationReturnTime < 0) {
  94280. return;
  94281. }
  94282. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  94283. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  94284. var limitBeta = Math.PI * 0.5;
  94285. // Bring the camera back up if below the ground plane
  94286. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  94287. this._betaIsAnimating = true;
  94288. //Transition to new position
  94289. this.stopAllAnimations();
  94290. if (!this._betaTransition) {
  94291. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94292. }
  94293. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  94294. _this._clearAnimationLocks();
  94295. _this.stopAllAnimations();
  94296. });
  94297. if (animatabe) {
  94298. this._animatables.push(animatabe);
  94299. }
  94300. }
  94301. };
  94302. /**
  94303. * Returns the frustum slope based on the canvas ratio and camera FOV
  94304. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  94305. */
  94306. FramingBehavior.prototype._getFrustumSlope = function () {
  94307. // Calculate the viewport ratio
  94308. // Aspect Ratio is Height/Width.
  94309. var camera = this._attachedCamera;
  94310. if (!camera) {
  94311. return BABYLON.Vector2.Zero();
  94312. }
  94313. var engine = camera.getScene().getEngine();
  94314. var aspectRatio = engine.getAspectRatio(camera);
  94315. // Camera FOV is the vertical field of view (top-bottom) in radians.
  94316. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  94317. var frustumSlopeY = Math.tan(camera.fov / 2);
  94318. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  94319. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  94320. // along the forward vector.
  94321. var frustumSlopeX = frustumSlopeY * aspectRatio;
  94322. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  94323. };
  94324. /**
  94325. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  94326. */
  94327. FramingBehavior.prototype._clearAnimationLocks = function () {
  94328. this._betaIsAnimating = false;
  94329. };
  94330. /**
  94331. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94332. */
  94333. FramingBehavior.prototype._applyUserInteraction = function () {
  94334. if (this.isUserIsMoving) {
  94335. this._lastInteractionTime = BABYLON.Tools.Now;
  94336. this.stopAllAnimations();
  94337. this._clearAnimationLocks();
  94338. }
  94339. };
  94340. /**
  94341. * Stops and removes all animations that have been applied to the camera
  94342. */
  94343. FramingBehavior.prototype.stopAllAnimations = function () {
  94344. if (this._attachedCamera) {
  94345. this._attachedCamera.animations = [];
  94346. }
  94347. while (this._animatables.length) {
  94348. if (this._animatables[0]) {
  94349. this._animatables[0].onAnimationEnd = null;
  94350. this._animatables[0].stop();
  94351. }
  94352. this._animatables.shift();
  94353. }
  94354. };
  94355. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  94356. /**
  94357. * Gets a value indicating if the user is moving the camera
  94358. */
  94359. get: function () {
  94360. if (!this._attachedCamera) {
  94361. return false;
  94362. }
  94363. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94364. this._attachedCamera.inertialBetaOffset !== 0 ||
  94365. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94366. this._attachedCamera.inertialPanningX !== 0 ||
  94367. this._attachedCamera.inertialPanningY !== 0 ||
  94368. this._isPointerDown;
  94369. },
  94370. enumerable: true,
  94371. configurable: true
  94372. });
  94373. /**
  94374. * The easing function used by animations
  94375. */
  94376. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  94377. /**
  94378. * The easing mode used by animations
  94379. */
  94380. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  94381. // Statics
  94382. /**
  94383. * The camera can move all the way towards the mesh.
  94384. */
  94385. FramingBehavior.IgnoreBoundsSizeMode = 0;
  94386. /**
  94387. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  94388. */
  94389. FramingBehavior.FitFrustumSidesMode = 1;
  94390. return FramingBehavior;
  94391. }());
  94392. BABYLON.FramingBehavior = FramingBehavior;
  94393. })(BABYLON || (BABYLON = {}));
  94394. //# sourceMappingURL=babylon.framingBehavior.js.map
  94395. var BABYLON;
  94396. (function (BABYLON) {
  94397. /**
  94398. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  94399. */
  94400. var BouncingBehavior = /** @class */ (function () {
  94401. function BouncingBehavior() {
  94402. /**
  94403. * The duration of the animation, in milliseconds
  94404. */
  94405. this.transitionDuration = 450;
  94406. /**
  94407. * Length of the distance animated by the transition when lower radius is reached
  94408. */
  94409. this.lowerRadiusTransitionRange = 2;
  94410. /**
  94411. * Length of the distance animated by the transition when upper radius is reached
  94412. */
  94413. this.upperRadiusTransitionRange = -2;
  94414. this._autoTransitionRange = false;
  94415. // Animations
  94416. this._radiusIsAnimating = false;
  94417. this._radiusBounceTransition = null;
  94418. this._animatables = new Array();
  94419. }
  94420. Object.defineProperty(BouncingBehavior.prototype, "name", {
  94421. get: function () {
  94422. return "Bouncing";
  94423. },
  94424. enumerable: true,
  94425. configurable: true
  94426. });
  94427. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  94428. /**
  94429. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94430. */
  94431. get: function () {
  94432. return this._autoTransitionRange;
  94433. },
  94434. /**
  94435. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94436. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  94437. */
  94438. set: function (value) {
  94439. var _this = this;
  94440. if (this._autoTransitionRange === value) {
  94441. return;
  94442. }
  94443. this._autoTransitionRange = value;
  94444. var camera = this._attachedCamera;
  94445. if (!camera) {
  94446. return;
  94447. }
  94448. if (value) {
  94449. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94450. if (!mesh) {
  94451. return;
  94452. }
  94453. mesh.computeWorldMatrix(true);
  94454. var diagonal = mesh.getBoundingInfo().diagonalLength;
  94455. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  94456. _this.upperRadiusTransitionRange = diagonal * 0.05;
  94457. });
  94458. }
  94459. else if (this._onMeshTargetChangedObserver) {
  94460. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94461. }
  94462. },
  94463. enumerable: true,
  94464. configurable: true
  94465. });
  94466. BouncingBehavior.prototype.init = function () {
  94467. // Do notihng
  94468. };
  94469. BouncingBehavior.prototype.attach = function (camera) {
  94470. var _this = this;
  94471. this._attachedCamera = camera;
  94472. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94473. if (!_this._attachedCamera) {
  94474. return;
  94475. }
  94476. // Add the bounce animation to the lower radius limit
  94477. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  94478. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  94479. }
  94480. // Add the bounce animation to the upper radius limit
  94481. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  94482. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  94483. }
  94484. });
  94485. };
  94486. BouncingBehavior.prototype.detach = function () {
  94487. if (!this._attachedCamera) {
  94488. return;
  94489. }
  94490. if (this._onAfterCheckInputsObserver) {
  94491. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94492. }
  94493. if (this._onMeshTargetChangedObserver) {
  94494. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94495. }
  94496. this._attachedCamera = null;
  94497. };
  94498. /**
  94499. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  94500. * @param radiusLimit The limit to check against.
  94501. * @return Bool to indicate if at limit.
  94502. */
  94503. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  94504. if (!this._attachedCamera) {
  94505. return false;
  94506. }
  94507. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  94508. return true;
  94509. }
  94510. return false;
  94511. };
  94512. /**
  94513. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  94514. * @param radiusDelta The delta by which to animate to. Can be negative.
  94515. */
  94516. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  94517. var _this = this;
  94518. if (!this._attachedCamera) {
  94519. return;
  94520. }
  94521. if (!this._radiusBounceTransition) {
  94522. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  94523. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  94524. }
  94525. // Prevent zoom until bounce has completed
  94526. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  94527. this._attachedCamera.wheelPrecision = Infinity;
  94528. this._attachedCamera.inertialRadiusOffset = 0;
  94529. // Animate to the radius limit
  94530. this.stopAllAnimations();
  94531. this._radiusIsAnimating = true;
  94532. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  94533. if (animatable) {
  94534. this._animatables.push(animatable);
  94535. }
  94536. };
  94537. /**
  94538. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  94539. */
  94540. BouncingBehavior.prototype._clearAnimationLocks = function () {
  94541. this._radiusIsAnimating = false;
  94542. if (this._attachedCamera) {
  94543. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  94544. }
  94545. };
  94546. /**
  94547. * Stops and removes all animations that have been applied to the camera
  94548. */
  94549. BouncingBehavior.prototype.stopAllAnimations = function () {
  94550. if (this._attachedCamera) {
  94551. this._attachedCamera.animations = [];
  94552. }
  94553. while (this._animatables.length) {
  94554. this._animatables[0].onAnimationEnd = null;
  94555. this._animatables[0].stop();
  94556. this._animatables.shift();
  94557. }
  94558. };
  94559. /**
  94560. * The easing function used by animations
  94561. */
  94562. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  94563. /**
  94564. * The easing mode used by animations
  94565. */
  94566. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  94567. return BouncingBehavior;
  94568. }());
  94569. BABYLON.BouncingBehavior = BouncingBehavior;
  94570. })(BABYLON || (BABYLON = {}));
  94571. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  94572. var BABYLON;
  94573. (function (BABYLON) {
  94574. var AutoRotationBehavior = /** @class */ (function () {
  94575. function AutoRotationBehavior() {
  94576. this._zoomStopsAnimation = false;
  94577. this._idleRotationSpeed = 0.05;
  94578. this._idleRotationWaitTime = 2000;
  94579. this._idleRotationSpinupTime = 2000;
  94580. this._isPointerDown = false;
  94581. this._lastFrameTime = null;
  94582. this._lastInteractionTime = -Infinity;
  94583. this._cameraRotationSpeed = 0;
  94584. this._lastFrameRadius = 0;
  94585. }
  94586. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  94587. get: function () {
  94588. return "AutoRotation";
  94589. },
  94590. enumerable: true,
  94591. configurable: true
  94592. });
  94593. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  94594. /**
  94595. * Gets the flag that indicates if user zooming should stop animation.
  94596. */
  94597. get: function () {
  94598. return this._zoomStopsAnimation;
  94599. },
  94600. /**
  94601. * Sets the flag that indicates if user zooming should stop animation.
  94602. */
  94603. set: function (flag) {
  94604. this._zoomStopsAnimation = flag;
  94605. },
  94606. enumerable: true,
  94607. configurable: true
  94608. });
  94609. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  94610. /**
  94611. * Gets the default speed at which the camera rotates around the model.
  94612. */
  94613. get: function () {
  94614. return this._idleRotationSpeed;
  94615. },
  94616. /**
  94617. * Sets the default speed at which the camera rotates around the model.
  94618. */
  94619. set: function (speed) {
  94620. this._idleRotationSpeed = speed;
  94621. },
  94622. enumerable: true,
  94623. configurable: true
  94624. });
  94625. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  94626. /**
  94627. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  94628. */
  94629. get: function () {
  94630. return this._idleRotationWaitTime;
  94631. },
  94632. /**
  94633. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  94634. */
  94635. set: function (time) {
  94636. this._idleRotationWaitTime = time;
  94637. },
  94638. enumerable: true,
  94639. configurable: true
  94640. });
  94641. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  94642. /**
  94643. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94644. */
  94645. get: function () {
  94646. return this._idleRotationSpinupTime;
  94647. },
  94648. /**
  94649. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94650. */
  94651. set: function (time) {
  94652. this._idleRotationSpinupTime = time;
  94653. },
  94654. enumerable: true,
  94655. configurable: true
  94656. });
  94657. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  94658. /**
  94659. * Gets a value indicating if the camera is currently rotating because of this behavior
  94660. */
  94661. get: function () {
  94662. return Math.abs(this._cameraRotationSpeed) > 0;
  94663. },
  94664. enumerable: true,
  94665. configurable: true
  94666. });
  94667. AutoRotationBehavior.prototype.init = function () {
  94668. // Do notihng
  94669. };
  94670. AutoRotationBehavior.prototype.attach = function (camera) {
  94671. var _this = this;
  94672. this._attachedCamera = camera;
  94673. var scene = this._attachedCamera.getScene();
  94674. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94675. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94676. _this._isPointerDown = true;
  94677. return;
  94678. }
  94679. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94680. _this._isPointerDown = false;
  94681. }
  94682. });
  94683. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94684. var now = BABYLON.Tools.Now;
  94685. var dt = 0;
  94686. if (_this._lastFrameTime != null) {
  94687. dt = now - _this._lastFrameTime;
  94688. }
  94689. _this._lastFrameTime = now;
  94690. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94691. _this._applyUserInteraction();
  94692. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  94693. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  94694. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  94695. // Step camera rotation by rotation speed
  94696. if (_this._attachedCamera) {
  94697. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  94698. }
  94699. });
  94700. };
  94701. AutoRotationBehavior.prototype.detach = function () {
  94702. if (!this._attachedCamera) {
  94703. return;
  94704. }
  94705. var scene = this._attachedCamera.getScene();
  94706. if (this._onPrePointerObservableObserver) {
  94707. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94708. }
  94709. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94710. this._attachedCamera = null;
  94711. };
  94712. /**
  94713. * Returns true if user is scrolling.
  94714. * @return true if user is scrolling.
  94715. */
  94716. AutoRotationBehavior.prototype._userIsZooming = function () {
  94717. if (!this._attachedCamera) {
  94718. return false;
  94719. }
  94720. return this._attachedCamera.inertialRadiusOffset !== 0;
  94721. };
  94722. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  94723. if (!this._attachedCamera) {
  94724. return false;
  94725. }
  94726. var zoomHasHitLimit = false;
  94727. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  94728. zoomHasHitLimit = true;
  94729. }
  94730. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  94731. this._lastFrameRadius = this._attachedCamera.radius;
  94732. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  94733. };
  94734. /**
  94735. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94736. */
  94737. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  94738. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  94739. this._lastInteractionTime = BABYLON.Tools.Now;
  94740. }
  94741. };
  94742. // Tools
  94743. AutoRotationBehavior.prototype._userIsMoving = function () {
  94744. if (!this._attachedCamera) {
  94745. return false;
  94746. }
  94747. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94748. this._attachedCamera.inertialBetaOffset !== 0 ||
  94749. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94750. this._attachedCamera.inertialPanningX !== 0 ||
  94751. this._attachedCamera.inertialPanningY !== 0 ||
  94752. this._isPointerDown;
  94753. };
  94754. return AutoRotationBehavior;
  94755. }());
  94756. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  94757. })(BABYLON || (BABYLON = {}));
  94758. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  94759. var BABYLON;
  94760. (function (BABYLON) {
  94761. var NullEngineOptions = /** @class */ (function () {
  94762. function NullEngineOptions() {
  94763. this.renderWidth = 512;
  94764. this.renderHeight = 256;
  94765. this.textureSize = 512;
  94766. this.deterministicLockstep = false;
  94767. this.lockstepMaxSteps = 4;
  94768. }
  94769. return NullEngineOptions;
  94770. }());
  94771. BABYLON.NullEngineOptions = NullEngineOptions;
  94772. /**
  94773. * The null engine class provides support for headless version of babylon.js.
  94774. * This can be used in server side scenario or for testing purposes
  94775. */
  94776. var NullEngine = /** @class */ (function (_super) {
  94777. __extends(NullEngine, _super);
  94778. function NullEngine(options) {
  94779. if (options === void 0) { options = new NullEngineOptions(); }
  94780. var _this = _super.call(this, null) || this;
  94781. if (options.deterministicLockstep === undefined) {
  94782. options.deterministicLockstep = false;
  94783. }
  94784. if (options.lockstepMaxSteps === undefined) {
  94785. options.lockstepMaxSteps = 4;
  94786. }
  94787. _this._options = options;
  94788. // Init caps
  94789. // We consider we are on a webgl1 capable device
  94790. _this._caps = new BABYLON.EngineCapabilities();
  94791. _this._caps.maxTexturesImageUnits = 16;
  94792. _this._caps.maxVertexTextureImageUnits = 16;
  94793. _this._caps.maxTextureSize = 512;
  94794. _this._caps.maxCubemapTextureSize = 512;
  94795. _this._caps.maxRenderTextureSize = 512;
  94796. _this._caps.maxVertexAttribs = 16;
  94797. _this._caps.maxVaryingVectors = 16;
  94798. _this._caps.maxFragmentUniformVectors = 16;
  94799. _this._caps.maxVertexUniformVectors = 16;
  94800. // Extensions
  94801. _this._caps.standardDerivatives = false;
  94802. _this._caps.astc = null;
  94803. _this._caps.s3tc = null;
  94804. _this._caps.pvrtc = null;
  94805. _this._caps.etc1 = null;
  94806. _this._caps.etc2 = null;
  94807. _this._caps.textureAnisotropicFilterExtension = null;
  94808. _this._caps.maxAnisotropy = 0;
  94809. _this._caps.uintIndices = false;
  94810. _this._caps.fragmentDepthSupported = false;
  94811. _this._caps.highPrecisionShaderSupported = true;
  94812. _this._caps.colorBufferFloat = false;
  94813. _this._caps.textureFloat = false;
  94814. _this._caps.textureFloatLinearFiltering = false;
  94815. _this._caps.textureFloatRender = false;
  94816. _this._caps.textureHalfFloat = false;
  94817. _this._caps.textureHalfFloatLinearFiltering = false;
  94818. _this._caps.textureHalfFloatRender = false;
  94819. _this._caps.textureLOD = false;
  94820. _this._caps.drawBuffersExtension = false;
  94821. _this._caps.depthTextureExtension = false;
  94822. _this._caps.vertexArrayObject = false;
  94823. _this._caps.instancedArrays = false;
  94824. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  94825. // Wrappers
  94826. if (typeof URL === "undefined") {
  94827. URL = {
  94828. createObjectURL: function () { },
  94829. revokeObjectURL: function () { }
  94830. };
  94831. }
  94832. if (typeof Blob === "undefined") {
  94833. Blob = function () { };
  94834. }
  94835. return _this;
  94836. }
  94837. NullEngine.prototype.isDeterministicLockStep = function () {
  94838. return this._options.deterministicLockstep;
  94839. };
  94840. NullEngine.prototype.getLockstepMaxSteps = function () {
  94841. return this._options.lockstepMaxSteps;
  94842. };
  94843. NullEngine.prototype.getHardwareScalingLevel = function () {
  94844. return 1.0;
  94845. };
  94846. NullEngine.prototype.createVertexBuffer = function (vertices) {
  94847. return {
  94848. capacity: 0,
  94849. references: 1,
  94850. is32Bits: false
  94851. };
  94852. };
  94853. NullEngine.prototype.createIndexBuffer = function (indices) {
  94854. return {
  94855. capacity: 0,
  94856. references: 1,
  94857. is32Bits: false
  94858. };
  94859. };
  94860. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  94861. if (stencil === void 0) { stencil = false; }
  94862. };
  94863. NullEngine.prototype.getRenderWidth = function (useScreen) {
  94864. if (useScreen === void 0) { useScreen = false; }
  94865. if (!useScreen && this._currentRenderTarget) {
  94866. return this._currentRenderTarget.width;
  94867. }
  94868. return this._options.renderWidth;
  94869. };
  94870. NullEngine.prototype.getRenderHeight = function (useScreen) {
  94871. if (useScreen === void 0) { useScreen = false; }
  94872. if (!useScreen && this._currentRenderTarget) {
  94873. return this._currentRenderTarget.height;
  94874. }
  94875. return this._options.renderHeight;
  94876. };
  94877. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  94878. this._cachedViewport = viewport;
  94879. };
  94880. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  94881. return {
  94882. transformFeedback: null,
  94883. __SPECTOR_rebuildProgram: null
  94884. };
  94885. };
  94886. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  94887. return [];
  94888. };
  94889. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  94890. return [];
  94891. };
  94892. NullEngine.prototype.bindSamplers = function (effect) {
  94893. this._currentEffect = null;
  94894. };
  94895. NullEngine.prototype.enableEffect = function (effect) {
  94896. this._currentEffect = effect;
  94897. if (effect.onBind) {
  94898. effect.onBind(effect);
  94899. }
  94900. effect.onBindObservable.notifyObservers(effect);
  94901. };
  94902. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  94903. if (zOffset === void 0) { zOffset = 0; }
  94904. if (reverseSide === void 0) { reverseSide = false; }
  94905. };
  94906. NullEngine.prototype.setIntArray = function (uniform, array) {
  94907. };
  94908. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  94909. };
  94910. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  94911. };
  94912. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  94913. };
  94914. NullEngine.prototype.setFloatArray = function (uniform, array) {
  94915. };
  94916. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  94917. };
  94918. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  94919. };
  94920. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  94921. };
  94922. NullEngine.prototype.setArray = function (uniform, array) {
  94923. };
  94924. NullEngine.prototype.setArray2 = function (uniform, array) {
  94925. };
  94926. NullEngine.prototype.setArray3 = function (uniform, array) {
  94927. };
  94928. NullEngine.prototype.setArray4 = function (uniform, array) {
  94929. };
  94930. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  94931. };
  94932. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  94933. };
  94934. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  94935. };
  94936. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  94937. };
  94938. NullEngine.prototype.setFloat = function (uniform, value) {
  94939. };
  94940. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  94941. };
  94942. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  94943. };
  94944. NullEngine.prototype.setBool = function (uniform, bool) {
  94945. };
  94946. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  94947. };
  94948. NullEngine.prototype.setColor3 = function (uniform, color3) {
  94949. };
  94950. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  94951. };
  94952. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  94953. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  94954. if (this._alphaMode === mode) {
  94955. return;
  94956. }
  94957. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  94958. if (!noDepthWriteChange) {
  94959. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  94960. }
  94961. this._alphaMode = mode;
  94962. };
  94963. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  94964. };
  94965. NullEngine.prototype.wipeCaches = function (bruteForce) {
  94966. if (this.preventCacheWipeBetweenFrames) {
  94967. return;
  94968. }
  94969. this.resetTextureCache();
  94970. this._currentEffect = null;
  94971. if (bruteForce) {
  94972. this._currentProgram = null;
  94973. this._stencilState.reset();
  94974. this._depthCullingState.reset();
  94975. this._alphaState.reset();
  94976. }
  94977. this._cachedVertexBuffers = null;
  94978. this._cachedIndexBuffer = null;
  94979. this._cachedEffectForVertexBuffers = null;
  94980. };
  94981. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  94982. };
  94983. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  94984. };
  94985. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  94986. };
  94987. NullEngine.prototype._createTexture = function () {
  94988. return {};
  94989. };
  94990. NullEngine.prototype._releaseTexture = function (texture) {
  94991. };
  94992. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  94993. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  94994. if (onLoad === void 0) { onLoad = null; }
  94995. if (onError === void 0) { onError = null; }
  94996. if (buffer === void 0) { buffer = null; }
  94997. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  94998. var url = String(urlArg);
  94999. texture.url = url;
  95000. texture.generateMipMaps = !noMipmap;
  95001. texture.samplingMode = samplingMode;
  95002. texture.invertY = invertY;
  95003. texture.baseWidth = this._options.textureSize;
  95004. texture.baseHeight = this._options.textureSize;
  95005. texture.width = this._options.textureSize;
  95006. texture.height = this._options.textureSize;
  95007. if (format) {
  95008. texture.format = format;
  95009. }
  95010. texture.isReady = true;
  95011. if (onLoad) {
  95012. onLoad();
  95013. }
  95014. return texture;
  95015. };
  95016. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  95017. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  95018. if (options !== undefined && typeof options === "object") {
  95019. fullOptions.generateMipMaps = options.generateMipMaps;
  95020. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  95021. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  95022. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  95023. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  95024. }
  95025. else {
  95026. fullOptions.generateMipMaps = options;
  95027. fullOptions.generateDepthBuffer = true;
  95028. fullOptions.generateStencilBuffer = false;
  95029. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95030. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  95031. }
  95032. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  95033. var width = size.width || size;
  95034. var height = size.height || size;
  95035. texture._depthStencilBuffer = {};
  95036. texture._framebuffer = {};
  95037. texture.baseWidth = width;
  95038. texture.baseHeight = height;
  95039. texture.width = width;
  95040. texture.height = height;
  95041. texture.isReady = true;
  95042. texture.samples = 1;
  95043. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  95044. texture.samplingMode = fullOptions.samplingMode;
  95045. texture.type = fullOptions.type;
  95046. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  95047. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  95048. return texture;
  95049. };
  95050. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  95051. texture.samplingMode = samplingMode;
  95052. };
  95053. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  95054. if (this._currentRenderTarget) {
  95055. this.unBindFramebuffer(this._currentRenderTarget);
  95056. }
  95057. this._currentRenderTarget = texture;
  95058. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  95059. if (this._cachedViewport && !forceFullscreenViewport) {
  95060. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  95061. }
  95062. };
  95063. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  95064. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  95065. this._currentRenderTarget = null;
  95066. if (onBeforeUnbind) {
  95067. if (texture._MSAAFramebuffer) {
  95068. this._currentFramebuffer = texture._framebuffer;
  95069. }
  95070. onBeforeUnbind();
  95071. }
  95072. this._currentFramebuffer = null;
  95073. };
  95074. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  95075. var vbo = {
  95076. capacity: 1,
  95077. references: 1,
  95078. is32Bits: false
  95079. };
  95080. return vbo;
  95081. };
  95082. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  95083. if (offset === void 0) { offset = 0; }
  95084. };
  95085. /**
  95086. * Updates a dynamic vertex buffer.
  95087. * @param vertexBuffer the vertex buffer to update
  95088. * @param data the data used to update the vertex buffer
  95089. * @param byteOffset the byte offset of the data (optional)
  95090. * @param byteLength the byte length of the data (optional)
  95091. */
  95092. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  95093. };
  95094. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  95095. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  95096. this._boundTexturesCache[this._activeChannel] = texture;
  95097. }
  95098. };
  95099. NullEngine.prototype._bindTexture = function (channel, texture) {
  95100. if (channel < 0) {
  95101. return;
  95102. }
  95103. this._bindTextureDirectly(0, texture);
  95104. };
  95105. NullEngine.prototype._releaseBuffer = function (buffer) {
  95106. buffer.references--;
  95107. if (buffer.references === 0) {
  95108. return true;
  95109. }
  95110. return false;
  95111. };
  95112. return NullEngine;
  95113. }(BABYLON.Engine));
  95114. BABYLON.NullEngine = NullEngine;
  95115. })(BABYLON || (BABYLON = {}));
  95116. //# sourceMappingURL=babylon.nullEngine.js.map
  95117. var BABYLON;
  95118. (function (BABYLON) {
  95119. /**
  95120. * This class can be used to get instrumentation data from a Babylon engine
  95121. */
  95122. var EngineInstrumentation = /** @class */ (function () {
  95123. function EngineInstrumentation(engine) {
  95124. this.engine = engine;
  95125. this._captureGPUFrameTime = false;
  95126. this._gpuFrameTime = new BABYLON.PerfCounter();
  95127. this._captureShaderCompilationTime = false;
  95128. this._shaderCompilationTime = new BABYLON.PerfCounter();
  95129. // Observers
  95130. this._onBeginFrameObserver = null;
  95131. this._onEndFrameObserver = null;
  95132. this._onBeforeShaderCompilationObserver = null;
  95133. this._onAfterShaderCompilationObserver = null;
  95134. }
  95135. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  95136. // Properties
  95137. /**
  95138. * Gets the perf counter used for GPU frame time
  95139. */
  95140. get: function () {
  95141. return this._gpuFrameTime;
  95142. },
  95143. enumerable: true,
  95144. configurable: true
  95145. });
  95146. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  95147. /**
  95148. * Gets the GPU frame time capture status
  95149. */
  95150. get: function () {
  95151. return this._captureGPUFrameTime;
  95152. },
  95153. /**
  95154. * Enable or disable the GPU frame time capture
  95155. */
  95156. set: function (value) {
  95157. var _this = this;
  95158. if (value === this._captureGPUFrameTime) {
  95159. return;
  95160. }
  95161. this._captureGPUFrameTime = value;
  95162. if (value) {
  95163. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  95164. if (!_this._gpuFrameTimeToken) {
  95165. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  95166. }
  95167. });
  95168. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  95169. if (!_this._gpuFrameTimeToken) {
  95170. return;
  95171. }
  95172. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  95173. if (time > -1) {
  95174. _this._gpuFrameTimeToken = null;
  95175. _this._gpuFrameTime.fetchNewFrame();
  95176. _this._gpuFrameTime.addCount(time, true);
  95177. }
  95178. });
  95179. }
  95180. else {
  95181. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95182. this._onBeginFrameObserver = null;
  95183. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95184. this._onEndFrameObserver = null;
  95185. }
  95186. },
  95187. enumerable: true,
  95188. configurable: true
  95189. });
  95190. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  95191. /**
  95192. * Gets the perf counter used for shader compilation time
  95193. */
  95194. get: function () {
  95195. return this._shaderCompilationTime;
  95196. },
  95197. enumerable: true,
  95198. configurable: true
  95199. });
  95200. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  95201. /**
  95202. * Gets the shader compilation time capture status
  95203. */
  95204. get: function () {
  95205. return this._captureShaderCompilationTime;
  95206. },
  95207. /**
  95208. * Enable or disable the shader compilation time capture
  95209. */
  95210. set: function (value) {
  95211. var _this = this;
  95212. if (value === this._captureShaderCompilationTime) {
  95213. return;
  95214. }
  95215. this._captureShaderCompilationTime = value;
  95216. if (value) {
  95217. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  95218. _this._shaderCompilationTime.fetchNewFrame();
  95219. _this._shaderCompilationTime.beginMonitoring();
  95220. });
  95221. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  95222. _this._shaderCompilationTime.endMonitoring();
  95223. });
  95224. }
  95225. else {
  95226. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95227. this._onBeforeShaderCompilationObserver = null;
  95228. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95229. this._onAfterShaderCompilationObserver = null;
  95230. }
  95231. },
  95232. enumerable: true,
  95233. configurable: true
  95234. });
  95235. EngineInstrumentation.prototype.dispose = function () {
  95236. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95237. this._onBeginFrameObserver = null;
  95238. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95239. this._onEndFrameObserver = null;
  95240. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95241. this._onBeforeShaderCompilationObserver = null;
  95242. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95243. this._onAfterShaderCompilationObserver = null;
  95244. this.engine = null;
  95245. };
  95246. return EngineInstrumentation;
  95247. }());
  95248. BABYLON.EngineInstrumentation = EngineInstrumentation;
  95249. })(BABYLON || (BABYLON = {}));
  95250. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  95251. var BABYLON;
  95252. (function (BABYLON) {
  95253. /**
  95254. * This class can be used to get instrumentation data from a Babylon engine
  95255. */
  95256. var SceneInstrumentation = /** @class */ (function () {
  95257. function SceneInstrumentation(scene) {
  95258. var _this = this;
  95259. this.scene = scene;
  95260. this._captureActiveMeshesEvaluationTime = false;
  95261. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  95262. this._captureRenderTargetsRenderTime = false;
  95263. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  95264. this._captureFrameTime = false;
  95265. this._frameTime = new BABYLON.PerfCounter();
  95266. this._captureRenderTime = false;
  95267. this._renderTime = new BABYLON.PerfCounter();
  95268. this._captureInterFrameTime = false;
  95269. this._interFrameTime = new BABYLON.PerfCounter();
  95270. this._captureParticlesRenderTime = false;
  95271. this._particlesRenderTime = new BABYLON.PerfCounter();
  95272. this._captureSpritesRenderTime = false;
  95273. this._spritesRenderTime = new BABYLON.PerfCounter();
  95274. this._capturePhysicsTime = false;
  95275. this._physicsTime = new BABYLON.PerfCounter();
  95276. this._captureAnimationsTime = false;
  95277. this._animationsTime = new BABYLON.PerfCounter();
  95278. // Observers
  95279. this._onBeforeActiveMeshesEvaluationObserver = null;
  95280. this._onAfterActiveMeshesEvaluationObserver = null;
  95281. this._onBeforeRenderTargetsRenderObserver = null;
  95282. this._onAfterRenderTargetsRenderObserver = null;
  95283. this._onAfterRenderObserver = null;
  95284. this._onBeforeDrawPhaseObserver = null;
  95285. this._onAfterDrawPhaseObserver = null;
  95286. this._onBeforeAnimationsObserver = null;
  95287. this._onBeforeParticlesRenderingObserver = null;
  95288. this._onAfterParticlesRenderingObserver = null;
  95289. this._onBeforeSpritesRenderingObserver = null;
  95290. this._onAfterSpritesRenderingObserver = null;
  95291. this._onBeforePhysicsObserver = null;
  95292. this._onAfterPhysicsObserver = null;
  95293. this._onAfterAnimationsObserver = null;
  95294. // Before render
  95295. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  95296. if (_this._captureActiveMeshesEvaluationTime) {
  95297. _this._activeMeshesEvaluationTime.fetchNewFrame();
  95298. }
  95299. if (_this._captureRenderTargetsRenderTime) {
  95300. _this._renderTargetsRenderTime.fetchNewFrame();
  95301. }
  95302. if (_this._captureFrameTime) {
  95303. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  95304. _this._frameTime.beginMonitoring();
  95305. }
  95306. if (_this._captureInterFrameTime) {
  95307. _this._interFrameTime.endMonitoring();
  95308. }
  95309. if (_this._captureParticlesRenderTime) {
  95310. _this._particlesRenderTime.fetchNewFrame();
  95311. }
  95312. if (_this._captureSpritesRenderTime) {
  95313. _this._spritesRenderTime.fetchNewFrame();
  95314. }
  95315. if (_this._captureAnimationsTime) {
  95316. _this._animationsTime.beginMonitoring();
  95317. }
  95318. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  95319. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  95320. });
  95321. // After render
  95322. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  95323. if (_this._captureFrameTime) {
  95324. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  95325. _this._frameTime.endMonitoring();
  95326. }
  95327. if (_this._captureRenderTime) {
  95328. _this._renderTime.endMonitoring(false);
  95329. }
  95330. if (_this._captureInterFrameTime) {
  95331. _this._interFrameTime.beginMonitoring();
  95332. }
  95333. });
  95334. }
  95335. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  95336. // Properties
  95337. /**
  95338. * Gets the perf counter used for active meshes evaluation time
  95339. */
  95340. get: function () {
  95341. return this._activeMeshesEvaluationTime;
  95342. },
  95343. enumerable: true,
  95344. configurable: true
  95345. });
  95346. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  95347. /**
  95348. * Gets the active meshes evaluation time capture status
  95349. */
  95350. get: function () {
  95351. return this._captureActiveMeshesEvaluationTime;
  95352. },
  95353. /**
  95354. * Enable or disable the active meshes evaluation time capture
  95355. */
  95356. set: function (value) {
  95357. var _this = this;
  95358. if (value === this._captureActiveMeshesEvaluationTime) {
  95359. return;
  95360. }
  95361. this._captureActiveMeshesEvaluationTime = value;
  95362. if (value) {
  95363. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  95364. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  95365. _this._activeMeshesEvaluationTime.beginMonitoring();
  95366. });
  95367. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  95368. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  95369. _this._activeMeshesEvaluationTime.endMonitoring();
  95370. });
  95371. }
  95372. else {
  95373. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95374. this._onBeforeActiveMeshesEvaluationObserver = null;
  95375. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95376. this._onAfterActiveMeshesEvaluationObserver = null;
  95377. }
  95378. },
  95379. enumerable: true,
  95380. configurable: true
  95381. });
  95382. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  95383. /**
  95384. * Gets the perf counter used for render targets render time
  95385. */
  95386. get: function () {
  95387. return this._renderTargetsRenderTime;
  95388. },
  95389. enumerable: true,
  95390. configurable: true
  95391. });
  95392. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  95393. /**
  95394. * Gets the render targets render time capture status
  95395. */
  95396. get: function () {
  95397. return this._captureRenderTargetsRenderTime;
  95398. },
  95399. /**
  95400. * Enable or disable the render targets render time capture
  95401. */
  95402. set: function (value) {
  95403. var _this = this;
  95404. if (value === this._captureRenderTargetsRenderTime) {
  95405. return;
  95406. }
  95407. this._captureRenderTargetsRenderTime = value;
  95408. if (value) {
  95409. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  95410. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  95411. _this._renderTargetsRenderTime.beginMonitoring();
  95412. });
  95413. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  95414. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  95415. _this._renderTargetsRenderTime.endMonitoring(false);
  95416. });
  95417. }
  95418. else {
  95419. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95420. this._onBeforeRenderTargetsRenderObserver = null;
  95421. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95422. this._onAfterRenderTargetsRenderObserver = null;
  95423. }
  95424. },
  95425. enumerable: true,
  95426. configurable: true
  95427. });
  95428. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  95429. /**
  95430. * Gets the perf counter used for particles render time
  95431. */
  95432. get: function () {
  95433. return this._particlesRenderTime;
  95434. },
  95435. enumerable: true,
  95436. configurable: true
  95437. });
  95438. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  95439. /**
  95440. * Gets the particles render time capture status
  95441. */
  95442. get: function () {
  95443. return this._captureParticlesRenderTime;
  95444. },
  95445. /**
  95446. * Enable or disable the particles render time capture
  95447. */
  95448. set: function (value) {
  95449. var _this = this;
  95450. if (value === this._captureParticlesRenderTime) {
  95451. return;
  95452. }
  95453. this._captureParticlesRenderTime = value;
  95454. if (value) {
  95455. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  95456. BABYLON.Tools.StartPerformanceCounter("Particles");
  95457. _this._particlesRenderTime.beginMonitoring();
  95458. });
  95459. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  95460. BABYLON.Tools.EndPerformanceCounter("Particles");
  95461. _this._particlesRenderTime.endMonitoring(false);
  95462. });
  95463. }
  95464. else {
  95465. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95466. this._onBeforeParticlesRenderingObserver = null;
  95467. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95468. this._onAfterParticlesRenderingObserver = null;
  95469. }
  95470. },
  95471. enumerable: true,
  95472. configurable: true
  95473. });
  95474. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  95475. /**
  95476. * Gets the perf counter used for sprites render time
  95477. */
  95478. get: function () {
  95479. return this._spritesRenderTime;
  95480. },
  95481. enumerable: true,
  95482. configurable: true
  95483. });
  95484. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  95485. /**
  95486. * Gets the sprites render time capture status
  95487. */
  95488. get: function () {
  95489. return this._captureSpritesRenderTime;
  95490. },
  95491. /**
  95492. * Enable or disable the sprites render time capture
  95493. */
  95494. set: function (value) {
  95495. var _this = this;
  95496. if (value === this._captureSpritesRenderTime) {
  95497. return;
  95498. }
  95499. this._captureSpritesRenderTime = value;
  95500. if (value) {
  95501. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  95502. BABYLON.Tools.StartPerformanceCounter("Sprites");
  95503. _this._spritesRenderTime.beginMonitoring();
  95504. });
  95505. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  95506. BABYLON.Tools.EndPerformanceCounter("Sprites");
  95507. _this._spritesRenderTime.endMonitoring(false);
  95508. });
  95509. }
  95510. else {
  95511. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95512. this._onBeforeSpritesRenderingObserver = null;
  95513. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95514. this._onAfterSpritesRenderingObserver = null;
  95515. }
  95516. },
  95517. enumerable: true,
  95518. configurable: true
  95519. });
  95520. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  95521. /**
  95522. * Gets the perf counter used for physics time
  95523. */
  95524. get: function () {
  95525. return this._physicsTime;
  95526. },
  95527. enumerable: true,
  95528. configurable: true
  95529. });
  95530. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  95531. /**
  95532. * Gets the physics time capture status
  95533. */
  95534. get: function () {
  95535. return this._capturePhysicsTime;
  95536. },
  95537. /**
  95538. * Enable or disable the physics time capture
  95539. */
  95540. set: function (value) {
  95541. var _this = this;
  95542. if (value === this._capturePhysicsTime) {
  95543. return;
  95544. }
  95545. this._capturePhysicsTime = value;
  95546. if (value) {
  95547. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  95548. BABYLON.Tools.StartPerformanceCounter("Physics");
  95549. _this._physicsTime.beginMonitoring();
  95550. });
  95551. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  95552. BABYLON.Tools.EndPerformanceCounter("Physics");
  95553. _this._physicsTime.endMonitoring();
  95554. });
  95555. }
  95556. else {
  95557. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95558. this._onBeforePhysicsObserver = null;
  95559. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95560. this._onAfterPhysicsObserver = null;
  95561. }
  95562. },
  95563. enumerable: true,
  95564. configurable: true
  95565. });
  95566. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  95567. /**
  95568. * Gets the perf counter used for animations time
  95569. */
  95570. get: function () {
  95571. return this._animationsTime;
  95572. },
  95573. enumerable: true,
  95574. configurable: true
  95575. });
  95576. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  95577. /**
  95578. * Gets the animations time capture status
  95579. */
  95580. get: function () {
  95581. return this._captureAnimationsTime;
  95582. },
  95583. /**
  95584. * Enable or disable the animations time capture
  95585. */
  95586. set: function (value) {
  95587. var _this = this;
  95588. if (value === this._captureAnimationsTime) {
  95589. return;
  95590. }
  95591. this._captureAnimationsTime = value;
  95592. if (value) {
  95593. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  95594. _this._animationsTime.endMonitoring();
  95595. });
  95596. }
  95597. else {
  95598. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95599. this._onAfterAnimationsObserver = null;
  95600. }
  95601. },
  95602. enumerable: true,
  95603. configurable: true
  95604. });
  95605. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  95606. /**
  95607. * Gets the perf counter used for frame time capture
  95608. */
  95609. get: function () {
  95610. return this._frameTime;
  95611. },
  95612. enumerable: true,
  95613. configurable: true
  95614. });
  95615. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  95616. /**
  95617. * Gets the frame time capture status
  95618. */
  95619. get: function () {
  95620. return this._captureFrameTime;
  95621. },
  95622. /**
  95623. * Enable or disable the frame time capture
  95624. */
  95625. set: function (value) {
  95626. this._captureFrameTime = value;
  95627. },
  95628. enumerable: true,
  95629. configurable: true
  95630. });
  95631. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  95632. /**
  95633. * Gets the perf counter used for inter-frames time capture
  95634. */
  95635. get: function () {
  95636. return this._interFrameTime;
  95637. },
  95638. enumerable: true,
  95639. configurable: true
  95640. });
  95641. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  95642. /**
  95643. * Gets the inter-frames time capture status
  95644. */
  95645. get: function () {
  95646. return this._captureInterFrameTime;
  95647. },
  95648. /**
  95649. * Enable or disable the inter-frames time capture
  95650. */
  95651. set: function (value) {
  95652. this._captureInterFrameTime = value;
  95653. },
  95654. enumerable: true,
  95655. configurable: true
  95656. });
  95657. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  95658. /**
  95659. * Gets the perf counter used for render time capture
  95660. */
  95661. get: function () {
  95662. return this._renderTime;
  95663. },
  95664. enumerable: true,
  95665. configurable: true
  95666. });
  95667. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  95668. /**
  95669. * Gets the render time capture status
  95670. */
  95671. get: function () {
  95672. return this._captureRenderTime;
  95673. },
  95674. /**
  95675. * Enable or disable the render time capture
  95676. */
  95677. set: function (value) {
  95678. var _this = this;
  95679. if (value === this._captureRenderTime) {
  95680. return;
  95681. }
  95682. this._captureRenderTime = value;
  95683. if (value) {
  95684. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  95685. _this._renderTime.beginMonitoring();
  95686. BABYLON.Tools.StartPerformanceCounter("Main render");
  95687. });
  95688. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  95689. _this._renderTime.endMonitoring(false);
  95690. BABYLON.Tools.EndPerformanceCounter("Main render");
  95691. });
  95692. }
  95693. else {
  95694. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95695. this._onBeforeDrawPhaseObserver = null;
  95696. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95697. this._onAfterDrawPhaseObserver = null;
  95698. }
  95699. },
  95700. enumerable: true,
  95701. configurable: true
  95702. });
  95703. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  95704. /**
  95705. * Gets the perf counter used for draw calls
  95706. */
  95707. get: function () {
  95708. return this.scene.getEngine()._drawCalls;
  95709. },
  95710. enumerable: true,
  95711. configurable: true
  95712. });
  95713. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  95714. /**
  95715. * Gets the perf counter used for texture collisions
  95716. */
  95717. get: function () {
  95718. return this.scene.getEngine()._textureCollisions;
  95719. },
  95720. enumerable: true,
  95721. configurable: true
  95722. });
  95723. SceneInstrumentation.prototype.dispose = function () {
  95724. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  95725. this._onAfterRenderObserver = null;
  95726. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95727. this._onBeforeActiveMeshesEvaluationObserver = null;
  95728. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95729. this._onAfterActiveMeshesEvaluationObserver = null;
  95730. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95731. this._onBeforeRenderTargetsRenderObserver = null;
  95732. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95733. this._onAfterRenderTargetsRenderObserver = null;
  95734. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  95735. this._onBeforeAnimationsObserver = null;
  95736. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95737. this._onBeforeParticlesRenderingObserver = null;
  95738. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95739. this._onAfterParticlesRenderingObserver = null;
  95740. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95741. this._onBeforeSpritesRenderingObserver = null;
  95742. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95743. this._onAfterSpritesRenderingObserver = null;
  95744. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95745. this._onBeforeDrawPhaseObserver = null;
  95746. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95747. this._onAfterDrawPhaseObserver = null;
  95748. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95749. this._onBeforePhysicsObserver = null;
  95750. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95751. this._onAfterPhysicsObserver = null;
  95752. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95753. this._onAfterAnimationsObserver = null;
  95754. this.scene = null;
  95755. };
  95756. return SceneInstrumentation;
  95757. }());
  95758. BABYLON.SceneInstrumentation = SceneInstrumentation;
  95759. })(BABYLON || (BABYLON = {}));
  95760. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  95761. var BABYLON;
  95762. (function (BABYLON) {
  95763. /**
  95764. * @hidden
  95765. **/
  95766. var _TimeToken = /** @class */ (function () {
  95767. function _TimeToken() {
  95768. this._timeElapsedQueryEnded = false;
  95769. }
  95770. return _TimeToken;
  95771. }());
  95772. BABYLON._TimeToken = _TimeToken;
  95773. })(BABYLON || (BABYLON = {}));
  95774. //# sourceMappingURL=babylon.timeToken.js.map
  95775. var BABYLON;
  95776. (function (BABYLON) {
  95777. /**
  95778. * Background material defines definition.
  95779. * @hidden Mainly internal Use
  95780. */
  95781. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  95782. __extends(BackgroundMaterialDefines, _super);
  95783. /**
  95784. * Constructor of the defines.
  95785. */
  95786. function BackgroundMaterialDefines() {
  95787. var _this = _super.call(this) || this;
  95788. /**
  95789. * True if the diffuse texture is in use.
  95790. */
  95791. _this.DIFFUSE = false;
  95792. /**
  95793. * The direct UV channel to use.
  95794. */
  95795. _this.DIFFUSEDIRECTUV = 0;
  95796. /**
  95797. * True if the diffuse texture is in gamma space.
  95798. */
  95799. _this.GAMMADIFFUSE = false;
  95800. /**
  95801. * True if the diffuse texture has opacity in the alpha channel.
  95802. */
  95803. _this.DIFFUSEHASALPHA = false;
  95804. /**
  95805. * True if you want the material to fade to transparent at grazing angle.
  95806. */
  95807. _this.OPACITYFRESNEL = false;
  95808. /**
  95809. * True if an extra blur needs to be added in the reflection.
  95810. */
  95811. _this.REFLECTIONBLUR = false;
  95812. /**
  95813. * True if you want the material to fade to reflection at grazing angle.
  95814. */
  95815. _this.REFLECTIONFRESNEL = false;
  95816. /**
  95817. * True if you want the material to falloff as far as you move away from the scene center.
  95818. */
  95819. _this.REFLECTIONFALLOFF = false;
  95820. /**
  95821. * False if the current Webgl implementation does not support the texture lod extension.
  95822. */
  95823. _this.TEXTURELODSUPPORT = false;
  95824. /**
  95825. * True to ensure the data are premultiplied.
  95826. */
  95827. _this.PREMULTIPLYALPHA = false;
  95828. /**
  95829. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  95830. */
  95831. _this.USERGBCOLOR = false;
  95832. /**
  95833. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  95834. * stays aligned with the desired configuration.
  95835. */
  95836. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  95837. /**
  95838. * True to add noise in order to reduce the banding effect.
  95839. */
  95840. _this.NOISE = false;
  95841. /**
  95842. * is the reflection texture in BGR color scheme?
  95843. * Mainly used to solve a bug in ios10 video tag
  95844. */
  95845. _this.REFLECTIONBGR = false;
  95846. _this.IMAGEPROCESSING = false;
  95847. _this.VIGNETTE = false;
  95848. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  95849. _this.VIGNETTEBLENDMODEOPAQUE = false;
  95850. _this.TONEMAPPING = false;
  95851. _this.CONTRAST = false;
  95852. _this.COLORCURVES = false;
  95853. _this.COLORGRADING = false;
  95854. _this.COLORGRADING3D = false;
  95855. _this.SAMPLER3DGREENDEPTH = false;
  95856. _this.SAMPLER3DBGRMAP = false;
  95857. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  95858. _this.EXPOSURE = false;
  95859. // Reflection.
  95860. _this.REFLECTION = false;
  95861. _this.REFLECTIONMAP_3D = false;
  95862. _this.REFLECTIONMAP_SPHERICAL = false;
  95863. _this.REFLECTIONMAP_PLANAR = false;
  95864. _this.REFLECTIONMAP_CUBIC = false;
  95865. _this.REFLECTIONMAP_PROJECTION = false;
  95866. _this.REFLECTIONMAP_SKYBOX = false;
  95867. _this.REFLECTIONMAP_EXPLICIT = false;
  95868. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  95869. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  95870. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  95871. _this.INVERTCUBICMAP = false;
  95872. _this.REFLECTIONMAP_OPPOSITEZ = false;
  95873. _this.LODINREFLECTIONALPHA = false;
  95874. _this.GAMMAREFLECTION = false;
  95875. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  95876. // Default BJS.
  95877. _this.MAINUV1 = false;
  95878. _this.MAINUV2 = false;
  95879. _this.UV1 = false;
  95880. _this.UV2 = false;
  95881. _this.CLIPPLANE = false;
  95882. _this.POINTSIZE = false;
  95883. _this.FOG = false;
  95884. _this.NORMAL = false;
  95885. _this.NUM_BONE_INFLUENCERS = 0;
  95886. _this.BonesPerMesh = 0;
  95887. _this.INSTANCES = false;
  95888. _this.SHADOWFLOAT = false;
  95889. _this.rebuild();
  95890. return _this;
  95891. }
  95892. return BackgroundMaterialDefines;
  95893. }(BABYLON.MaterialDefines));
  95894. /**
  95895. * Background material used to create an efficient environement around your scene.
  95896. */
  95897. var BackgroundMaterial = /** @class */ (function (_super) {
  95898. __extends(BackgroundMaterial, _super);
  95899. /**
  95900. * Instantiates a Background Material in the given scene
  95901. * @param name The friendly name of the material
  95902. * @param scene The scene to add the material to
  95903. */
  95904. function BackgroundMaterial(name, scene) {
  95905. var _this = _super.call(this, name, scene) || this;
  95906. /**
  95907. * Key light Color (multiply against the environement texture)
  95908. */
  95909. _this.primaryColor = BABYLON.Color3.White();
  95910. _this._primaryColorShadowLevel = 0;
  95911. _this._primaryColorHighlightLevel = 0;
  95912. /**
  95913. * Reflection Texture used in the material.
  95914. * Should be author in a specific way for the best result (refer to the documentation).
  95915. */
  95916. _this.reflectionTexture = null;
  95917. /**
  95918. * Reflection Texture level of blur.
  95919. *
  95920. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  95921. * texture twice.
  95922. */
  95923. _this.reflectionBlur = 0;
  95924. /**
  95925. * Diffuse Texture used in the material.
  95926. * Should be author in a specific way for the best result (refer to the documentation).
  95927. */
  95928. _this.diffuseTexture = null;
  95929. _this._shadowLights = null;
  95930. /**
  95931. * Specify the list of lights casting shadow on the material.
  95932. * All scene shadow lights will be included if null.
  95933. */
  95934. _this.shadowLights = null;
  95935. /**
  95936. * Helps adjusting the shadow to a softer level if required.
  95937. * 0 means black shadows and 1 means no shadows.
  95938. */
  95939. _this.shadowLevel = 0;
  95940. /**
  95941. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  95942. * It is usually zero but might be interesting to modify according to your setup.
  95943. */
  95944. _this.sceneCenter = BABYLON.Vector3.Zero();
  95945. /**
  95946. * This helps specifying that the material is falling off to the sky box at grazing angle.
  95947. * This helps ensuring a nice transition when the camera goes under the ground.
  95948. */
  95949. _this.opacityFresnel = true;
  95950. /**
  95951. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  95952. * This helps adding a mirror texture on the ground.
  95953. */
  95954. _this.reflectionFresnel = false;
  95955. /**
  95956. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  95957. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  95958. */
  95959. _this.reflectionFalloffDistance = 0.0;
  95960. /**
  95961. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  95962. */
  95963. _this.reflectionAmount = 1.0;
  95964. /**
  95965. * This specifies the weight of the reflection at grazing angle.
  95966. */
  95967. _this.reflectionReflectance0 = 0.05;
  95968. /**
  95969. * This specifies the weight of the reflection at a perpendicular point of view.
  95970. */
  95971. _this.reflectionReflectance90 = 0.5;
  95972. /**
  95973. * Helps to directly use the maps channels instead of their level.
  95974. */
  95975. _this.useRGBColor = true;
  95976. /**
  95977. * This helps reducing the banding effect that could occur on the background.
  95978. */
  95979. _this.enableNoise = false;
  95980. _this._fovMultiplier = 1.0;
  95981. /**
  95982. * Enable the FOV adjustment feature controlled by fovMultiplier.
  95983. */
  95984. _this.useEquirectangularFOV = false;
  95985. _this._maxSimultaneousLights = 4;
  95986. /**
  95987. * Number of Simultaneous lights allowed on the material.
  95988. */
  95989. _this.maxSimultaneousLights = 4;
  95990. /**
  95991. * Keep track of the image processing observer to allow dispose and replace.
  95992. */
  95993. _this._imageProcessingObserver = null;
  95994. /**
  95995. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  95996. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  95997. */
  95998. _this.switchToBGR = false;
  95999. // Temp values kept as cache in the material.
  96000. _this._renderTargets = new BABYLON.SmartArray(16);
  96001. _this._reflectionControls = BABYLON.Vector4.Zero();
  96002. _this._white = BABYLON.Color3.White();
  96003. _this._primaryShadowColor = BABYLON.Color3.Black();
  96004. _this._primaryHighlightColor = BABYLON.Color3.Black();
  96005. // Setup the default processing configuration to the scene.
  96006. _this._attachImageProcessingConfiguration(null);
  96007. _this.getRenderTargetTextures = function () {
  96008. _this._renderTargets.reset();
  96009. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  96010. _this._renderTargets.push(_this._diffuseTexture);
  96011. }
  96012. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  96013. _this._renderTargets.push(_this._reflectionTexture);
  96014. }
  96015. return _this._renderTargets;
  96016. };
  96017. return _this;
  96018. }
  96019. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  96020. /**
  96021. * Experimental Internal Use Only.
  96022. *
  96023. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  96024. * This acts as a helper to set the primary color to a more "human friendly" value.
  96025. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  96026. * output color as close as possible from the chosen value.
  96027. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  96028. * part of lighting setup.)
  96029. */
  96030. get: function () {
  96031. return this.__perceptualColor;
  96032. },
  96033. set: function (value) {
  96034. this.__perceptualColor = value;
  96035. this._computePrimaryColorFromPerceptualColor();
  96036. this._markAllSubMeshesAsLightsDirty();
  96037. },
  96038. enumerable: true,
  96039. configurable: true
  96040. });
  96041. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  96042. /**
  96043. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  96044. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  96045. */
  96046. get: function () {
  96047. return this._primaryColorShadowLevel;
  96048. },
  96049. set: function (value) {
  96050. this._primaryColorShadowLevel = value;
  96051. this._computePrimaryColors();
  96052. this._markAllSubMeshesAsLightsDirty();
  96053. },
  96054. enumerable: true,
  96055. configurable: true
  96056. });
  96057. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  96058. /**
  96059. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  96060. * The primary color is used at the level chosen to define what the white area would look.
  96061. */
  96062. get: function () {
  96063. return this._primaryColorHighlightLevel;
  96064. },
  96065. set: function (value) {
  96066. this._primaryColorHighlightLevel = value;
  96067. this._computePrimaryColors();
  96068. this._markAllSubMeshesAsLightsDirty();
  96069. },
  96070. enumerable: true,
  96071. configurable: true
  96072. });
  96073. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  96074. /**
  96075. * Sets the reflection reflectance fresnel values according to the default standard
  96076. * empirically know to work well :-)
  96077. */
  96078. set: function (value) {
  96079. var reflectionWeight = value;
  96080. if (reflectionWeight < 0.5) {
  96081. reflectionWeight = reflectionWeight * 2.0;
  96082. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  96083. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  96084. }
  96085. else {
  96086. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  96087. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  96088. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  96089. }
  96090. },
  96091. enumerable: true,
  96092. configurable: true
  96093. });
  96094. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  96095. /**
  96096. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96097. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  96098. * Recommended to be keep at 1.0 except for special cases.
  96099. */
  96100. get: function () {
  96101. return this._fovMultiplier;
  96102. },
  96103. set: function (value) {
  96104. if (isNaN(value)) {
  96105. value = 1.0;
  96106. }
  96107. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  96108. },
  96109. enumerable: true,
  96110. configurable: true
  96111. });
  96112. /**
  96113. * Attaches a new image processing configuration to the PBR Material.
  96114. * @param configuration (if null the scene configuration will be use)
  96115. */
  96116. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  96117. var _this = this;
  96118. if (configuration === this._imageProcessingConfiguration) {
  96119. return;
  96120. }
  96121. // Detaches observer.
  96122. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96123. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96124. }
  96125. // Pick the scene configuration if needed.
  96126. if (!configuration) {
  96127. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  96128. }
  96129. else {
  96130. this._imageProcessingConfiguration = configuration;
  96131. }
  96132. // Attaches observer.
  96133. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  96134. _this._computePrimaryColorFromPerceptualColor();
  96135. _this._markAllSubMeshesAsImageProcessingDirty();
  96136. });
  96137. };
  96138. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  96139. /**
  96140. * Gets the image processing configuration used either in this material.
  96141. */
  96142. get: function () {
  96143. return this._imageProcessingConfiguration;
  96144. },
  96145. /**
  96146. * Sets the Default image processing configuration used either in the this material.
  96147. *
  96148. * If sets to null, the scene one is in use.
  96149. */
  96150. set: function (value) {
  96151. this._attachImageProcessingConfiguration(value);
  96152. // Ensure the effect will be rebuilt.
  96153. this._markAllSubMeshesAsTexturesDirty();
  96154. },
  96155. enumerable: true,
  96156. configurable: true
  96157. });
  96158. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  96159. /**
  96160. * Gets wether the color curves effect is enabled.
  96161. */
  96162. get: function () {
  96163. return this.imageProcessingConfiguration.colorCurvesEnabled;
  96164. },
  96165. /**
  96166. * Sets wether the color curves effect is enabled.
  96167. */
  96168. set: function (value) {
  96169. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  96170. },
  96171. enumerable: true,
  96172. configurable: true
  96173. });
  96174. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  96175. /**
  96176. * Gets wether the color grading effect is enabled.
  96177. */
  96178. get: function () {
  96179. return this.imageProcessingConfiguration.colorGradingEnabled;
  96180. },
  96181. /**
  96182. * Gets wether the color grading effect is enabled.
  96183. */
  96184. set: function (value) {
  96185. this.imageProcessingConfiguration.colorGradingEnabled = value;
  96186. },
  96187. enumerable: true,
  96188. configurable: true
  96189. });
  96190. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  96191. /**
  96192. * Gets wether tonemapping is enabled or not.
  96193. */
  96194. get: function () {
  96195. return this._imageProcessingConfiguration.toneMappingEnabled;
  96196. },
  96197. /**
  96198. * Sets wether tonemapping is enabled or not
  96199. */
  96200. set: function (value) {
  96201. this._imageProcessingConfiguration.toneMappingEnabled = value;
  96202. },
  96203. enumerable: true,
  96204. configurable: true
  96205. });
  96206. ;
  96207. ;
  96208. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  96209. /**
  96210. * The camera exposure used on this material.
  96211. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96212. * This corresponds to a photographic exposure.
  96213. */
  96214. get: function () {
  96215. return this._imageProcessingConfiguration.exposure;
  96216. },
  96217. /**
  96218. * The camera exposure used on this material.
  96219. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96220. * This corresponds to a photographic exposure.
  96221. */
  96222. set: function (value) {
  96223. this._imageProcessingConfiguration.exposure = value;
  96224. },
  96225. enumerable: true,
  96226. configurable: true
  96227. });
  96228. ;
  96229. ;
  96230. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  96231. /**
  96232. * Gets The camera contrast used on this material.
  96233. */
  96234. get: function () {
  96235. return this._imageProcessingConfiguration.contrast;
  96236. },
  96237. /**
  96238. * Sets The camera contrast used on this material.
  96239. */
  96240. set: function (value) {
  96241. this._imageProcessingConfiguration.contrast = value;
  96242. },
  96243. enumerable: true,
  96244. configurable: true
  96245. });
  96246. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  96247. /**
  96248. * Gets the Color Grading 2D Lookup Texture.
  96249. */
  96250. get: function () {
  96251. return this._imageProcessingConfiguration.colorGradingTexture;
  96252. },
  96253. /**
  96254. * Sets the Color Grading 2D Lookup Texture.
  96255. */
  96256. set: function (value) {
  96257. this.imageProcessingConfiguration.colorGradingTexture = value;
  96258. },
  96259. enumerable: true,
  96260. configurable: true
  96261. });
  96262. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  96263. /**
  96264. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96265. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96266. * 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;
  96267. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96268. */
  96269. get: function () {
  96270. return this.imageProcessingConfiguration.colorCurves;
  96271. },
  96272. /**
  96273. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96274. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96275. * 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;
  96276. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96277. */
  96278. set: function (value) {
  96279. this.imageProcessingConfiguration.colorCurves = value;
  96280. },
  96281. enumerable: true,
  96282. configurable: true
  96283. });
  96284. /**
  96285. * The entire material has been created in order to prevent overdraw.
  96286. * @returns false
  96287. */
  96288. BackgroundMaterial.prototype.needAlphaTesting = function () {
  96289. return true;
  96290. };
  96291. /**
  96292. * The entire material has been created in order to prevent overdraw.
  96293. * @returns true if blending is enable
  96294. */
  96295. BackgroundMaterial.prototype.needAlphaBlending = function () {
  96296. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  96297. };
  96298. /**
  96299. * Checks wether the material is ready to be rendered for a given mesh.
  96300. * @param mesh The mesh to render
  96301. * @param subMesh The submesh to check against
  96302. * @param useInstances Specify wether or not the material is used with instances
  96303. * @returns true if all the dependencies are ready (Textures, Effects...)
  96304. */
  96305. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  96306. var _this = this;
  96307. if (useInstances === void 0) { useInstances = false; }
  96308. if (subMesh.effect && this.isFrozen) {
  96309. if (this._wasPreviouslyReady) {
  96310. return true;
  96311. }
  96312. }
  96313. if (!subMesh._materialDefines) {
  96314. subMesh._materialDefines = new BackgroundMaterialDefines();
  96315. }
  96316. var scene = this.getScene();
  96317. var defines = subMesh._materialDefines;
  96318. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  96319. if (defines._renderId === scene.getRenderId()) {
  96320. return true;
  96321. }
  96322. }
  96323. var engine = scene.getEngine();
  96324. // Lights
  96325. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  96326. defines._needNormals = true;
  96327. // Textures
  96328. if (defines._areTexturesDirty) {
  96329. defines._needUVs = false;
  96330. if (scene.texturesEnabled) {
  96331. if (scene.getEngine().getCaps().textureLOD) {
  96332. defines.TEXTURELODSUPPORT = true;
  96333. }
  96334. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96335. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  96336. return false;
  96337. }
  96338. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  96339. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  96340. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  96341. defines.OPACITYFRESNEL = this._opacityFresnel;
  96342. }
  96343. else {
  96344. defines.DIFFUSE = false;
  96345. defines.DIFFUSEHASALPHA = false;
  96346. defines.GAMMADIFFUSE = false;
  96347. defines.OPACITYFRESNEL = false;
  96348. }
  96349. var reflectionTexture = this._reflectionTexture;
  96350. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96351. if (!reflectionTexture.isReadyOrNotBlocking()) {
  96352. return false;
  96353. }
  96354. defines.REFLECTION = true;
  96355. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  96356. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  96357. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  96358. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  96359. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  96360. defines.REFLECTIONBGR = this.switchToBGR;
  96361. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  96362. defines.INVERTCUBICMAP = true;
  96363. }
  96364. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  96365. switch (reflectionTexture.coordinatesMode) {
  96366. case BABYLON.Texture.EXPLICIT_MODE:
  96367. defines.REFLECTIONMAP_EXPLICIT = true;
  96368. break;
  96369. case BABYLON.Texture.PLANAR_MODE:
  96370. defines.REFLECTIONMAP_PLANAR = true;
  96371. break;
  96372. case BABYLON.Texture.PROJECTION_MODE:
  96373. defines.REFLECTIONMAP_PROJECTION = true;
  96374. break;
  96375. case BABYLON.Texture.SKYBOX_MODE:
  96376. defines.REFLECTIONMAP_SKYBOX = true;
  96377. break;
  96378. case BABYLON.Texture.SPHERICAL_MODE:
  96379. defines.REFLECTIONMAP_SPHERICAL = true;
  96380. break;
  96381. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  96382. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  96383. break;
  96384. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  96385. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  96386. break;
  96387. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  96388. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  96389. break;
  96390. case BABYLON.Texture.CUBIC_MODE:
  96391. case BABYLON.Texture.INVCUBIC_MODE:
  96392. default:
  96393. defines.REFLECTIONMAP_CUBIC = true;
  96394. break;
  96395. }
  96396. if (this.reflectionFresnel) {
  96397. defines.REFLECTIONFRESNEL = true;
  96398. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  96399. this._reflectionControls.x = this.reflectionAmount;
  96400. this._reflectionControls.y = this.reflectionReflectance0;
  96401. this._reflectionControls.z = this.reflectionReflectance90;
  96402. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  96403. }
  96404. else {
  96405. defines.REFLECTIONFRESNEL = false;
  96406. defines.REFLECTIONFALLOFF = false;
  96407. }
  96408. }
  96409. else {
  96410. defines.REFLECTION = false;
  96411. defines.REFLECTIONFRESNEL = false;
  96412. defines.REFLECTIONFALLOFF = false;
  96413. defines.REFLECTIONBLUR = false;
  96414. defines.REFLECTIONMAP_3D = false;
  96415. defines.REFLECTIONMAP_SPHERICAL = false;
  96416. defines.REFLECTIONMAP_PLANAR = false;
  96417. defines.REFLECTIONMAP_CUBIC = false;
  96418. defines.REFLECTIONMAP_PROJECTION = false;
  96419. defines.REFLECTIONMAP_SKYBOX = false;
  96420. defines.REFLECTIONMAP_EXPLICIT = false;
  96421. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96422. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96423. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96424. defines.INVERTCUBICMAP = false;
  96425. defines.REFLECTIONMAP_OPPOSITEZ = false;
  96426. defines.LODINREFLECTIONALPHA = false;
  96427. defines.GAMMAREFLECTION = false;
  96428. }
  96429. }
  96430. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  96431. defines.USERGBCOLOR = this._useRGBColor;
  96432. defines.NOISE = this._enableNoise;
  96433. }
  96434. if (defines._areLightsDirty) {
  96435. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  96436. }
  96437. if (defines._areImageProcessingDirty) {
  96438. if (!this._imageProcessingConfiguration.isReady()) {
  96439. return false;
  96440. }
  96441. this._imageProcessingConfiguration.prepareDefines(defines);
  96442. }
  96443. // Misc.
  96444. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  96445. // Values that need to be evaluated on every frame
  96446. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  96447. // Attribs
  96448. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  96449. if (mesh) {
  96450. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  96451. mesh.createNormals(true);
  96452. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  96453. }
  96454. }
  96455. }
  96456. // Get correct effect
  96457. if (defines.isDirty) {
  96458. defines.markAsProcessed();
  96459. scene.resetCachedMaterial();
  96460. // Fallbacks
  96461. var fallbacks = new BABYLON.EffectFallbacks();
  96462. if (defines.FOG) {
  96463. fallbacks.addFallback(0, "FOG");
  96464. }
  96465. if (defines.POINTSIZE) {
  96466. fallbacks.addFallback(1, "POINTSIZE");
  96467. }
  96468. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  96469. if (defines.NUM_BONE_INFLUENCERS > 0) {
  96470. fallbacks.addCPUSkinningFallback(0, mesh);
  96471. }
  96472. //Attributes
  96473. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96474. if (defines.NORMAL) {
  96475. attribs.push(BABYLON.VertexBuffer.NormalKind);
  96476. }
  96477. if (defines.UV1) {
  96478. attribs.push(BABYLON.VertexBuffer.UVKind);
  96479. }
  96480. if (defines.UV2) {
  96481. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96482. }
  96483. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  96484. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  96485. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  96486. "vFogInfos", "vFogColor", "pointSize",
  96487. "vClipPlane", "mBones",
  96488. "vPrimaryColor", "vPrimaryColorShadow",
  96489. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  96490. "shadowLevel", "alpha",
  96491. "vBackgroundCenter", "vReflectionControl",
  96492. "vDiffuseInfos", "diffuseMatrix",
  96493. ];
  96494. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  96495. var uniformBuffers = ["Material", "Scene"];
  96496. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  96497. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  96498. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  96499. uniformsNames: uniforms,
  96500. uniformBuffersNames: uniformBuffers,
  96501. samplers: samplers,
  96502. defines: defines,
  96503. maxSimultaneousLights: this._maxSimultaneousLights
  96504. });
  96505. var onCompiled = function (effect) {
  96506. if (_this.onCompiled) {
  96507. _this.onCompiled(effect);
  96508. }
  96509. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  96510. };
  96511. var join = defines.toString();
  96512. subMesh.setEffect(scene.getEngine().createEffect("background", {
  96513. attributes: attribs,
  96514. uniformsNames: uniforms,
  96515. uniformBuffersNames: uniformBuffers,
  96516. samplers: samplers,
  96517. defines: join,
  96518. fallbacks: fallbacks,
  96519. onCompiled: onCompiled,
  96520. onError: this.onError,
  96521. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  96522. }, engine), defines);
  96523. this.buildUniformLayout();
  96524. }
  96525. if (!subMesh.effect || !subMesh.effect.isReady()) {
  96526. return false;
  96527. }
  96528. defines._renderId = scene.getRenderId();
  96529. this._wasPreviouslyReady = true;
  96530. return true;
  96531. };
  96532. /**
  96533. * Compute the primary color according to the chosen perceptual color.
  96534. */
  96535. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  96536. if (!this.__perceptualColor) {
  96537. return;
  96538. }
  96539. this._primaryColor.copyFrom(this.__perceptualColor);
  96540. // Revert gamma space.
  96541. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  96542. // Revert image processing configuration.
  96543. if (this._imageProcessingConfiguration) {
  96544. // Revert Exposure.
  96545. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  96546. }
  96547. this._computePrimaryColors();
  96548. };
  96549. /**
  96550. * Compute the highlights and shadow colors according to their chosen levels.
  96551. */
  96552. BackgroundMaterial.prototype._computePrimaryColors = function () {
  96553. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  96554. return;
  96555. }
  96556. // Find the highlight color based on the configuration.
  96557. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  96558. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  96559. // Find the shadow color based on the configuration.
  96560. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  96561. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  96562. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  96563. };
  96564. /**
  96565. * Build the uniform buffer used in the material.
  96566. */
  96567. BackgroundMaterial.prototype.buildUniformLayout = function () {
  96568. // Order is important !
  96569. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  96570. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  96571. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  96572. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  96573. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  96574. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  96575. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  96576. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  96577. this._uniformBuffer.addUniform("pointSize", 1);
  96578. this._uniformBuffer.addUniform("shadowLevel", 1);
  96579. this._uniformBuffer.addUniform("alpha", 1);
  96580. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  96581. this._uniformBuffer.addUniform("vReflectionControl", 4);
  96582. this._uniformBuffer.create();
  96583. };
  96584. /**
  96585. * Unbind the material.
  96586. */
  96587. BackgroundMaterial.prototype.unbind = function () {
  96588. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  96589. this._uniformBuffer.setTexture("diffuseSampler", null);
  96590. }
  96591. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  96592. this._uniformBuffer.setTexture("reflectionSampler", null);
  96593. }
  96594. _super.prototype.unbind.call(this);
  96595. };
  96596. /**
  96597. * Bind only the world matrix to the material.
  96598. * @param world The world matrix to bind.
  96599. */
  96600. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  96601. this._activeEffect.setMatrix("world", world);
  96602. };
  96603. /**
  96604. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  96605. * @param world The world matrix to bind.
  96606. * @param subMesh The submesh to bind for.
  96607. */
  96608. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  96609. var scene = this.getScene();
  96610. var defines = subMesh._materialDefines;
  96611. if (!defines) {
  96612. return;
  96613. }
  96614. var effect = subMesh.effect;
  96615. if (!effect) {
  96616. return;
  96617. }
  96618. this._activeEffect = effect;
  96619. // Matrices
  96620. this.bindOnlyWorldMatrix(world);
  96621. // Bones
  96622. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  96623. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  96624. if (mustRebind) {
  96625. this._uniformBuffer.bindToEffect(effect, "Material");
  96626. this.bindViewProjection(effect);
  96627. var reflectionTexture = this._reflectionTexture;
  96628. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  96629. // Texture uniforms
  96630. if (scene.texturesEnabled) {
  96631. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96632. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  96633. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  96634. }
  96635. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96636. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  96637. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  96638. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  96639. }
  96640. }
  96641. if (this.shadowLevel > 0) {
  96642. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  96643. }
  96644. this._uniformBuffer.updateFloat("alpha", this.alpha);
  96645. // Point size
  96646. if (this.pointsCloud) {
  96647. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  96648. }
  96649. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  96650. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  96651. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  96652. }
  96653. else {
  96654. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  96655. }
  96656. }
  96657. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  96658. // Textures
  96659. if (scene.texturesEnabled) {
  96660. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96661. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  96662. }
  96663. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96664. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  96665. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96666. }
  96667. else if (!defines.REFLECTIONBLUR) {
  96668. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96669. }
  96670. else {
  96671. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  96672. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  96673. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  96674. }
  96675. if (defines.REFLECTIONFRESNEL) {
  96676. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  96677. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  96678. }
  96679. }
  96680. }
  96681. // Clip plane
  96682. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  96683. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  96684. }
  96685. if (mustRebind || !this.isFrozen) {
  96686. if (scene.lightsEnabled) {
  96687. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  96688. }
  96689. // View
  96690. this.bindView(effect);
  96691. // Fog
  96692. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  96693. // image processing
  96694. this._imageProcessingConfiguration.bind(this._activeEffect);
  96695. }
  96696. this._uniformBuffer.update();
  96697. this._afterBind(mesh);
  96698. };
  96699. /**
  96700. * Dispose the material.
  96701. * @param forceDisposeEffect Force disposal of the associated effect.
  96702. * @param forceDisposeTextures Force disposal of the associated textures.
  96703. */
  96704. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  96705. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  96706. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  96707. if (forceDisposeTextures) {
  96708. if (this.diffuseTexture) {
  96709. this.diffuseTexture.dispose();
  96710. }
  96711. if (this.reflectionTexture) {
  96712. this.reflectionTexture.dispose();
  96713. }
  96714. }
  96715. this._renderTargets.dispose();
  96716. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96717. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96718. }
  96719. _super.prototype.dispose.call(this, forceDisposeEffect);
  96720. };
  96721. /**
  96722. * Clones the material.
  96723. * @param name The cloned name.
  96724. * @returns The cloned material.
  96725. */
  96726. BackgroundMaterial.prototype.clone = function (name) {
  96727. var _this = this;
  96728. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  96729. };
  96730. /**
  96731. * Serializes the current material to its JSON representation.
  96732. * @returns The JSON representation.
  96733. */
  96734. BackgroundMaterial.prototype.serialize = function () {
  96735. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96736. serializationObject.customType = "BABYLON.BackgroundMaterial";
  96737. return serializationObject;
  96738. };
  96739. /**
  96740. * Gets the class name of the material
  96741. * @returns "BackgroundMaterial"
  96742. */
  96743. BackgroundMaterial.prototype.getClassName = function () {
  96744. return "BackgroundMaterial";
  96745. };
  96746. /**
  96747. * Parse a JSON input to create back a background material.
  96748. * @param source The JSON data to parse
  96749. * @param scene The scene to create the parsed material in
  96750. * @param rootUrl The root url of the assets the material depends upon
  96751. * @returns the instantiated BackgroundMaterial.
  96752. */
  96753. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  96754. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  96755. };
  96756. /**
  96757. * Standard reflectance value at parallel view angle.
  96758. */
  96759. BackgroundMaterial.StandardReflectance0 = 0.05;
  96760. /**
  96761. * Standard reflectance value at grazing angle.
  96762. */
  96763. BackgroundMaterial.StandardReflectance90 = 0.5;
  96764. __decorate([
  96765. BABYLON.serializeAsColor3()
  96766. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  96767. __decorate([
  96768. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96769. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  96770. __decorate([
  96771. BABYLON.serializeAsColor3()
  96772. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  96773. __decorate([
  96774. BABYLON.serialize()
  96775. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  96776. __decorate([
  96777. BABYLON.serialize()
  96778. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  96779. __decorate([
  96780. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96781. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  96782. __decorate([
  96783. BABYLON.serializeAsTexture()
  96784. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  96785. __decorate([
  96786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96787. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  96788. __decorate([
  96789. BABYLON.serialize()
  96790. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  96791. __decorate([
  96792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96793. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  96794. __decorate([
  96795. BABYLON.serializeAsTexture()
  96796. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  96797. __decorate([
  96798. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96799. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  96800. __decorate([
  96801. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96802. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  96803. __decorate([
  96804. BABYLON.serialize()
  96805. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  96806. __decorate([
  96807. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96808. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  96809. __decorate([
  96810. BABYLON.serializeAsVector3()
  96811. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  96812. __decorate([
  96813. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96814. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  96815. __decorate([
  96816. BABYLON.serialize()
  96817. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  96818. __decorate([
  96819. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96820. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  96821. __decorate([
  96822. BABYLON.serialize()
  96823. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  96824. __decorate([
  96825. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96826. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  96827. __decorate([
  96828. BABYLON.serialize()
  96829. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  96830. __decorate([
  96831. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96832. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  96833. __decorate([
  96834. BABYLON.serialize()
  96835. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  96836. __decorate([
  96837. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96838. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  96839. __decorate([
  96840. BABYLON.serialize()
  96841. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  96842. __decorate([
  96843. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96844. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  96845. __decorate([
  96846. BABYLON.serialize()
  96847. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  96848. __decorate([
  96849. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96850. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  96851. __decorate([
  96852. BABYLON.serialize()
  96853. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  96854. __decorate([
  96855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96856. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  96857. __decorate([
  96858. BABYLON.serialize()
  96859. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  96860. __decorate([
  96861. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96862. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  96863. __decorate([
  96864. BABYLON.serialize()
  96865. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  96866. __decorate([
  96867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96868. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  96869. __decorate([
  96870. BABYLON.serializeAsImageProcessingConfiguration()
  96871. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  96872. return BackgroundMaterial;
  96873. }(BABYLON.PushMaterial));
  96874. BABYLON.BackgroundMaterial = BackgroundMaterial;
  96875. })(BABYLON || (BABYLON = {}));
  96876. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  96877. var __assign = (this && this.__assign) || Object.assign || function(t) {
  96878. for (var s, i = 1, n = arguments.length; i < n; i++) {
  96879. s = arguments[i];
  96880. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  96881. t[p] = s[p];
  96882. }
  96883. return t;
  96884. };
  96885. var BABYLON;
  96886. (function (BABYLON) {
  96887. /**
  96888. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  96889. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  96890. * It also helps with the default setup of your imageProcessing configuration.
  96891. */
  96892. var EnvironmentHelper = /** @class */ (function () {
  96893. /**
  96894. * constructor
  96895. * @param options
  96896. * @param scene The scene to add the material to
  96897. */
  96898. function EnvironmentHelper(options, scene) {
  96899. var _this = this;
  96900. this._errorHandler = function (message, exception) {
  96901. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  96902. };
  96903. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  96904. this._scene = scene;
  96905. this.onErrorObservable = new BABYLON.Observable();
  96906. this._setupBackground();
  96907. this._setupImageProcessing();
  96908. }
  96909. /**
  96910. * Creates the default options for the helper.
  96911. */
  96912. EnvironmentHelper._getDefaultOptions = function () {
  96913. return {
  96914. createGround: true,
  96915. groundSize: 15,
  96916. groundTexture: this._groundTextureCDNUrl,
  96917. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  96918. groundOpacity: 0.9,
  96919. enableGroundShadow: true,
  96920. groundShadowLevel: 0.5,
  96921. enableGroundMirror: false,
  96922. groundMirrorSizeRatio: 0.3,
  96923. groundMirrorBlurKernel: 64,
  96924. groundMirrorAmount: 1,
  96925. groundMirrorFresnelWeight: 1,
  96926. groundMirrorFallOffDistance: 0,
  96927. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  96928. groundYBias: 0.00001,
  96929. createSkybox: true,
  96930. skyboxSize: 20,
  96931. skyboxTexture: this._skyboxTextureCDNUrl,
  96932. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  96933. backgroundYRotation: 0,
  96934. sizeAuto: true,
  96935. rootPosition: BABYLON.Vector3.Zero(),
  96936. setupImageProcessing: true,
  96937. environmentTexture: this._environmentTextureCDNUrl,
  96938. cameraExposure: 0.8,
  96939. cameraContrast: 1.2,
  96940. toneMappingEnabled: true,
  96941. };
  96942. };
  96943. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  96944. /**
  96945. * Gets the root mesh created by the helper.
  96946. */
  96947. get: function () {
  96948. return this._rootMesh;
  96949. },
  96950. enumerable: true,
  96951. configurable: true
  96952. });
  96953. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  96954. /**
  96955. * Gets the skybox created by the helper.
  96956. */
  96957. get: function () {
  96958. return this._skybox;
  96959. },
  96960. enumerable: true,
  96961. configurable: true
  96962. });
  96963. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  96964. /**
  96965. * Gets the skybox texture created by the helper.
  96966. */
  96967. get: function () {
  96968. return this._skyboxTexture;
  96969. },
  96970. enumerable: true,
  96971. configurable: true
  96972. });
  96973. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  96974. /**
  96975. * Gets the skybox material created by the helper.
  96976. */
  96977. get: function () {
  96978. return this._skyboxMaterial;
  96979. },
  96980. enumerable: true,
  96981. configurable: true
  96982. });
  96983. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  96984. /**
  96985. * Gets the ground mesh created by the helper.
  96986. */
  96987. get: function () {
  96988. return this._ground;
  96989. },
  96990. enumerable: true,
  96991. configurable: true
  96992. });
  96993. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  96994. /**
  96995. * Gets the ground texture created by the helper.
  96996. */
  96997. get: function () {
  96998. return this._groundTexture;
  96999. },
  97000. enumerable: true,
  97001. configurable: true
  97002. });
  97003. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  97004. /**
  97005. * Gets the ground mirror created by the helper.
  97006. */
  97007. get: function () {
  97008. return this._groundMirror;
  97009. },
  97010. enumerable: true,
  97011. configurable: true
  97012. });
  97013. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  97014. /**
  97015. * Gets the ground mirror render list to helps pushing the meshes
  97016. * you wish in the ground reflection.
  97017. */
  97018. get: function () {
  97019. if (this._groundMirror) {
  97020. return this._groundMirror.renderList;
  97021. }
  97022. return null;
  97023. },
  97024. enumerable: true,
  97025. configurable: true
  97026. });
  97027. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  97028. /**
  97029. * Gets the ground material created by the helper.
  97030. */
  97031. get: function () {
  97032. return this._groundMaterial;
  97033. },
  97034. enumerable: true,
  97035. configurable: true
  97036. });
  97037. /**
  97038. * Updates the background according to the new options
  97039. * @param options
  97040. */
  97041. EnvironmentHelper.prototype.updateOptions = function (options) {
  97042. var newOptions = __assign({}, this._options, options);
  97043. if (this._ground && !newOptions.createGround) {
  97044. this._ground.dispose();
  97045. this._ground = null;
  97046. }
  97047. if (this._groundMaterial && !newOptions.createGround) {
  97048. this._groundMaterial.dispose();
  97049. this._groundMaterial = null;
  97050. }
  97051. if (this._groundTexture) {
  97052. if (this._options.groundTexture != newOptions.groundTexture) {
  97053. this._groundTexture.dispose();
  97054. this._groundTexture = null;
  97055. }
  97056. }
  97057. if (this._skybox && !newOptions.createSkybox) {
  97058. this._skybox.dispose();
  97059. this._skybox = null;
  97060. }
  97061. if (this._skyboxMaterial && !newOptions.createSkybox) {
  97062. this._skyboxMaterial.dispose();
  97063. this._skyboxMaterial = null;
  97064. }
  97065. if (this._skyboxTexture) {
  97066. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  97067. this._skyboxTexture.dispose();
  97068. this._skyboxTexture = null;
  97069. }
  97070. }
  97071. if (this._groundMirror && !newOptions.enableGroundMirror) {
  97072. this._groundMirror.dispose();
  97073. this._groundMirror = null;
  97074. }
  97075. if (this._scene.environmentTexture) {
  97076. if (this._options.environmentTexture != newOptions.environmentTexture) {
  97077. this._scene.environmentTexture.dispose();
  97078. }
  97079. }
  97080. this._options = newOptions;
  97081. this._setupBackground();
  97082. this._setupImageProcessing();
  97083. };
  97084. /**
  97085. * Sets the primary color of all the available elements.
  97086. * @param color the main color to affect to the ground and the background
  97087. */
  97088. EnvironmentHelper.prototype.setMainColor = function (color) {
  97089. if (this.groundMaterial) {
  97090. this.groundMaterial.primaryColor = color;
  97091. }
  97092. if (this.skyboxMaterial) {
  97093. this.skyboxMaterial.primaryColor = color;
  97094. }
  97095. if (this.groundMirror) {
  97096. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  97097. }
  97098. };
  97099. /**
  97100. * Setup the image processing according to the specified options.
  97101. */
  97102. EnvironmentHelper.prototype._setupImageProcessing = function () {
  97103. if (this._options.setupImageProcessing) {
  97104. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  97105. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  97106. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  97107. this._setupEnvironmentTexture();
  97108. }
  97109. };
  97110. /**
  97111. * Setup the environment texture according to the specified options.
  97112. */
  97113. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  97114. if (this._scene.environmentTexture) {
  97115. return;
  97116. }
  97117. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  97118. this._scene.environmentTexture = this._options.environmentTexture;
  97119. return;
  97120. }
  97121. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  97122. this._scene.environmentTexture = environmentTexture;
  97123. };
  97124. /**
  97125. * Setup the background according to the specified options.
  97126. */
  97127. EnvironmentHelper.prototype._setupBackground = function () {
  97128. if (!this._rootMesh) {
  97129. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  97130. }
  97131. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  97132. var sceneSize = this._getSceneSize();
  97133. if (this._options.createGround) {
  97134. this._setupGround(sceneSize);
  97135. this._setupGroundMaterial();
  97136. this._setupGroundDiffuseTexture();
  97137. if (this._options.enableGroundMirror) {
  97138. this._setupGroundMirrorTexture(sceneSize);
  97139. }
  97140. this._setupMirrorInGroundMaterial();
  97141. }
  97142. if (this._options.createSkybox) {
  97143. this._setupSkybox(sceneSize);
  97144. this._setupSkyboxMaterial();
  97145. this._setupSkyboxReflectionTexture();
  97146. }
  97147. this._rootMesh.position.x = sceneSize.rootPosition.x;
  97148. this._rootMesh.position.z = sceneSize.rootPosition.z;
  97149. this._rootMesh.position.y = sceneSize.rootPosition.y;
  97150. };
  97151. /**
  97152. * Get the scene sizes according to the setup.
  97153. */
  97154. EnvironmentHelper.prototype._getSceneSize = function () {
  97155. var _this = this;
  97156. var groundSize = this._options.groundSize;
  97157. var skyboxSize = this._options.skyboxSize;
  97158. var rootPosition = this._options.rootPosition;
  97159. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  97160. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97161. }
  97162. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  97163. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  97164. });
  97165. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97166. if (this._options.sizeAuto) {
  97167. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  97168. this._scene.activeCamera.upperRadiusLimit) {
  97169. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  97170. skyboxSize = groundSize;
  97171. }
  97172. var sceneDiagonalLenght = sceneDiagonal.length();
  97173. if (sceneDiagonalLenght > groundSize) {
  97174. groundSize = sceneDiagonalLenght * 2;
  97175. skyboxSize = groundSize;
  97176. }
  97177. // 10 % bigger.
  97178. groundSize *= 1.1;
  97179. skyboxSize *= 1.5;
  97180. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  97181. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  97182. }
  97183. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97184. };
  97185. /**
  97186. * Setup the ground according to the specified options.
  97187. */
  97188. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  97189. var _this = this;
  97190. if (!this._ground) {
  97191. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  97192. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  97193. this._ground.parent = this._rootMesh;
  97194. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  97195. }
  97196. this._ground.receiveShadows = this._options.enableGroundShadow;
  97197. };
  97198. /**
  97199. * Setup the ground material according to the specified options.
  97200. */
  97201. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  97202. if (!this._groundMaterial) {
  97203. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  97204. }
  97205. this._groundMaterial.alpha = this._options.groundOpacity;
  97206. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  97207. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  97208. this._groundMaterial.primaryColor = this._options.groundColor;
  97209. this._groundMaterial.useRGBColor = false;
  97210. this._groundMaterial.enableNoise = true;
  97211. if (this._ground) {
  97212. this._ground.material = this._groundMaterial;
  97213. }
  97214. };
  97215. /**
  97216. * Setup the ground diffuse texture according to the specified options.
  97217. */
  97218. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  97219. if (!this._groundMaterial) {
  97220. return;
  97221. }
  97222. if (this._groundTexture) {
  97223. return;
  97224. }
  97225. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  97226. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  97227. return;
  97228. }
  97229. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97230. diffuseTexture.gammaSpace = false;
  97231. diffuseTexture.hasAlpha = true;
  97232. this._groundMaterial.diffuseTexture = diffuseTexture;
  97233. };
  97234. /**
  97235. * Setup the ground mirror texture according to the specified options.
  97236. */
  97237. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  97238. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97239. if (!this._groundMirror) {
  97240. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  97241. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  97242. this._groundMirror.anisotropicFilteringLevel = 1;
  97243. this._groundMirror.wrapU = wrapping;
  97244. this._groundMirror.wrapV = wrapping;
  97245. this._groundMirror.gammaSpace = false;
  97246. if (this._groundMirror.renderList) {
  97247. for (var i = 0; i < this._scene.meshes.length; i++) {
  97248. var mesh = this._scene.meshes[i];
  97249. if (mesh !== this._ground &&
  97250. mesh !== this._skybox &&
  97251. mesh !== this._rootMesh) {
  97252. this._groundMirror.renderList.push(mesh);
  97253. }
  97254. }
  97255. }
  97256. }
  97257. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  97258. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  97259. };
  97260. /**
  97261. * Setup the ground to receive the mirror texture.
  97262. */
  97263. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  97264. if (this._groundMaterial) {
  97265. this._groundMaterial.reflectionTexture = this._groundMirror;
  97266. this._groundMaterial.reflectionFresnel = true;
  97267. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  97268. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  97269. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  97270. }
  97271. };
  97272. /**
  97273. * Setup the skybox according to the specified options.
  97274. */
  97275. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  97276. var _this = this;
  97277. if (!this._skybox) {
  97278. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  97279. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  97280. }
  97281. this._skybox.parent = this._rootMesh;
  97282. };
  97283. /**
  97284. * Setup the skybox material according to the specified options.
  97285. */
  97286. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  97287. if (!this._skybox) {
  97288. return;
  97289. }
  97290. if (!this._skyboxMaterial) {
  97291. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  97292. }
  97293. this._skyboxMaterial.useRGBColor = false;
  97294. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  97295. this._skyboxMaterial.enableNoise = true;
  97296. this._skybox.material = this._skyboxMaterial;
  97297. };
  97298. /**
  97299. * Setup the skybox reflection texture according to the specified options.
  97300. */
  97301. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  97302. if (!this._skyboxMaterial) {
  97303. return;
  97304. }
  97305. if (this._skyboxTexture) {
  97306. return;
  97307. }
  97308. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  97309. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  97310. return;
  97311. }
  97312. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97313. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  97314. this._skyboxTexture.gammaSpace = false;
  97315. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  97316. };
  97317. /**
  97318. * Dispose all the elements created by the Helper.
  97319. */
  97320. EnvironmentHelper.prototype.dispose = function () {
  97321. if (this._groundMaterial) {
  97322. this._groundMaterial.dispose(true, true);
  97323. }
  97324. if (this._skyboxMaterial) {
  97325. this._skyboxMaterial.dispose(true, true);
  97326. }
  97327. this._rootMesh.dispose(false);
  97328. };
  97329. /**
  97330. * Default ground texture URL.
  97331. */
  97332. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  97333. /**
  97334. * Default skybox texture URL.
  97335. */
  97336. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  97337. /**
  97338. * Default environment texture URL.
  97339. */
  97340. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  97341. return EnvironmentHelper;
  97342. }());
  97343. BABYLON.EnvironmentHelper = EnvironmentHelper;
  97344. })(BABYLON || (BABYLON = {}));
  97345. //# sourceMappingURL=babylon.environmentHelper.js.map
  97346. var BABYLON;
  97347. (function (BABYLON) {
  97348. /**
  97349. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  97350. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  97351. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  97352. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  97353. */
  97354. var VideoDome = /** @class */ (function (_super) {
  97355. __extends(VideoDome, _super);
  97356. /**
  97357. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  97358. * @param name Element's name, child elements will append suffixes for their own names.
  97359. * @param urlsOrVideo
  97360. * @param options An object containing optional or exposed sub element properties:
  97361. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  97362. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  97363. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  97364. * @param options **loop=true** Automatically loop video on end.
  97365. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  97366. */
  97367. function VideoDome(name, urlsOrVideo, options, scene) {
  97368. var _this = _super.call(this, name, scene) || this;
  97369. // set defaults and manage values
  97370. name = name || "videoDome";
  97371. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  97372. options.clickToPlay = Boolean(options.clickToPlay);
  97373. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  97374. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  97375. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  97376. // create
  97377. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  97378. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  97379. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  97380. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  97381. flat: false,
  97382. radius: options.size,
  97383. subdivisions: options.resolution,
  97384. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  97385. }, scene);
  97386. // configure material
  97387. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  97388. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  97389. material.reflectionTexture = _this._videoTexture;
  97390. material.useEquirectangularFOV = true;
  97391. material.fovMultiplier = 1.0;
  97392. // configure mesh
  97393. _this._mesh.material = material;
  97394. _this._mesh.parent = _this;
  97395. // optional configuration
  97396. if (options.clickToPlay) {
  97397. scene.onPointerUp = function () {
  97398. _this._videoTexture.video.play();
  97399. };
  97400. }
  97401. return _this;
  97402. }
  97403. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  97404. /**
  97405. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97406. * Also see the options.resolution property.
  97407. */
  97408. get: function () {
  97409. return this._material.fovMultiplier;
  97410. },
  97411. set: function (value) {
  97412. this._material.fovMultiplier = value;
  97413. },
  97414. enumerable: true,
  97415. configurable: true
  97416. });
  97417. /**
  97418. * Releases resources associated with this node.
  97419. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  97420. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  97421. */
  97422. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  97423. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  97424. this._videoTexture.dispose();
  97425. this._mesh.dispose();
  97426. this._material.dispose();
  97427. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  97428. };
  97429. return VideoDome;
  97430. }(BABYLON.Node));
  97431. BABYLON.VideoDome = VideoDome;
  97432. })(BABYLON || (BABYLON = {}));
  97433. //# sourceMappingURL=babylon.videoDome.js.map
  97434. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height;\nposition=vec3(randX,randY,randZ); \n\nif (angle == 0.) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(generalRandoms.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed)-vec3(0.5,0.5,0.5));\n#endif\nfloat power=emitPower.x+(emitPower.y-emitPower.x)*randoms.a;\noutPosition=(emitterWM*vec4(position,1.)).xyz;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\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}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  97435. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};