es6.js 4.3 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359
  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;
  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;
  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. var finalVertexCode;
  216. this._loadVertexShaderAsync(vertexSource)
  217. .then(function (vertexCode) {
  218. return _this._processIncludesAsync(vertexCode);
  219. })
  220. .then(function (vertexCodeWithIncludes) {
  221. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  222. return _this._loadFragmentShaderAsync(fragmentSource);
  223. })
  224. .then(function (fragmentCode) {
  225. return _this._processIncludesAsync(fragmentCode);
  226. })
  227. .then(function (fragmentCodeWithIncludes) {
  228. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  229. if (baseName) {
  230. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  231. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  232. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  233. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  234. }
  235. else {
  236. _this._vertexSourceCode = finalVertexCode;
  237. _this._fragmentSourceCode = migratedFragmentCode;
  238. }
  239. _this._prepareEffect();
  240. });
  241. }
  242. Object.defineProperty(Effect.prototype, "key", {
  243. /**
  244. * Unique key for this effect
  245. */
  246. get: function () {
  247. return this._key;
  248. },
  249. enumerable: true,
  250. configurable: true
  251. });
  252. /**
  253. * If the effect has been compiled and prepared.
  254. * @returns if the effect is compiled and prepared.
  255. */
  256. Effect.prototype.isReady = function () {
  257. return this._isReady;
  258. };
  259. /**
  260. * The engine the effect was initialized with.
  261. * @returns the engine.
  262. */
  263. Effect.prototype.getEngine = function () {
  264. return this._engine;
  265. };
  266. /**
  267. * The compiled webGL program for the effect
  268. * @returns the webGL program.
  269. */
  270. Effect.prototype.getProgram = function () {
  271. return this._program;
  272. };
  273. /**
  274. * The set of names of attribute variables for the shader.
  275. * @returns An array of attribute names.
  276. */
  277. Effect.prototype.getAttributesNames = function () {
  278. return this._attributesNames;
  279. };
  280. /**
  281. * Returns the attribute at the given index.
  282. * @param index The index of the attribute.
  283. * @returns The location of the attribute.
  284. */
  285. Effect.prototype.getAttributeLocation = function (index) {
  286. return this._attributes[index];
  287. };
  288. /**
  289. * Returns the attribute based on the name of the variable.
  290. * @param name of the attribute to look up.
  291. * @returns the attribute location.
  292. */
  293. Effect.prototype.getAttributeLocationByName = function (name) {
  294. var index = this._attributesNames.indexOf(name);
  295. return this._attributes[index];
  296. };
  297. /**
  298. * The number of attributes.
  299. * @returns the numnber of attributes.
  300. */
  301. Effect.prototype.getAttributesCount = function () {
  302. return this._attributes.length;
  303. };
  304. /**
  305. * Gets the index of a uniform variable.
  306. * @param uniformName of the uniform to look up.
  307. * @returns the index.
  308. */
  309. Effect.prototype.getUniformIndex = function (uniformName) {
  310. return this._uniformsNames.indexOf(uniformName);
  311. };
  312. /**
  313. * Returns the attribute based on the name of the variable.
  314. * @param uniformName of the uniform to look up.
  315. * @returns the location of the uniform.
  316. */
  317. Effect.prototype.getUniform = function (uniformName) {
  318. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  319. };
  320. /**
  321. * Returns an array of sampler variable names
  322. * @returns The array of sampler variable neames.
  323. */
  324. Effect.prototype.getSamplers = function () {
  325. return this._samplers;
  326. };
  327. /**
  328. * The error from the last compilation.
  329. * @returns the error string.
  330. */
  331. Effect.prototype.getCompilationError = function () {
  332. return this._compilationError;
  333. };
  334. /**
  335. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  336. * @param func The callback to be used.
  337. */
  338. Effect.prototype.executeWhenCompiled = function (func) {
  339. if (this.isReady()) {
  340. func(this);
  341. return;
  342. }
  343. this.onCompileObservable.add(function (effect) {
  344. func(effect);
  345. });
  346. };
  347. /** @ignore */
  348. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  349. if (BABYLON.Tools.IsWindowObjectExist()) {
  350. // DOM element ?
  351. if (vertex instanceof HTMLElement) {
  352. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  353. return Promise.resolve(vertexCode);
  354. }
  355. }
  356. // Base64 encoded ?
  357. if (vertex.substr(0, 7) === "base64:") {
  358. var vertexBinary = window.atob(vertex.substr(7));
  359. return Promise.resolve(vertexBinary);
  360. }
  361. // Is in local store ?
  362. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  363. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  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. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  374. };
  375. /** @ignore */
  376. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  377. if (BABYLON.Tools.IsWindowObjectExist()) {
  378. // DOM element ?
  379. if (fragment instanceof HTMLElement) {
  380. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  381. return Promise.resolve(fragmentCode);
  382. }
  383. }
  384. // Base64 encoded ?
  385. if (fragment.substr(0, 7) === "base64:") {
  386. var fragmentBinary = window.atob(fragment.substr(7));
  387. return Promise.resolve(fragmentBinary);
  388. }
  389. // Is in local store ?
  390. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  391. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  392. }
  393. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  394. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  395. }
  396. var fragmentShaderUrl;
  397. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  398. fragmentShaderUrl = fragment;
  399. }
  400. else {
  401. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  402. }
  403. // Fragment shader
  404. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  405. };
  406. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  407. // Rebuild shaders source code
  408. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  409. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  410. vertexCode = prefix + vertexCode;
  411. fragmentCode = prefix + fragmentCode;
  412. // Number lines of shaders source code
  413. var i = 2;
  414. var regex = /\n/gm;
  415. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  416. i = 2;
  417. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  418. // Dump shaders name and formatted source code
  419. if (this.name.vertexElement) {
  420. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  421. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  422. }
  423. else if (this.name.vertex) {
  424. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  425. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  426. }
  427. else {
  428. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  429. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  430. }
  431. };
  432. ;
  433. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  434. var preparedSourceCode = this._processPrecision(sourceCode);
  435. if (this._engine.webGLVersion == 1) {
  436. return preparedSourceCode;
  437. }
  438. // Already converted
  439. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  440. return preparedSourceCode.replace("#version 300 es", "");
  441. }
  442. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  443. // Remove extensions
  444. // #extension GL_OES_standard_derivatives : enable
  445. // #extension GL_EXT_shader_texture_lod : enable
  446. // #extension GL_EXT_frag_depth : enable
  447. // #extension GL_EXT_draw_buffers : require
  448. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  449. var result = preparedSourceCode.replace(regex, "");
  450. // Migrate to GLSL v300
  451. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  452. result = result.replace(/attribute[ \t]/g, "in ");
  453. result = result.replace(/[ \t]attribute/g, " in");
  454. if (isFragment) {
  455. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  456. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  457. result = result.replace(/texture2D\s*\(/g, "texture(");
  458. result = result.replace(/textureCube\s*\(/g, "texture(");
  459. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  460. result = result.replace(/gl_FragColor/g, "glFragColor");
  461. result = result.replace(/gl_FragData/g, "glFragData");
  462. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  463. }
  464. return result;
  465. };
  466. Effect.prototype._processIncludesAsync = function (sourceCode) {
  467. var _this = this;
  468. return new Promise(function (resolve, reject) {
  469. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  470. var match = regex.exec(sourceCode);
  471. var returnValue = sourceCode;
  472. while (match != null) {
  473. var includeFile = match[1];
  474. // Uniform declaration
  475. if (includeFile.indexOf("__decl__") !== -1) {
  476. includeFile = includeFile.replace(/__decl__/, "");
  477. if (_this._engine.supportsUniformBuffers) {
  478. includeFile = includeFile.replace(/Vertex/, "Ubo");
  479. includeFile = includeFile.replace(/Fragment/, "Ubo");
  480. }
  481. includeFile = includeFile + "Declaration";
  482. }
  483. if (Effect.IncludesShadersStore[includeFile]) {
  484. // Substitution
  485. var includeContent = Effect.IncludesShadersStore[includeFile];
  486. if (match[2]) {
  487. var splits = match[3].split(",");
  488. for (var index = 0; index < splits.length; index += 2) {
  489. var source = new RegExp(splits[index], "g");
  490. var dest = splits[index + 1];
  491. includeContent = includeContent.replace(source, dest);
  492. }
  493. }
  494. if (match[4]) {
  495. var indexString = match[5];
  496. if (indexString.indexOf("..") !== -1) {
  497. var indexSplits = indexString.split("..");
  498. var minIndex = parseInt(indexSplits[0]);
  499. var maxIndex = parseInt(indexSplits[1]);
  500. var sourceIncludeContent = includeContent.slice(0);
  501. includeContent = "";
  502. if (isNaN(maxIndex)) {
  503. maxIndex = _this._indexParameters[indexSplits[1]];
  504. }
  505. for (var i = minIndex; i < maxIndex; i++) {
  506. if (!_this._engine.supportsUniformBuffers) {
  507. // Ubo replacement
  508. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  509. return p1 + "{X}";
  510. });
  511. }
  512. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  513. }
  514. }
  515. else {
  516. if (!_this._engine.supportsUniformBuffers) {
  517. // Ubo replacement
  518. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  519. return p1 + "{X}";
  520. });
  521. }
  522. includeContent = includeContent.replace(/\{X\}/g, indexString);
  523. }
  524. }
  525. // Replace
  526. returnValue = returnValue.replace(match[0], includeContent);
  527. }
  528. else {
  529. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  530. _this._engine._loadFileAsync(includeShaderUrl)
  531. .then(function (fileContent) {
  532. Effect.IncludesShadersStore[includeFile] = fileContent;
  533. return _this._processIncludesAsync(returnValue);
  534. })
  535. .then(function (returnValue) {
  536. resolve(returnValue);
  537. });
  538. return;
  539. }
  540. match = regex.exec(sourceCode);
  541. }
  542. resolve(returnValue);
  543. });
  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) {
  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 {
  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 an array of textures on the engine to be used in the shader.
  714. * @param channel Name of the variable.
  715. * @param textures Textures to set.
  716. */
  717. Effect.prototype.setTextureArray = function (channel, textures) {
  718. if (this._samplers.indexOf(channel + "Ex") === -1) {
  719. var initialPos = this._samplers.indexOf(channel);
  720. for (var index = 1; index < textures.length; index++) {
  721. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  722. }
  723. }
  724. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  725. };
  726. /**
  727. * 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)
  728. * @param channel Name of the sampler variable.
  729. * @param postProcess Post process to get the input texture from.
  730. */
  731. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  732. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  733. };
  734. /** @ignore */
  735. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  736. var cache = this._valueCache[uniformName];
  737. var flag = matrix.updateFlag;
  738. if (cache !== undefined && cache === flag) {
  739. return false;
  740. }
  741. this._valueCache[uniformName] = flag;
  742. return true;
  743. };
  744. /** @ignore */
  745. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  746. var cache = this._valueCache[uniformName];
  747. if (!cache) {
  748. cache = [x, y];
  749. this._valueCache[uniformName] = cache;
  750. return true;
  751. }
  752. var changed = false;
  753. if (cache[0] !== x) {
  754. cache[0] = x;
  755. changed = true;
  756. }
  757. if (cache[1] !== y) {
  758. cache[1] = y;
  759. changed = true;
  760. }
  761. return changed;
  762. };
  763. /** @ignore */
  764. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  765. var cache = this._valueCache[uniformName];
  766. if (!cache) {
  767. cache = [x, y, z];
  768. this._valueCache[uniformName] = cache;
  769. return true;
  770. }
  771. var changed = false;
  772. if (cache[0] !== x) {
  773. cache[0] = x;
  774. changed = true;
  775. }
  776. if (cache[1] !== y) {
  777. cache[1] = y;
  778. changed = true;
  779. }
  780. if (cache[2] !== z) {
  781. cache[2] = z;
  782. changed = true;
  783. }
  784. return changed;
  785. };
  786. /** @ignore */
  787. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  788. var cache = this._valueCache[uniformName];
  789. if (!cache) {
  790. cache = [x, y, z, w];
  791. this._valueCache[uniformName] = cache;
  792. return true;
  793. }
  794. var changed = false;
  795. if (cache[0] !== x) {
  796. cache[0] = x;
  797. changed = true;
  798. }
  799. if (cache[1] !== y) {
  800. cache[1] = y;
  801. changed = true;
  802. }
  803. if (cache[2] !== z) {
  804. cache[2] = z;
  805. changed = true;
  806. }
  807. if (cache[3] !== w) {
  808. cache[3] = w;
  809. changed = true;
  810. }
  811. return changed;
  812. };
  813. /**
  814. * Binds a buffer to a uniform.
  815. * @param buffer Buffer to bind.
  816. * @param name Name of the uniform variable to bind to.
  817. */
  818. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  819. var bufferName = this._uniformBuffersNames[name];
  820. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  821. return;
  822. }
  823. Effect._baseCache[bufferName] = buffer;
  824. this._engine.bindUniformBufferBase(buffer, bufferName);
  825. };
  826. /**
  827. * Binds block to a uniform.
  828. * @param blockName Name of the block to bind.
  829. * @param index Index to bind.
  830. */
  831. Effect.prototype.bindUniformBlock = function (blockName, index) {
  832. this._engine.bindUniformBlock(this._program, blockName, index);
  833. };
  834. /**
  835. * Sets an interger value on a uniform variable.
  836. * @param uniformName Name of the variable.
  837. * @param value Value to be set.
  838. * @returns this effect.
  839. */
  840. Effect.prototype.setInt = function (uniformName, value) {
  841. var cache = this._valueCache[uniformName];
  842. if (cache !== undefined && cache === value)
  843. return this;
  844. this._valueCache[uniformName] = value;
  845. this._engine.setInt(this.getUniform(uniformName), value);
  846. return this;
  847. };
  848. /**
  849. * Sets an int array on a uniform variable.
  850. * @param uniformName Name of the variable.
  851. * @param array array to be set.
  852. * @returns this effect.
  853. */
  854. Effect.prototype.setIntArray = function (uniformName, array) {
  855. this._valueCache[uniformName] = null;
  856. this._engine.setIntArray(this.getUniform(uniformName), array);
  857. return this;
  858. };
  859. /**
  860. * 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)
  861. * @param uniformName Name of the variable.
  862. * @param array array to be set.
  863. * @returns this effect.
  864. */
  865. Effect.prototype.setIntArray2 = function (uniformName, array) {
  866. this._valueCache[uniformName] = null;
  867. this._engine.setIntArray2(this.getUniform(uniformName), array);
  868. return this;
  869. };
  870. /**
  871. * 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)
  872. * @param uniformName Name of the variable.
  873. * @param array array to be set.
  874. * @returns this effect.
  875. */
  876. Effect.prototype.setIntArray3 = function (uniformName, array) {
  877. this._valueCache[uniformName] = null;
  878. this._engine.setIntArray3(this.getUniform(uniformName), array);
  879. return this;
  880. };
  881. /**
  882. * 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)
  883. * @param uniformName Name of the variable.
  884. * @param array array to be set.
  885. * @returns this effect.
  886. */
  887. Effect.prototype.setIntArray4 = function (uniformName, array) {
  888. this._valueCache[uniformName] = null;
  889. this._engine.setIntArray4(this.getUniform(uniformName), array);
  890. return this;
  891. };
  892. /**
  893. * Sets an float array on a uniform variable.
  894. * @param uniformName Name of the variable.
  895. * @param array array to be set.
  896. * @returns this effect.
  897. */
  898. Effect.prototype.setFloatArray = function (uniformName, array) {
  899. this._valueCache[uniformName] = null;
  900. this._engine.setFloatArray(this.getUniform(uniformName), array);
  901. return this;
  902. };
  903. /**
  904. * 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)
  905. * @param uniformName Name of the variable.
  906. * @param array array to be set.
  907. * @returns this effect.
  908. */
  909. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  910. this._valueCache[uniformName] = null;
  911. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  912. return this;
  913. };
  914. /**
  915. * 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)
  916. * @param uniformName Name of the variable.
  917. * @param array array to be set.
  918. * @returns this effect.
  919. */
  920. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  921. this._valueCache[uniformName] = null;
  922. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  923. return this;
  924. };
  925. /**
  926. * 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)
  927. * @param uniformName Name of the variable.
  928. * @param array array to be set.
  929. * @returns this effect.
  930. */
  931. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  932. this._valueCache[uniformName] = null;
  933. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  934. return this;
  935. };
  936. /**
  937. * Sets an array on a uniform variable.
  938. * @param uniformName Name of the variable.
  939. * @param array array to be set.
  940. * @returns this effect.
  941. */
  942. Effect.prototype.setArray = function (uniformName, array) {
  943. this._valueCache[uniformName] = null;
  944. this._engine.setArray(this.getUniform(uniformName), array);
  945. return this;
  946. };
  947. /**
  948. * 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)
  949. * @param uniformName Name of the variable.
  950. * @param array array to be set.
  951. * @returns this effect.
  952. */
  953. Effect.prototype.setArray2 = function (uniformName, array) {
  954. this._valueCache[uniformName] = null;
  955. this._engine.setArray2(this.getUniform(uniformName), array);
  956. return this;
  957. };
  958. /**
  959. * 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)
  960. * @param uniformName Name of the variable.
  961. * @param array array to be set.
  962. * @returns this effect.
  963. */
  964. Effect.prototype.setArray3 = function (uniformName, array) {
  965. this._valueCache[uniformName] = null;
  966. this._engine.setArray3(this.getUniform(uniformName), array);
  967. return this;
  968. };
  969. /**
  970. * 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)
  971. * @param uniformName Name of the variable.
  972. * @param array array to be set.
  973. * @returns this effect.
  974. */
  975. Effect.prototype.setArray4 = function (uniformName, array) {
  976. this._valueCache[uniformName] = null;
  977. this._engine.setArray4(this.getUniform(uniformName), array);
  978. return this;
  979. };
  980. /**
  981. * Sets matrices on a uniform variable.
  982. * @param uniformName Name of the variable.
  983. * @param matrices matrices to be set.
  984. * @returns this effect.
  985. */
  986. Effect.prototype.setMatrices = function (uniformName, matrices) {
  987. if (!matrices) {
  988. return this;
  989. }
  990. this._valueCache[uniformName] = null;
  991. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  992. return this;
  993. };
  994. /**
  995. * Sets matrix on a uniform variable.
  996. * @param uniformName Name of the variable.
  997. * @param matrix matrix to be set.
  998. * @returns this effect.
  999. */
  1000. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1001. if (this._cacheMatrix(uniformName, matrix)) {
  1002. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1003. }
  1004. return this;
  1005. };
  1006. /**
  1007. * 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)
  1008. * @param uniformName Name of the variable.
  1009. * @param matrix matrix to be set.
  1010. * @returns this effect.
  1011. */
  1012. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1013. this._valueCache[uniformName] = null;
  1014. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1015. return this;
  1016. };
  1017. /**
  1018. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1019. * @param uniformName Name of the variable.
  1020. * @param matrix matrix to be set.
  1021. * @returns this effect.
  1022. */
  1023. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1024. this._valueCache[uniformName] = null;
  1025. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1026. return this;
  1027. };
  1028. /**
  1029. * Sets a float on a uniform variable.
  1030. * @param uniformName Name of the variable.
  1031. * @param value value to be set.
  1032. * @returns this effect.
  1033. */
  1034. Effect.prototype.setFloat = function (uniformName, value) {
  1035. var cache = this._valueCache[uniformName];
  1036. if (cache !== undefined && cache === value)
  1037. return this;
  1038. this._valueCache[uniformName] = value;
  1039. this._engine.setFloat(this.getUniform(uniformName), value);
  1040. return this;
  1041. };
  1042. /**
  1043. * Sets a boolean on a uniform variable.
  1044. * @param uniformName Name of the variable.
  1045. * @param bool value to be set.
  1046. * @returns this effect.
  1047. */
  1048. Effect.prototype.setBool = function (uniformName, bool) {
  1049. var cache = this._valueCache[uniformName];
  1050. if (cache !== undefined && cache === bool)
  1051. return this;
  1052. this._valueCache[uniformName] = bool;
  1053. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1054. return this;
  1055. };
  1056. /**
  1057. * Sets a Vector2 on a uniform variable.
  1058. * @param uniformName Name of the variable.
  1059. * @param vector2 vector2 to be set.
  1060. * @returns this effect.
  1061. */
  1062. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1063. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1064. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1065. }
  1066. return this;
  1067. };
  1068. /**
  1069. * Sets a float2 on a uniform variable.
  1070. * @param uniformName Name of the variable.
  1071. * @param x First float in float2.
  1072. * @param y Second float in float2.
  1073. * @returns this effect.
  1074. */
  1075. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1076. if (this._cacheFloat2(uniformName, x, y)) {
  1077. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1078. }
  1079. return this;
  1080. };
  1081. /**
  1082. * Sets a Vector3 on a uniform variable.
  1083. * @param uniformName Name of the variable.
  1084. * @param vector3 Value to be set.
  1085. * @returns this effect.
  1086. */
  1087. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1088. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1089. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1090. }
  1091. return this;
  1092. };
  1093. /**
  1094. * Sets a float3 on a uniform variable.
  1095. * @param uniformName Name of the variable.
  1096. * @param x First float in float3.
  1097. * @param y Second float in float3.
  1098. * @param z Third float in float3.
  1099. * @returns this effect.
  1100. */
  1101. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1102. if (this._cacheFloat3(uniformName, x, y, z)) {
  1103. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1104. }
  1105. return this;
  1106. };
  1107. /**
  1108. * Sets a Vector4 on a uniform variable.
  1109. * @param uniformName Name of the variable.
  1110. * @param vector4 Value to be set.
  1111. * @returns this effect.
  1112. */
  1113. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1114. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1115. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1116. }
  1117. return this;
  1118. };
  1119. /**
  1120. * Sets a float4 on a uniform variable.
  1121. * @param uniformName Name of the variable.
  1122. * @param x First float in float4.
  1123. * @param y Second float in float4.
  1124. * @param z Third float in float4.
  1125. * @param w Fourth float in float4.
  1126. * @returns this effect.
  1127. */
  1128. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1129. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1130. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1131. }
  1132. return this;
  1133. };
  1134. /**
  1135. * Sets a Color3 on a uniform variable.
  1136. * @param uniformName Name of the variable.
  1137. * @param color3 Value to be set.
  1138. * @returns this effect.
  1139. */
  1140. Effect.prototype.setColor3 = function (uniformName, color3) {
  1141. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1142. this._engine.setColor3(this.getUniform(uniformName), color3);
  1143. }
  1144. return this;
  1145. };
  1146. /**
  1147. * Sets a Color4 on a uniform variable.
  1148. * @param uniformName Name of the variable.
  1149. * @param color3 Value to be set.
  1150. * @param alpha Alpha value to be set.
  1151. * @returns this effect.
  1152. */
  1153. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1154. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1155. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1156. }
  1157. return this;
  1158. };
  1159. /**
  1160. * Sets a Color4 on a uniform variable
  1161. * @param uniformName defines the name of the variable
  1162. * @param color4 defines the value to be set
  1163. * @returns this effect.
  1164. */
  1165. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1166. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1167. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1168. }
  1169. return this;
  1170. };
  1171. /**
  1172. * Resets the cache of effects.
  1173. */
  1174. Effect.ResetCache = function () {
  1175. Effect._baseCache = {};
  1176. };
  1177. Effect._uniqueIdSeed = 0;
  1178. Effect._baseCache = {};
  1179. // Statics
  1180. /**
  1181. * Store of each shader (The can be looked up using effect.key)
  1182. */
  1183. Effect.ShadersStore = {};
  1184. /**
  1185. * Store of each included file for a shader (The can be looked up using effect.key)
  1186. */
  1187. Effect.IncludesShadersStore = {};
  1188. return Effect;
  1189. }());
  1190. BABYLON.Effect = Effect;
  1191. })(BABYLON || (BABYLON = {}));
  1192. //# sourceMappingURL=babylon.effect.js.map
  1193. //# sourceMappingURL=babylon.types.js.map
  1194. var BABYLON;
  1195. (function (BABYLON) {
  1196. var KeyboardEventTypes = /** @class */ (function () {
  1197. function KeyboardEventTypes() {
  1198. }
  1199. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1200. get: function () {
  1201. return KeyboardEventTypes._KEYDOWN;
  1202. },
  1203. enumerable: true,
  1204. configurable: true
  1205. });
  1206. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1207. get: function () {
  1208. return KeyboardEventTypes._KEYUP;
  1209. },
  1210. enumerable: true,
  1211. configurable: true
  1212. });
  1213. KeyboardEventTypes._KEYDOWN = 0x01;
  1214. KeyboardEventTypes._KEYUP = 0x02;
  1215. return KeyboardEventTypes;
  1216. }());
  1217. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1218. var KeyboardInfo = /** @class */ (function () {
  1219. function KeyboardInfo(type, event) {
  1220. this.type = type;
  1221. this.event = event;
  1222. }
  1223. return KeyboardInfo;
  1224. }());
  1225. BABYLON.KeyboardInfo = KeyboardInfo;
  1226. /**
  1227. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1228. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1229. */
  1230. var KeyboardInfoPre = /** @class */ (function (_super) {
  1231. __extends(KeyboardInfoPre, _super);
  1232. function KeyboardInfoPre(type, event) {
  1233. var _this = _super.call(this, type, event) || this;
  1234. _this.skipOnPointerObservable = false;
  1235. return _this;
  1236. }
  1237. return KeyboardInfoPre;
  1238. }(KeyboardInfo));
  1239. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1240. })(BABYLON || (BABYLON = {}));
  1241. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1242. var BABYLON;
  1243. (function (BABYLON) {
  1244. var PointerEventTypes = /** @class */ (function () {
  1245. function PointerEventTypes() {
  1246. }
  1247. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1248. get: function () {
  1249. return PointerEventTypes._POINTERDOWN;
  1250. },
  1251. enumerable: true,
  1252. configurable: true
  1253. });
  1254. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1255. get: function () {
  1256. return PointerEventTypes._POINTERUP;
  1257. },
  1258. enumerable: true,
  1259. configurable: true
  1260. });
  1261. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1262. get: function () {
  1263. return PointerEventTypes._POINTERMOVE;
  1264. },
  1265. enumerable: true,
  1266. configurable: true
  1267. });
  1268. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1269. get: function () {
  1270. return PointerEventTypes._POINTERWHEEL;
  1271. },
  1272. enumerable: true,
  1273. configurable: true
  1274. });
  1275. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1276. get: function () {
  1277. return PointerEventTypes._POINTERPICK;
  1278. },
  1279. enumerable: true,
  1280. configurable: true
  1281. });
  1282. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1283. get: function () {
  1284. return PointerEventTypes._POINTERTAP;
  1285. },
  1286. enumerable: true,
  1287. configurable: true
  1288. });
  1289. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1290. get: function () {
  1291. return PointerEventTypes._POINTERDOUBLETAP;
  1292. },
  1293. enumerable: true,
  1294. configurable: true
  1295. });
  1296. PointerEventTypes._POINTERDOWN = 0x01;
  1297. PointerEventTypes._POINTERUP = 0x02;
  1298. PointerEventTypes._POINTERMOVE = 0x04;
  1299. PointerEventTypes._POINTERWHEEL = 0x08;
  1300. PointerEventTypes._POINTERPICK = 0x10;
  1301. PointerEventTypes._POINTERTAP = 0x20;
  1302. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1303. return PointerEventTypes;
  1304. }());
  1305. BABYLON.PointerEventTypes = PointerEventTypes;
  1306. var PointerInfoBase = /** @class */ (function () {
  1307. function PointerInfoBase(type, event) {
  1308. this.type = type;
  1309. this.event = event;
  1310. }
  1311. return PointerInfoBase;
  1312. }());
  1313. BABYLON.PointerInfoBase = PointerInfoBase;
  1314. /**
  1315. * This class is used to store pointer related info for the onPrePointerObservable event.
  1316. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1317. */
  1318. var PointerInfoPre = /** @class */ (function (_super) {
  1319. __extends(PointerInfoPre, _super);
  1320. function PointerInfoPre(type, event, localX, localY) {
  1321. var _this = _super.call(this, type, event) || this;
  1322. _this.skipOnPointerObservable = false;
  1323. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1324. return _this;
  1325. }
  1326. return PointerInfoPre;
  1327. }(PointerInfoBase));
  1328. BABYLON.PointerInfoPre = PointerInfoPre;
  1329. /**
  1330. * This type contains all the data related to a pointer event in Babylon.js.
  1331. * 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.
  1332. */
  1333. var PointerInfo = /** @class */ (function (_super) {
  1334. __extends(PointerInfo, _super);
  1335. function PointerInfo(type, event, pickInfo) {
  1336. var _this = _super.call(this, type, event) || this;
  1337. _this.pickInfo = pickInfo;
  1338. return _this;
  1339. }
  1340. return PointerInfo;
  1341. }(PointerInfoBase));
  1342. BABYLON.PointerInfo = PointerInfo;
  1343. })(BABYLON || (BABYLON = {}));
  1344. //# sourceMappingURL=babylon.pointerEvents.js.map
  1345. var BABYLON;
  1346. (function (BABYLON) {
  1347. BABYLON.ToGammaSpace = 1 / 2.2;
  1348. BABYLON.ToLinearSpace = 2.2;
  1349. BABYLON.Epsilon = 0.001;
  1350. /**
  1351. * Class used to hold a RBG color
  1352. */
  1353. var Color3 = /** @class */ (function () {
  1354. /**
  1355. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1356. * @param r defines the red component (between 0 and 1, default is 0)
  1357. * @param g defines the green component (between 0 and 1, default is 0)
  1358. * @param b defines the blue component (between 0 and 1, default is 0)
  1359. */
  1360. function Color3(
  1361. /**
  1362. * Defines the red component (between 0 and 1, default is 0)
  1363. */
  1364. r,
  1365. /**
  1366. * Defines the green component (between 0 and 1, default is 0)
  1367. */
  1368. g,
  1369. /**
  1370. * Defines the blue component (between 0 and 1, default is 0)
  1371. */
  1372. b) {
  1373. if (r === void 0) { r = 0; }
  1374. if (g === void 0) { g = 0; }
  1375. if (b === void 0) { b = 0; }
  1376. this.r = r;
  1377. this.g = g;
  1378. this.b = b;
  1379. }
  1380. /**
  1381. * Creates a string with the Color3 current values
  1382. * @returns the string representation of the Color3 object
  1383. */
  1384. Color3.prototype.toString = function () {
  1385. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1386. };
  1387. /**
  1388. * Returns the string "Color3"
  1389. * @returns "Color3"
  1390. */
  1391. Color3.prototype.getClassName = function () {
  1392. return "Color3";
  1393. };
  1394. /**
  1395. * Compute the Color3 hash code
  1396. * @returns an unique number that can be used to hash Color3 objects
  1397. */
  1398. Color3.prototype.getHashCode = function () {
  1399. var hash = this.r || 0;
  1400. hash = (hash * 397) ^ (this.g || 0);
  1401. hash = (hash * 397) ^ (this.b || 0);
  1402. return hash;
  1403. };
  1404. // Operators
  1405. /**
  1406. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1407. * @param array defines the array where to store the r,g,b components
  1408. * @param index defines an optional index in the target array to define where to start storing values
  1409. * @returns the current Color3 object
  1410. */
  1411. Color3.prototype.toArray = function (array, index) {
  1412. if (index === undefined) {
  1413. index = 0;
  1414. }
  1415. array[index] = this.r;
  1416. array[index + 1] = this.g;
  1417. array[index + 2] = this.b;
  1418. return this;
  1419. };
  1420. /**
  1421. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1422. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1423. * @returns a new {BABYLON.Color4} object
  1424. */
  1425. Color3.prototype.toColor4 = function (alpha) {
  1426. if (alpha === void 0) { alpha = 1; }
  1427. return new Color4(this.r, this.g, this.b, alpha);
  1428. };
  1429. /**
  1430. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1431. * @returns the new array
  1432. */
  1433. Color3.prototype.asArray = function () {
  1434. var result = new Array();
  1435. this.toArray(result, 0);
  1436. return result;
  1437. };
  1438. /**
  1439. * Returns the luminance value
  1440. * @returns a float value
  1441. */
  1442. Color3.prototype.toLuminance = function () {
  1443. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1444. };
  1445. /**
  1446. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1447. * @param otherColor defines the second operand
  1448. * @returns the new Color3 object
  1449. */
  1450. Color3.prototype.multiply = function (otherColor) {
  1451. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1452. };
  1453. /**
  1454. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1455. * @param otherColor defines the second operand
  1456. * @param result defines the Color3 object where to store the result
  1457. * @returns the current Color3
  1458. */
  1459. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1460. result.r = this.r * otherColor.r;
  1461. result.g = this.g * otherColor.g;
  1462. result.b = this.b * otherColor.b;
  1463. return this;
  1464. };
  1465. /**
  1466. * Determines equality between Color3 objects
  1467. * @param otherColor defines the second operand
  1468. * @returns true if the rgb values are equal to the passed ones
  1469. */
  1470. Color3.prototype.equals = function (otherColor) {
  1471. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1472. };
  1473. /**
  1474. * Determines equality between the current Color3 object and a set of r,b,g values
  1475. * @param r defines the red component to check
  1476. * @param g defines the green component to check
  1477. * @param b defines the blue component to check
  1478. * @returns true if the rgb values are equal to the passed ones
  1479. */
  1480. Color3.prototype.equalsFloats = function (r, g, b) {
  1481. return this.r === r && this.g === g && this.b === b;
  1482. };
  1483. /**
  1484. * Multiplies in place each rgb value by scale
  1485. * @param scale defines the scaling factor
  1486. * @returns the updated Color3.
  1487. */
  1488. Color3.prototype.scale = function (scale) {
  1489. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1490. };
  1491. /**
  1492. * Multiplies the rgb values by scale and stores the result into "result"
  1493. * @param scale defines the scaling factor
  1494. * @param result defines the Color3 object where to store the result
  1495. * @returns the unmodified current Color3.
  1496. */
  1497. Color3.prototype.scaleToRef = function (scale, result) {
  1498. result.r = this.r * scale;
  1499. result.g = this.g * scale;
  1500. result.b = this.b * scale;
  1501. return this;
  1502. };
  1503. /**
  1504. * Clamps the rgb values by the min and max values and stores the result into "result"
  1505. * @param min defines minimum clamping value (default is 0)
  1506. * @param max defines maximum clamping value (default is 1)
  1507. * @param result defines color to store the result into
  1508. * @returns the original Color3
  1509. */
  1510. Color3.prototype.clampToRef = function (min, max, result) {
  1511. if (min === void 0) { min = 0; }
  1512. if (max === void 0) { max = 1; }
  1513. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1514. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1515. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1516. return this;
  1517. };
  1518. /**
  1519. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1520. * @param otherColor defines the second operand
  1521. * @returns the new Color3
  1522. */
  1523. Color3.prototype.add = function (otherColor) {
  1524. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1525. };
  1526. /**
  1527. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1528. * @param otherColor defines the second operand
  1529. * @param result defines Color3 object to store the result into
  1530. * @returns the unmodified current Color3
  1531. */
  1532. Color3.prototype.addToRef = function (otherColor, result) {
  1533. result.r = this.r + otherColor.r;
  1534. result.g = this.g + otherColor.g;
  1535. result.b = this.b + otherColor.b;
  1536. return this;
  1537. };
  1538. /**
  1539. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1540. * @param otherColor defines the second operand
  1541. * @returns the new Color3
  1542. */
  1543. Color3.prototype.subtract = function (otherColor) {
  1544. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1545. };
  1546. /**
  1547. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1548. * @param otherColor defines the second operand
  1549. * @param result defines Color3 object to store the result into
  1550. * @returns the unmodified current Color3
  1551. */
  1552. Color3.prototype.subtractToRef = function (otherColor, result) {
  1553. result.r = this.r - otherColor.r;
  1554. result.g = this.g - otherColor.g;
  1555. result.b = this.b - otherColor.b;
  1556. return this;
  1557. };
  1558. /**
  1559. * Copy the current object
  1560. * @returns a new Color3 copied the current one
  1561. */
  1562. Color3.prototype.clone = function () {
  1563. return new Color3(this.r, this.g, this.b);
  1564. };
  1565. /**
  1566. * Copies the rgb values from the source in the current Color3
  1567. * @param source defines the source Color3 object
  1568. * @returns the updated Color3 object
  1569. */
  1570. Color3.prototype.copyFrom = function (source) {
  1571. this.r = source.r;
  1572. this.g = source.g;
  1573. this.b = source.b;
  1574. return this;
  1575. };
  1576. /**
  1577. * Updates the Color3 rgb values from the passed floats
  1578. * @param r defines the red component to read from
  1579. * @param g defines the green component to read from
  1580. * @param b defines the blue component to read from
  1581. * @returns the current Color3 object
  1582. */
  1583. Color3.prototype.copyFromFloats = function (r, g, b) {
  1584. this.r = r;
  1585. this.g = g;
  1586. this.b = b;
  1587. return this;
  1588. };
  1589. /**
  1590. * Updates the Color3 rgb values from the passed floats
  1591. * @param r defines the red component to read from
  1592. * @param g defines the green component to read from
  1593. * @param b defines the blue component to read from
  1594. * @returns the current Color3 object
  1595. */
  1596. Color3.prototype.set = function (r, g, b) {
  1597. return this.copyFromFloats(r, g, b);
  1598. };
  1599. /**
  1600. * Compute the Color3 hexadecimal code as a string
  1601. * @returns a string containing the hexadecimal representation of the Color3 object
  1602. */
  1603. Color3.prototype.toHexString = function () {
  1604. var intR = (this.r * 255) | 0;
  1605. var intG = (this.g * 255) | 0;
  1606. var intB = (this.b * 255) | 0;
  1607. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1608. };
  1609. /**
  1610. * Computes a new Color3 converted from the current one to linear space
  1611. * @returns a new Color3 object
  1612. */
  1613. Color3.prototype.toLinearSpace = function () {
  1614. var convertedColor = new Color3();
  1615. this.toLinearSpaceToRef(convertedColor);
  1616. return convertedColor;
  1617. };
  1618. /**
  1619. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1620. * @param convertedColor defines the Color3 object where to store the linear space version
  1621. * @returns the unmodified Color3
  1622. */
  1623. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1624. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1625. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1626. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1627. return this;
  1628. };
  1629. /**
  1630. * Computes a new Color3 converted from the current one to gamma space
  1631. * @returns a new Color3 object
  1632. */
  1633. Color3.prototype.toGammaSpace = function () {
  1634. var convertedColor = new Color3();
  1635. this.toGammaSpaceToRef(convertedColor);
  1636. return convertedColor;
  1637. };
  1638. /**
  1639. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1640. * @param convertedColor defines the Color3 object where to store the gamma space version
  1641. * @returns the unmodified Color3
  1642. */
  1643. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1644. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1645. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1646. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1647. return this;
  1648. };
  1649. // Statics
  1650. /**
  1651. * Creates a new Color3 from the string containing valid hexadecimal values
  1652. * @param hex defines a string containing valid hexadecimal values
  1653. * @returns a new Color3 object
  1654. */
  1655. Color3.FromHexString = function (hex) {
  1656. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1657. return new Color3(0, 0, 0);
  1658. }
  1659. var r = parseInt(hex.substring(1, 3), 16);
  1660. var g = parseInt(hex.substring(3, 5), 16);
  1661. var b = parseInt(hex.substring(5, 7), 16);
  1662. return Color3.FromInts(r, g, b);
  1663. };
  1664. /**
  1665. * Creates a new Vector3 from the starting index of the passed array
  1666. * @param array defines the source array
  1667. * @param offset defines an offset in the source array
  1668. * @returns a new Color3 object
  1669. */
  1670. Color3.FromArray = function (array, offset) {
  1671. if (offset === void 0) { offset = 0; }
  1672. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1673. };
  1674. /**
  1675. * Creates a new Color3 from integer values (< 256)
  1676. * @param r defines the red component to read from (value between 0 and 255)
  1677. * @param g defines the green component to read from (value between 0 and 255)
  1678. * @param b defines the blue component to read from (value between 0 and 255)
  1679. * @returns a new Color3 object
  1680. */
  1681. Color3.FromInts = function (r, g, b) {
  1682. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1683. };
  1684. /**
  1685. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1686. * @param start defines the start Color3 value
  1687. * @param end defines the end Color3 value
  1688. * @param amount defines the gradient value between start and end
  1689. * @returns a new Color3 object
  1690. */
  1691. Color3.Lerp = function (start, end, amount) {
  1692. var r = start.r + ((end.r - start.r) * amount);
  1693. var g = start.g + ((end.g - start.g) * amount);
  1694. var b = start.b + ((end.b - start.b) * amount);
  1695. return new Color3(r, g, b);
  1696. };
  1697. /**
  1698. * Returns a Color3 value containing a red color
  1699. * @returns a new Color3 object
  1700. */
  1701. Color3.Red = function () { return new Color3(1, 0, 0); };
  1702. /**
  1703. * Returns a Color3 value containing a green color
  1704. * @returns a new Color3 object
  1705. */
  1706. Color3.Green = function () { return new Color3(0, 1, 0); };
  1707. /**
  1708. * Returns a Color3 value containing a blue color
  1709. * @returns a new Color3 object
  1710. */
  1711. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1712. /**
  1713. * Returns a Color3 value containing a black color
  1714. * @returns a new Color3 object
  1715. */
  1716. Color3.Black = function () { return new Color3(0, 0, 0); };
  1717. /**
  1718. * Returns a Color3 value containing a white color
  1719. * @returns a new Color3 object
  1720. */
  1721. Color3.White = function () { return new Color3(1, 1, 1); };
  1722. /**
  1723. * Returns a Color3 value containing a purple color
  1724. * @returns a new Color3 object
  1725. */
  1726. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1727. /**
  1728. * Returns a Color3 value containing a magenta color
  1729. * @returns a new Color3 object
  1730. */
  1731. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1732. /**
  1733. * Returns a Color3 value containing a yellow color
  1734. * @returns a new Color3 object
  1735. */
  1736. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1737. /**
  1738. * Returns a Color3 value containing a gray color
  1739. * @returns a new Color3 object
  1740. */
  1741. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1742. /**
  1743. * Returns a Color3 value containing a teal color
  1744. * @returns a new Color3 object
  1745. */
  1746. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1747. /**
  1748. * Returns a Color3 value containing a random color
  1749. * @returns a new Color3 object
  1750. */
  1751. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1752. return Color3;
  1753. }());
  1754. BABYLON.Color3 = Color3;
  1755. /**
  1756. * Class used to hold a RBGA color
  1757. */
  1758. var Color4 = /** @class */ (function () {
  1759. /**
  1760. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1761. * @param r defines the red component (between 0 and 1, default is 0)
  1762. * @param g defines the green component (between 0 and 1, default is 0)
  1763. * @param b defines the blue component (between 0 and 1, default is 0)
  1764. * @param a defines the alpha component (between 0 and 1, default is 1)
  1765. */
  1766. function Color4(
  1767. /**
  1768. * Defines the red component (between 0 and 1, default is 0)
  1769. */
  1770. r,
  1771. /**
  1772. * Defines the green component (between 0 and 1, default is 0)
  1773. */
  1774. g,
  1775. /**
  1776. * Defines the blue component (between 0 and 1, default is 0)
  1777. */
  1778. b,
  1779. /**
  1780. * Defines the alpha component (between 0 and 1, default is 1)
  1781. */
  1782. a) {
  1783. if (r === void 0) { r = 0; }
  1784. if (g === void 0) { g = 0; }
  1785. if (b === void 0) { b = 0; }
  1786. if (a === void 0) { a = 1; }
  1787. this.r = r;
  1788. this.g = g;
  1789. this.b = b;
  1790. this.a = a;
  1791. }
  1792. // Operators
  1793. /**
  1794. * Adds in place the passed Color4 values to the current Color4 object
  1795. * @param right defines the second operand
  1796. * @returns the current updated Color4 object
  1797. */
  1798. Color4.prototype.addInPlace = function (right) {
  1799. this.r += right.r;
  1800. this.g += right.g;
  1801. this.b += right.b;
  1802. this.a += right.a;
  1803. return this;
  1804. };
  1805. /**
  1806. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1807. * @returns the new array
  1808. */
  1809. Color4.prototype.asArray = function () {
  1810. var result = new Array();
  1811. this.toArray(result, 0);
  1812. return result;
  1813. };
  1814. /**
  1815. * Stores from the starting index in the passed array the Color4 successive values
  1816. * @param array defines the array where to store the r,g,b components
  1817. * @param index defines an optional index in the target array to define where to start storing values
  1818. * @returns the current Color4 object
  1819. */
  1820. Color4.prototype.toArray = function (array, index) {
  1821. if (index === undefined) {
  1822. index = 0;
  1823. }
  1824. array[index] = this.r;
  1825. array[index + 1] = this.g;
  1826. array[index + 2] = this.b;
  1827. array[index + 3] = this.a;
  1828. return this;
  1829. };
  1830. /**
  1831. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1832. * @param right defines the second operand
  1833. * @returns a new Color4 object
  1834. */
  1835. Color4.prototype.add = function (right) {
  1836. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1837. };
  1838. /**
  1839. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1840. * @param right defines the second operand
  1841. * @returns a new Color4 object
  1842. */
  1843. Color4.prototype.subtract = function (right) {
  1844. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1845. };
  1846. /**
  1847. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1848. * @param right defines the second operand
  1849. * @param result defines the Color4 object where to store the result
  1850. * @returns the current Color4 object
  1851. */
  1852. Color4.prototype.subtractToRef = function (right, result) {
  1853. result.r = this.r - right.r;
  1854. result.g = this.g - right.g;
  1855. result.b = this.b - right.b;
  1856. result.a = this.a - right.a;
  1857. return this;
  1858. };
  1859. /**
  1860. * Creates a new Color4 with the current Color4 values multiplied by scale
  1861. * @param scale defines the scaling factor to apply
  1862. * @returns a new Color4 object
  1863. */
  1864. Color4.prototype.scale = function (scale) {
  1865. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1866. };
  1867. /**
  1868. * Multiplies the current Color4 values by scale and stores the result in "result"
  1869. * @param scale defines the scaling factor to apply
  1870. * @param result defines the Color4 object where to store the result
  1871. * @returns the current Color4.
  1872. */
  1873. Color4.prototype.scaleToRef = function (scale, result) {
  1874. result.r = this.r * scale;
  1875. result.g = this.g * scale;
  1876. result.b = this.b * scale;
  1877. result.a = this.a * scale;
  1878. return this;
  1879. };
  1880. /**
  1881. * Clamps the rgb values by the min and max values and stores the result into "result"
  1882. * @param min defines minimum clamping value (default is 0)
  1883. * @param max defines maximum clamping value (default is 1)
  1884. * @param result defines color to store the result into.
  1885. * @returns the cuurent Color4
  1886. */
  1887. Color4.prototype.clampToRef = function (min, max, result) {
  1888. if (min === void 0) { min = 0; }
  1889. if (max === void 0) { max = 1; }
  1890. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1891. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1892. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1893. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1894. return this;
  1895. };
  1896. /**
  1897. * Multipy an Color4 value by another and return a new Color4 object
  1898. * @param color defines the Color4 value to multiply by
  1899. * @returns a new Color4 object
  1900. */
  1901. Color4.prototype.multiply = function (color) {
  1902. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1903. };
  1904. /**
  1905. * Multipy a Color4 value by another and push the result in a reference value
  1906. * @param color defines the Color4 value to multiply by
  1907. * @param result defines the Color4 to fill the result in
  1908. * @returns the result Color4
  1909. */
  1910. Color4.prototype.multiplyToRef = function (color, result) {
  1911. result.r = this.r * color.r;
  1912. result.g = this.g * color.g;
  1913. result.b = this.b * color.b;
  1914. result.a = this.a * color.a;
  1915. return result;
  1916. };
  1917. /**
  1918. * Creates a string with the Color4 current values
  1919. * @returns the string representation of the Color4 object
  1920. */
  1921. Color4.prototype.toString = function () {
  1922. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1923. };
  1924. /**
  1925. * Returns the string "Color4"
  1926. * @returns "Color4"
  1927. */
  1928. Color4.prototype.getClassName = function () {
  1929. return "Color4";
  1930. };
  1931. /**
  1932. * Compute the Color4 hash code
  1933. * @returns an unique number that can be used to hash Color4 objects
  1934. */
  1935. Color4.prototype.getHashCode = function () {
  1936. var hash = this.r || 0;
  1937. hash = (hash * 397) ^ (this.g || 0);
  1938. hash = (hash * 397) ^ (this.b || 0);
  1939. hash = (hash * 397) ^ (this.a || 0);
  1940. return hash;
  1941. };
  1942. /**
  1943. * Creates a new Color4 copied from the current one
  1944. * @returns a new Color4 object
  1945. */
  1946. Color4.prototype.clone = function () {
  1947. return new Color4(this.r, this.g, this.b, this.a);
  1948. };
  1949. /**
  1950. * Copies the passed Color4 values into the current one
  1951. * @param source defines the source Color4 object
  1952. * @returns the current updated Color4 object
  1953. */
  1954. Color4.prototype.copyFrom = function (source) {
  1955. this.r = source.r;
  1956. this.g = source.g;
  1957. this.b = source.b;
  1958. this.a = source.a;
  1959. return this;
  1960. };
  1961. /**
  1962. * Copies the passed float values into the current one
  1963. * @param r defines the red component to read from
  1964. * @param g defines the green component to read from
  1965. * @param b defines the blue component to read from
  1966. * @param a defines the alpha component to read from
  1967. * @returns the current updated Color4 object
  1968. */
  1969. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  1970. this.r = r;
  1971. this.g = g;
  1972. this.b = b;
  1973. this.a = a;
  1974. return this;
  1975. };
  1976. /**
  1977. * Copies the passed float values into the current one
  1978. * @param r defines the red component to read from
  1979. * @param g defines the green component to read from
  1980. * @param b defines the blue component to read from
  1981. * @param a defines the alpha component to read from
  1982. * @returns the current updated Color4 object
  1983. */
  1984. Color4.prototype.set = function (r, g, b, a) {
  1985. return this.copyFromFloats(r, g, b, a);
  1986. };
  1987. /**
  1988. * Compute the Color4 hexadecimal code as a string
  1989. * @returns a string containing the hexadecimal representation of the Color4 object
  1990. */
  1991. Color4.prototype.toHexString = function () {
  1992. var intR = (this.r * 255) | 0;
  1993. var intG = (this.g * 255) | 0;
  1994. var intB = (this.b * 255) | 0;
  1995. var intA = (this.a * 255) | 0;
  1996. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  1997. };
  1998. /**
  1999. * Computes a new Color4 converted from the current one to linear space
  2000. * @returns a new Color4 object
  2001. */
  2002. Color4.prototype.toLinearSpace = function () {
  2003. var convertedColor = new Color4();
  2004. this.toLinearSpaceToRef(convertedColor);
  2005. return convertedColor;
  2006. };
  2007. /**
  2008. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2009. * @param convertedColor defines the Color4 object where to store the linear space version
  2010. * @returns the unmodified Color4
  2011. */
  2012. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2013. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2014. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2015. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2016. convertedColor.a = this.a;
  2017. return this;
  2018. };
  2019. /**
  2020. * Computes a new Color4 converted from the current one to gamma space
  2021. * @returns a new Color4 object
  2022. */
  2023. Color4.prototype.toGammaSpace = function () {
  2024. var convertedColor = new Color4();
  2025. this.toGammaSpaceToRef(convertedColor);
  2026. return convertedColor;
  2027. };
  2028. /**
  2029. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2030. * @param convertedColor defines the Color4 object where to store the gamma space version
  2031. * @returns the unmodified Color4
  2032. */
  2033. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2034. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2035. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2036. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2037. convertedColor.a = this.a;
  2038. return this;
  2039. };
  2040. // Statics
  2041. /**
  2042. * Creates a new Color4 from the string containing valid hexadecimal values
  2043. * @param hex defines a string containing valid hexadecimal values
  2044. * @returns a new Color4 object
  2045. */
  2046. Color4.FromHexString = function (hex) {
  2047. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2048. return new Color4(0.0, 0.0, 0.0, 0.0);
  2049. }
  2050. var r = parseInt(hex.substring(1, 3), 16);
  2051. var g = parseInt(hex.substring(3, 5), 16);
  2052. var b = parseInt(hex.substring(5, 7), 16);
  2053. var a = parseInt(hex.substring(7, 9), 16);
  2054. return Color4.FromInts(r, g, b, a);
  2055. };
  2056. /**
  2057. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2058. * @param left defines the start value
  2059. * @param right defines the end value
  2060. * @param amount defines the gradient factor
  2061. * @returns a new Color4 object
  2062. */
  2063. Color4.Lerp = function (left, right, amount) {
  2064. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2065. Color4.LerpToRef(left, right, amount, result);
  2066. return result;
  2067. };
  2068. /**
  2069. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2070. * @param left defines the start value
  2071. * @param right defines the end value
  2072. * @param amount defines the gradient factor
  2073. * @param result defines the Color4 object where to store data
  2074. */
  2075. Color4.LerpToRef = function (left, right, amount, result) {
  2076. result.r = left.r + (right.r - left.r) * amount;
  2077. result.g = left.g + (right.g - left.g) * amount;
  2078. result.b = left.b + (right.b - left.b) * amount;
  2079. result.a = left.a + (right.a - left.a) * amount;
  2080. };
  2081. /**
  2082. * Creates a new Color4 from the starting index element of the passed array
  2083. * @param array defines the source array to read from
  2084. * @param offset defines the offset in the source array
  2085. * @returns a new Color4 object
  2086. */
  2087. Color4.FromArray = function (array, offset) {
  2088. if (offset === void 0) { offset = 0; }
  2089. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2090. };
  2091. /**
  2092. * Creates a new Color3 from integer values (< 256)
  2093. * @param r defines the red component to read from (value between 0 and 255)
  2094. * @param g defines the green component to read from (value between 0 and 255)
  2095. * @param b defines the blue component to read from (value between 0 and 255)
  2096. * @param a defines the alpha component to read from (value between 0 and 255)
  2097. * @returns a new Color3 object
  2098. */
  2099. Color4.FromInts = function (r, g, b, a) {
  2100. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2101. };
  2102. /**
  2103. * Check the content of a given array and convert it to an array containing RGBA data
  2104. * If the original array was already containing count * 4 values then it is returned directly
  2105. * @param colors defines the array to check
  2106. * @param count defines the number of RGBA data to expect
  2107. * @returns an array containing count * 4 values (RGBA)
  2108. */
  2109. Color4.CheckColors4 = function (colors, count) {
  2110. // Check if color3 was used
  2111. if (colors.length === count * 3) {
  2112. var colors4 = [];
  2113. for (var index = 0; index < colors.length; index += 3) {
  2114. var newIndex = (index / 3) * 4;
  2115. colors4[newIndex] = colors[index];
  2116. colors4[newIndex + 1] = colors[index + 1];
  2117. colors4[newIndex + 2] = colors[index + 2];
  2118. colors4[newIndex + 3] = 1.0;
  2119. }
  2120. return colors4;
  2121. }
  2122. return colors;
  2123. };
  2124. return Color4;
  2125. }());
  2126. BABYLON.Color4 = Color4;
  2127. var Vector2 = /** @class */ (function () {
  2128. /**
  2129. * Creates a new Vector2 from the passed x and y coordinates.
  2130. */
  2131. function Vector2(x, y) {
  2132. this.x = x;
  2133. this.y = y;
  2134. }
  2135. /**
  2136. * Returns a string with the Vector2 coordinates.
  2137. */
  2138. Vector2.prototype.toString = function () {
  2139. return "{X: " + this.x + " Y:" + this.y + "}";
  2140. };
  2141. /**
  2142. * Returns the string "Vector2"
  2143. */
  2144. Vector2.prototype.getClassName = function () {
  2145. return "Vector2";
  2146. };
  2147. /**
  2148. * Returns the Vector2 hash code as a number.
  2149. */
  2150. Vector2.prototype.getHashCode = function () {
  2151. var hash = this.x || 0;
  2152. hash = (hash * 397) ^ (this.y || 0);
  2153. return hash;
  2154. };
  2155. // Operators
  2156. /**
  2157. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2158. * Returns the Vector2.
  2159. */
  2160. Vector2.prototype.toArray = function (array, index) {
  2161. if (index === void 0) { index = 0; }
  2162. array[index] = this.x;
  2163. array[index + 1] = this.y;
  2164. return this;
  2165. };
  2166. /**
  2167. * Returns a new array with 2 elements : the Vector2 coordinates.
  2168. */
  2169. Vector2.prototype.asArray = function () {
  2170. var result = new Array();
  2171. this.toArray(result, 0);
  2172. return result;
  2173. };
  2174. /**
  2175. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2176. * Returns the updated Vector2.
  2177. */
  2178. Vector2.prototype.copyFrom = function (source) {
  2179. this.x = source.x;
  2180. this.y = source.y;
  2181. return this;
  2182. };
  2183. /**
  2184. * Sets the Vector2 coordinates with the passed floats.
  2185. * Returns the updated Vector2.
  2186. */
  2187. Vector2.prototype.copyFromFloats = function (x, y) {
  2188. this.x = x;
  2189. this.y = y;
  2190. return this;
  2191. };
  2192. /**
  2193. * Sets the Vector2 coordinates with the passed floats.
  2194. * Returns the updated Vector2.
  2195. */
  2196. Vector2.prototype.set = function (x, y) {
  2197. return this.copyFromFloats(x, y);
  2198. };
  2199. /**
  2200. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2201. */
  2202. Vector2.prototype.add = function (otherVector) {
  2203. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2204. };
  2205. /**
  2206. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2207. * Returns the Vector2.
  2208. */
  2209. Vector2.prototype.addToRef = function (otherVector, result) {
  2210. result.x = this.x + otherVector.x;
  2211. result.y = this.y + otherVector.y;
  2212. return this;
  2213. };
  2214. /**
  2215. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2216. * Returns the updated Vector2.
  2217. */
  2218. Vector2.prototype.addInPlace = function (otherVector) {
  2219. this.x += otherVector.x;
  2220. this.y += otherVector.y;
  2221. return this;
  2222. };
  2223. /**
  2224. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2225. */
  2226. Vector2.prototype.addVector3 = function (otherVector) {
  2227. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2228. };
  2229. /**
  2230. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2231. */
  2232. Vector2.prototype.subtract = function (otherVector) {
  2233. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2234. };
  2235. /**
  2236. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2237. * Returns the Vector2.
  2238. */
  2239. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2240. result.x = this.x - otherVector.x;
  2241. result.y = this.y - otherVector.y;
  2242. return this;
  2243. };
  2244. /**
  2245. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2246. * Returns the updated Vector2.
  2247. */
  2248. Vector2.prototype.subtractInPlace = function (otherVector) {
  2249. this.x -= otherVector.x;
  2250. this.y -= otherVector.y;
  2251. return this;
  2252. };
  2253. /**
  2254. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2255. * Returns the updated Vector2.
  2256. */
  2257. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2258. this.x *= otherVector.x;
  2259. this.y *= otherVector.y;
  2260. return this;
  2261. };
  2262. /**
  2263. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2264. */
  2265. Vector2.prototype.multiply = function (otherVector) {
  2266. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2267. };
  2268. /**
  2269. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2270. * Returns the Vector2.
  2271. */
  2272. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2273. result.x = this.x * otherVector.x;
  2274. result.y = this.y * otherVector.y;
  2275. return this;
  2276. };
  2277. /**
  2278. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2279. */
  2280. Vector2.prototype.multiplyByFloats = function (x, y) {
  2281. return new Vector2(this.x * x, this.y * y);
  2282. };
  2283. /**
  2284. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2285. */
  2286. Vector2.prototype.divide = function (otherVector) {
  2287. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2288. };
  2289. /**
  2290. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2291. * Returns the Vector2.
  2292. */
  2293. Vector2.prototype.divideToRef = function (otherVector, result) {
  2294. result.x = this.x / otherVector.x;
  2295. result.y = this.y / otherVector.y;
  2296. return this;
  2297. };
  2298. /**
  2299. * Divides the current Vector3 coordinates by the passed ones.
  2300. * Returns the updated Vector3.
  2301. */
  2302. Vector2.prototype.divideInPlace = function (otherVector) {
  2303. return this.divideToRef(otherVector, this);
  2304. };
  2305. /**
  2306. * Returns a new Vector2 with current Vector2 negated coordinates.
  2307. */
  2308. Vector2.prototype.negate = function () {
  2309. return new Vector2(-this.x, -this.y);
  2310. };
  2311. /**
  2312. * Multiply the Vector2 coordinates by scale.
  2313. * Returns the updated Vector2.
  2314. */
  2315. Vector2.prototype.scaleInPlace = function (scale) {
  2316. this.x *= scale;
  2317. this.y *= scale;
  2318. return this;
  2319. };
  2320. /**
  2321. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  2322. */
  2323. Vector2.prototype.scale = function (scale) {
  2324. return new Vector2(this.x * scale, this.y * scale);
  2325. };
  2326. /**
  2327. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2328. */
  2329. Vector2.prototype.equals = function (otherVector) {
  2330. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2331. };
  2332. /**
  2333. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2334. */
  2335. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2336. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2337. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2338. };
  2339. // Properties
  2340. /**
  2341. * Returns the vector length (float).
  2342. */
  2343. Vector2.prototype.length = function () {
  2344. return Math.sqrt(this.x * this.x + this.y * this.y);
  2345. };
  2346. /**
  2347. * Returns the vector squared length (float);
  2348. */
  2349. Vector2.prototype.lengthSquared = function () {
  2350. return (this.x * this.x + this.y * this.y);
  2351. };
  2352. // Methods
  2353. /**
  2354. * Normalize the vector.
  2355. * Returns the updated Vector2.
  2356. */
  2357. Vector2.prototype.normalize = function () {
  2358. var len = this.length();
  2359. if (len === 0)
  2360. return this;
  2361. var num = 1.0 / len;
  2362. this.x *= num;
  2363. this.y *= num;
  2364. return this;
  2365. };
  2366. /**
  2367. * Returns a new Vector2 copied from the Vector2.
  2368. */
  2369. Vector2.prototype.clone = function () {
  2370. return new Vector2(this.x, this.y);
  2371. };
  2372. // Statics
  2373. /**
  2374. * Returns a new Vector2(0, 0)
  2375. */
  2376. Vector2.Zero = function () {
  2377. return new Vector2(0, 0);
  2378. };
  2379. /**
  2380. * Returns a new Vector2(1, 1)
  2381. */
  2382. Vector2.One = function () {
  2383. return new Vector2(1, 1);
  2384. };
  2385. /**
  2386. * Returns a new Vector2 set from the passed index element of the passed array.
  2387. */
  2388. Vector2.FromArray = function (array, offset) {
  2389. if (offset === void 0) { offset = 0; }
  2390. return new Vector2(array[offset], array[offset + 1]);
  2391. };
  2392. /**
  2393. * Sets "result" from the passed index element of the passed array.
  2394. */
  2395. Vector2.FromArrayToRef = function (array, offset, result) {
  2396. result.x = array[offset];
  2397. result.y = array[offset + 1];
  2398. };
  2399. /**
  2400. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2401. */
  2402. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2403. var squared = amount * amount;
  2404. var cubed = amount * squared;
  2405. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2406. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2407. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2408. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2409. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2410. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2411. return new Vector2(x, y);
  2412. };
  2413. /**
  2414. * 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".
  2415. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2416. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2417. */
  2418. Vector2.Clamp = function (value, min, max) {
  2419. var x = value.x;
  2420. x = (x > max.x) ? max.x : x;
  2421. x = (x < min.x) ? min.x : x;
  2422. var y = value.y;
  2423. y = (y > max.y) ? max.y : y;
  2424. y = (y < min.y) ? min.y : y;
  2425. return new Vector2(x, y);
  2426. };
  2427. /**
  2428. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2429. */
  2430. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2431. var squared = amount * amount;
  2432. var cubed = amount * squared;
  2433. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2434. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2435. var part3 = (cubed - (2.0 * squared)) + amount;
  2436. var part4 = cubed - squared;
  2437. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2438. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2439. return new Vector2(x, y);
  2440. };
  2441. /**
  2442. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2443. */
  2444. Vector2.Lerp = function (start, end, amount) {
  2445. var x = start.x + ((end.x - start.x) * amount);
  2446. var y = start.y + ((end.y - start.y) * amount);
  2447. return new Vector2(x, y);
  2448. };
  2449. /**
  2450. * Returns the dot product (float) of the vector "left" and the vector "right".
  2451. */
  2452. Vector2.Dot = function (left, right) {
  2453. return left.x * right.x + left.y * right.y;
  2454. };
  2455. /**
  2456. * Returns a new Vector2 equal to the normalized passed vector.
  2457. */
  2458. Vector2.Normalize = function (vector) {
  2459. var newVector = vector.clone();
  2460. newVector.normalize();
  2461. return newVector;
  2462. };
  2463. /**
  2464. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2465. */
  2466. Vector2.Minimize = function (left, right) {
  2467. var x = (left.x < right.x) ? left.x : right.x;
  2468. var y = (left.y < right.y) ? left.y : right.y;
  2469. return new Vector2(x, y);
  2470. };
  2471. /**
  2472. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2473. */
  2474. Vector2.Maximize = function (left, right) {
  2475. var x = (left.x > right.x) ? left.x : right.x;
  2476. var y = (left.y > right.y) ? left.y : right.y;
  2477. return new Vector2(x, y);
  2478. };
  2479. /**
  2480. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2481. */
  2482. Vector2.Transform = function (vector, transformation) {
  2483. var r = Vector2.Zero();
  2484. Vector2.TransformToRef(vector, transformation, r);
  2485. return r;
  2486. };
  2487. /**
  2488. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2489. */
  2490. Vector2.TransformToRef = function (vector, transformation, result) {
  2491. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2492. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2493. result.x = x;
  2494. result.y = y;
  2495. };
  2496. /**
  2497. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2498. */
  2499. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2500. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2501. var sign = a < 0 ? -1 : 1;
  2502. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2503. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2504. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2505. };
  2506. /**
  2507. * Returns the distance (float) between the vectors "value1" and "value2".
  2508. */
  2509. Vector2.Distance = function (value1, value2) {
  2510. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2511. };
  2512. /**
  2513. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2514. */
  2515. Vector2.DistanceSquared = function (value1, value2) {
  2516. var x = value1.x - value2.x;
  2517. var y = value1.y - value2.y;
  2518. return (x * x) + (y * y);
  2519. };
  2520. /**
  2521. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2522. */
  2523. Vector2.Center = function (value1, value2) {
  2524. var center = value1.add(value2);
  2525. center.scaleInPlace(0.5);
  2526. return center;
  2527. };
  2528. /**
  2529. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2530. */
  2531. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2532. var l2 = Vector2.DistanceSquared(segA, segB);
  2533. if (l2 === 0.0) {
  2534. return Vector2.Distance(p, segA);
  2535. }
  2536. var v = segB.subtract(segA);
  2537. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2538. var proj = segA.add(v.multiplyByFloats(t, t));
  2539. return Vector2.Distance(p, proj);
  2540. };
  2541. return Vector2;
  2542. }());
  2543. BABYLON.Vector2 = Vector2;
  2544. /**
  2545. * Classed used to store (x,y,z) vector representation
  2546. * A Vector3 is the main object used in 3D geometry
  2547. * It can represent etiher the coordinates of a point the space, either a direction
  2548. * Reminder: Babylon.js uses a left handed forward facing system
  2549. */
  2550. var Vector3 = /** @class */ (function () {
  2551. /**
  2552. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2553. * @param x defines the first coordinates (on X axis)
  2554. * @param y defines the second coordinates (on Y axis)
  2555. * @param z defines the third coordinates (on Z axis)
  2556. */
  2557. function Vector3(
  2558. /**
  2559. * Defines the first coordinates (on X axis)
  2560. */
  2561. x,
  2562. /**
  2563. * Defines the second coordinates (on Y axis)
  2564. */
  2565. y,
  2566. /**
  2567. * Defines the third coordinates (on Z axis)
  2568. */
  2569. z) {
  2570. this.x = x;
  2571. this.y = y;
  2572. this.z = z;
  2573. }
  2574. /**
  2575. * Creates a string representation of the Vector3
  2576. * @returns a string with the Vector3 coordinates.
  2577. */
  2578. Vector3.prototype.toString = function () {
  2579. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2580. };
  2581. /**
  2582. * Gets the class name
  2583. * @returns the string "Vector3"
  2584. */
  2585. Vector3.prototype.getClassName = function () {
  2586. return "Vector3";
  2587. };
  2588. /**
  2589. * Creates the Vector3 hash code
  2590. * @returns a number which tends to be unique between Vector3 instances
  2591. */
  2592. Vector3.prototype.getHashCode = function () {
  2593. var hash = this.x || 0;
  2594. hash = (hash * 397) ^ (this.y || 0);
  2595. hash = (hash * 397) ^ (this.z || 0);
  2596. return hash;
  2597. };
  2598. // Operators
  2599. /**
  2600. * Creates an array containing three elements : the coordinates of the Vector3
  2601. * @returns a new array of numbers
  2602. */
  2603. Vector3.prototype.asArray = function () {
  2604. var result = [];
  2605. this.toArray(result, 0);
  2606. return result;
  2607. };
  2608. /**
  2609. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2610. * @param array defines the destination array
  2611. * @param index defines the offset in the destination array
  2612. * @returns the current Vector3
  2613. */
  2614. Vector3.prototype.toArray = function (array, index) {
  2615. if (index === void 0) { index = 0; }
  2616. array[index] = this.x;
  2617. array[index + 1] = this.y;
  2618. array[index + 2] = this.z;
  2619. return this;
  2620. };
  2621. /**
  2622. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2623. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2624. */
  2625. Vector3.prototype.toQuaternion = function () {
  2626. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2627. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2628. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2629. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2630. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2631. var cosy = Math.cos(this.y * 0.5);
  2632. var siny = Math.sin(this.y * 0.5);
  2633. result.x = coszMinusx * siny;
  2634. result.y = -sinzMinusx * siny;
  2635. result.z = sinxPlusz * cosy;
  2636. result.w = cosxPlusz * cosy;
  2637. return result;
  2638. };
  2639. /**
  2640. * Adds the passed vector to the current Vector3
  2641. * @param otherVector defines the second operand
  2642. * @returns the current updated Vector3
  2643. */
  2644. Vector3.prototype.addInPlace = function (otherVector) {
  2645. this.x += otherVector.x;
  2646. this.y += otherVector.y;
  2647. this.z += otherVector.z;
  2648. return this;
  2649. };
  2650. /**
  2651. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2652. * @param otherVector defines the second operand
  2653. * @returns the resulting Vector3
  2654. */
  2655. Vector3.prototype.add = function (otherVector) {
  2656. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2657. };
  2658. /**
  2659. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2660. * @param otherVector defines the second operand
  2661. * @param result defines the Vector3 object where to store the result
  2662. * @returns the current Vector3
  2663. */
  2664. Vector3.prototype.addToRef = function (otherVector, result) {
  2665. result.x = this.x + otherVector.x;
  2666. result.y = this.y + otherVector.y;
  2667. result.z = this.z + otherVector.z;
  2668. return this;
  2669. };
  2670. /**
  2671. * Subtract the passed vector from the current Vector3
  2672. * @param otherVector defines the second operand
  2673. * @returns the current updated Vector3
  2674. */
  2675. Vector3.prototype.subtractInPlace = function (otherVector) {
  2676. this.x -= otherVector.x;
  2677. this.y -= otherVector.y;
  2678. this.z -= otherVector.z;
  2679. return this;
  2680. };
  2681. /**
  2682. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2683. * @param otherVector defines the second operand
  2684. * @returns the resulting Vector3
  2685. */
  2686. Vector3.prototype.subtract = function (otherVector) {
  2687. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2688. };
  2689. /**
  2690. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2691. * @param otherVector defines the second operand
  2692. * @param result defines the Vector3 object where to store the result
  2693. * @returns the current Vector3
  2694. */
  2695. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2696. result.x = this.x - otherVector.x;
  2697. result.y = this.y - otherVector.y;
  2698. result.z = this.z - otherVector.z;
  2699. return this;
  2700. };
  2701. /**
  2702. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2703. * @param x defines the x coordinate of the operand
  2704. * @param y defines the y coordinate of the operand
  2705. * @param z defines the z coordinate of the operand
  2706. * @returns the resulting Vector3
  2707. */
  2708. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2709. return new Vector3(this.x - x, this.y - y, this.z - z);
  2710. };
  2711. /**
  2712. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2713. * @param x defines the x coordinate of the operand
  2714. * @param y defines the y coordinate of the operand
  2715. * @param z defines the z coordinate of the operand
  2716. * @param result defines the Vector3 object where to store the result
  2717. * @returns the current Vector3
  2718. */
  2719. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2720. result.x = this.x - x;
  2721. result.y = this.y - y;
  2722. result.z = this.z - z;
  2723. return this;
  2724. };
  2725. /**
  2726. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2727. * @returns a new Vector3
  2728. */
  2729. Vector3.prototype.negate = function () {
  2730. return new Vector3(-this.x, -this.y, -this.z);
  2731. };
  2732. /**
  2733. * Multiplies the Vector3 coordinates by the float "scale"
  2734. * @param scale defines the multiplier factor
  2735. * @returns the current updated Vector3
  2736. */
  2737. Vector3.prototype.scaleInPlace = function (scale) {
  2738. this.x *= scale;
  2739. this.y *= scale;
  2740. this.z *= scale;
  2741. return this;
  2742. };
  2743. /**
  2744. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2745. * @param scale defines the multiplier factor
  2746. * @returns a new Vector3
  2747. */
  2748. Vector3.prototype.scale = function (scale) {
  2749. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2750. };
  2751. /**
  2752. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2753. * @param scale defines the multiplier factor
  2754. * @param result defines the Vector3 object where to store the result
  2755. * @returns the current Vector3
  2756. */
  2757. Vector3.prototype.scaleToRef = function (scale, result) {
  2758. result.x = this.x * scale;
  2759. result.y = this.y * scale;
  2760. result.z = this.z * scale;
  2761. return this;
  2762. };
  2763. /**
  2764. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2765. * @param otherVector defines the second operand
  2766. * @returns true if both vectors are equals
  2767. */
  2768. Vector3.prototype.equals = function (otherVector) {
  2769. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2770. };
  2771. /**
  2772. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2773. * @param otherVector defines the second operand
  2774. * @param epsilon defines the minimal distance to define values as equals
  2775. * @returns true if both vectors are distant less than epsilon
  2776. */
  2777. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2778. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2779. 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);
  2780. };
  2781. /**
  2782. * Returns true if the current Vector3 coordinates equals the passed floats
  2783. * @param x defines the x coordinate of the operand
  2784. * @param y defines the y coordinate of the operand
  2785. * @param z defines the z coordinate of the operand
  2786. * @returns true if both vectors are equals
  2787. */
  2788. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2789. return this.x === x && this.y === y && this.z === z;
  2790. };
  2791. /**
  2792. * Multiplies the current Vector3 coordinates by the passed ones
  2793. * @param otherVector defines the second operand
  2794. * @returns the current updated Vector3
  2795. */
  2796. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2797. this.x *= otherVector.x;
  2798. this.y *= otherVector.y;
  2799. this.z *= otherVector.z;
  2800. return this;
  2801. };
  2802. /**
  2803. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2804. * @param otherVector defines the second operand
  2805. * @returns the new Vector3
  2806. */
  2807. Vector3.prototype.multiply = function (otherVector) {
  2808. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2809. };
  2810. /**
  2811. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2812. * @param otherVector defines the second operand
  2813. * @param result defines the Vector3 object where to store the result
  2814. * @returns the current Vector3
  2815. */
  2816. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2817. result.x = this.x * otherVector.x;
  2818. result.y = this.y * otherVector.y;
  2819. result.z = this.z * otherVector.z;
  2820. return this;
  2821. };
  2822. /**
  2823. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2824. * @param x defines the x coordinate of the operand
  2825. * @param y defines the y coordinate of the operand
  2826. * @param z defines the z coordinate of the operand
  2827. * @returns the new Vector3
  2828. */
  2829. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2830. return new Vector3(this.x * x, this.y * y, this.z * z);
  2831. };
  2832. /**
  2833. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2834. * @param otherVector defines the second operand
  2835. * @returns the new Vector3
  2836. */
  2837. Vector3.prototype.divide = function (otherVector) {
  2838. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2839. };
  2840. /**
  2841. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2842. * @param otherVector defines the second operand
  2843. * @param result defines the Vector3 object where to store the result
  2844. * @returns the current Vector3
  2845. */
  2846. Vector3.prototype.divideToRef = function (otherVector, result) {
  2847. result.x = this.x / otherVector.x;
  2848. result.y = this.y / otherVector.y;
  2849. result.z = this.z / otherVector.z;
  2850. return this;
  2851. };
  2852. /**
  2853. * Divides the current Vector3 coordinates by the passed ones.
  2854. * @param otherVector defines the second operand
  2855. * @returns the current updated Vector3
  2856. */
  2857. Vector3.prototype.divideInPlace = function (otherVector) {
  2858. return this.divideToRef(otherVector, this);
  2859. };
  2860. /**
  2861. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  2862. * @param other defines the second operand
  2863. * @returns the current updated Vector3
  2864. */
  2865. Vector3.prototype.minimizeInPlace = function (other) {
  2866. if (other.x < this.x)
  2867. this.x = other.x;
  2868. if (other.y < this.y)
  2869. this.y = other.y;
  2870. if (other.z < this.z)
  2871. this.z = other.z;
  2872. return this;
  2873. };
  2874. /**
  2875. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  2876. * @param other defines the second operand
  2877. * @returns the current updated Vector3
  2878. */
  2879. Vector3.prototype.maximizeInPlace = function (other) {
  2880. if (other.x > this.x)
  2881. this.x = other.x;
  2882. if (other.y > this.y)
  2883. this.y = other.y;
  2884. if (other.z > this.z)
  2885. this.z = other.z;
  2886. return this;
  2887. };
  2888. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  2889. /**
  2890. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  2891. */
  2892. get: function () {
  2893. var absX = Math.abs(this.x);
  2894. var absY = Math.abs(this.y);
  2895. if (absX !== absY) {
  2896. return true;
  2897. }
  2898. var absZ = Math.abs(this.z);
  2899. if (absX !== absZ) {
  2900. return true;
  2901. }
  2902. if (absY !== absZ) {
  2903. return true;
  2904. }
  2905. return false;
  2906. },
  2907. enumerable: true,
  2908. configurable: true
  2909. });
  2910. // Properties
  2911. /**
  2912. * Gets the length of the Vector3
  2913. * @returns the length of the Vecto3
  2914. */
  2915. Vector3.prototype.length = function () {
  2916. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  2917. };
  2918. /**
  2919. * Gets the squared length of the Vector3
  2920. * @returns squared length of the Vector3
  2921. */
  2922. Vector3.prototype.lengthSquared = function () {
  2923. return (this.x * this.x + this.y * this.y + this.z * this.z);
  2924. };
  2925. /**
  2926. * Normalize the current Vector3.
  2927. * Please note that this is an in place operation.
  2928. * @returns the current updated Vector3
  2929. */
  2930. Vector3.prototype.normalize = function () {
  2931. var len = this.length();
  2932. if (len === 0 || len === 1.0)
  2933. return this;
  2934. var num = 1.0 / len;
  2935. this.x *= num;
  2936. this.y *= num;
  2937. this.z *= num;
  2938. return this;
  2939. };
  2940. /**
  2941. * Normalize the current Vector3 to a new vector
  2942. * @returns the new Vector3
  2943. */
  2944. Vector3.prototype.normalizeToNew = function () {
  2945. var normalized = new Vector3(0, 0, 0);
  2946. this.normalizeToRef(normalized);
  2947. return normalized;
  2948. };
  2949. /**
  2950. * Normalize the current Vector3 to the reference
  2951. * @param reference define the Vector3 to update
  2952. * @returns the updated Vector3
  2953. */
  2954. Vector3.prototype.normalizeToRef = function (reference) {
  2955. var len = this.length();
  2956. if (len === 0 || len === 1.0) {
  2957. reference.set(this.x, this.y, this.z);
  2958. return reference;
  2959. }
  2960. var scale = 1.0 / len;
  2961. this.scaleToRef(scale, reference);
  2962. return reference;
  2963. };
  2964. /**
  2965. * Creates a new Vector3 copied from the current Vector3
  2966. * @returns the new Vector3
  2967. */
  2968. Vector3.prototype.clone = function () {
  2969. return new Vector3(this.x, this.y, this.z);
  2970. };
  2971. /**
  2972. * Copies the passed vector coordinates to the current Vector3 ones
  2973. * @param source defines the source Vector3
  2974. * @returns the current updated Vector3
  2975. */
  2976. Vector3.prototype.copyFrom = function (source) {
  2977. this.x = source.x;
  2978. this.y = source.y;
  2979. this.z = source.z;
  2980. return this;
  2981. };
  2982. /**
  2983. * Copies the passed floats to the current Vector3 coordinates
  2984. * @param x defines the x coordinate of the operand
  2985. * @param y defines the y coordinate of the operand
  2986. * @param z defines the z coordinate of the operand
  2987. * @returns the current updated Vector3
  2988. */
  2989. Vector3.prototype.copyFromFloats = function (x, y, z) {
  2990. this.x = x;
  2991. this.y = y;
  2992. this.z = z;
  2993. return this;
  2994. };
  2995. /**
  2996. * Copies the passed floats to the current Vector3 coordinates
  2997. * @param x defines the x coordinate of the operand
  2998. * @param y defines the y coordinate of the operand
  2999. * @param z defines the z coordinate of the operand
  3000. * @returns the current updated Vector3
  3001. */
  3002. Vector3.prototype.set = function (x, y, z) {
  3003. return this.copyFromFloats(x, y, z);
  3004. };
  3005. // Statics
  3006. /**
  3007. * Get the clip factor between two vectors
  3008. * @param vector0 defines the first operand
  3009. * @param vector1 defines the second operand
  3010. * @param axis defines the axis to use
  3011. * @param size defines the size along the axis
  3012. * @returns the clip factor
  3013. */
  3014. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3015. var d0 = Vector3.Dot(vector0, axis) - size;
  3016. var d1 = Vector3.Dot(vector1, axis) - size;
  3017. var s = d0 / (d0 - d1);
  3018. return s;
  3019. };
  3020. /**
  3021. * Get angle between two vectors
  3022. * @param vector0 angle between vector0 and vector1
  3023. * @param vector1 angle between vector0 and vector1
  3024. * @param normal direction of the normal
  3025. * @return the angle between vector0 and vector1
  3026. */
  3027. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3028. var v0 = vector0.clone().normalize();
  3029. var v1 = vector1.clone().normalize();
  3030. var dot = Vector3.Dot(v0, v1);
  3031. var n = Vector3.Cross(v0, v1);
  3032. if (Vector3.Dot(n, normal) > 0) {
  3033. return Math.acos(dot);
  3034. }
  3035. return -Math.acos(dot);
  3036. };
  3037. /**
  3038. * Returns a new Vector3 set from the index "offset" of the passed array
  3039. * @param array defines the source array
  3040. * @param offset defines the offset in the source array
  3041. * @returns the new Vector3
  3042. */
  3043. Vector3.FromArray = function (array, offset) {
  3044. if (!offset) {
  3045. offset = 0;
  3046. }
  3047. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3048. };
  3049. /**
  3050. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3051. * This function is deprecated. Use FromArray instead
  3052. * @param array defines the source array
  3053. * @param offset defines the offset in the source array
  3054. * @returns the new Vector3
  3055. */
  3056. Vector3.FromFloatArray = function (array, offset) {
  3057. return Vector3.FromArray(array, offset);
  3058. };
  3059. /**
  3060. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3061. * @param array defines the source array
  3062. * @param offset defines the offset in the source array
  3063. * @param result defines the Vector3 where to store the result
  3064. */
  3065. Vector3.FromArrayToRef = function (array, offset, result) {
  3066. result.x = array[offset];
  3067. result.y = array[offset + 1];
  3068. result.z = array[offset + 2];
  3069. };
  3070. /**
  3071. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3072. * This function is deprecated. Use FromArrayToRef instead.
  3073. * @param array defines the source array
  3074. * @param offset defines the offset in the source array
  3075. * @param result defines the Vector3 where to store the result
  3076. */
  3077. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3078. return Vector3.FromArrayToRef(array, offset, result);
  3079. };
  3080. /**
  3081. * Sets the passed vector "result" with the passed floats.
  3082. * @param x defines the x coordinate of the source
  3083. * @param y defines the y coordinate of the source
  3084. * @param z defines the z coordinate of the source
  3085. * @param result defines the Vector3 where to store the result
  3086. */
  3087. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3088. result.x = x;
  3089. result.y = y;
  3090. result.z = z;
  3091. };
  3092. /**
  3093. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3094. * @returns a new empty Vector3
  3095. */
  3096. Vector3.Zero = function () {
  3097. return new Vector3(0.0, 0.0, 0.0);
  3098. };
  3099. /**
  3100. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3101. * @returns a new unit Vector3
  3102. */
  3103. Vector3.One = function () {
  3104. return new Vector3(1.0, 1.0, 1.0);
  3105. };
  3106. /**
  3107. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3108. * @returns a new up Vector3
  3109. */
  3110. Vector3.Up = function () {
  3111. return new Vector3(0.0, 1.0, 0.0);
  3112. };
  3113. /**
  3114. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3115. * @returns a new forward Vector3
  3116. */
  3117. Vector3.Forward = function () {
  3118. return new Vector3(0.0, 0.0, 1.0);
  3119. };
  3120. /**
  3121. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3122. * @returns a new right Vector3
  3123. */
  3124. Vector3.Right = function () {
  3125. return new Vector3(1.0, 0.0, 0.0);
  3126. };
  3127. /**
  3128. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3129. * @returns a new left Vector3
  3130. */
  3131. Vector3.Left = function () {
  3132. return new Vector3(-1.0, 0.0, 0.0);
  3133. };
  3134. /**
  3135. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3136. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3137. * @param vector defines the Vector3 to transform
  3138. * @param transformation defines the transformation matrix
  3139. * @returns the transformed Vector3
  3140. */
  3141. Vector3.TransformCoordinates = function (vector, transformation) {
  3142. var result = Vector3.Zero();
  3143. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3144. return result;
  3145. };
  3146. /**
  3147. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3148. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3149. * @param vector defines the Vector3 to transform
  3150. * @param transformation defines the transformation matrix
  3151. * @param result defines the Vector3 where to store the result
  3152. */
  3153. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3154. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3155. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3156. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3157. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3158. result.x = x / w;
  3159. result.y = y / w;
  3160. result.z = z / w;
  3161. };
  3162. /**
  3163. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3164. * This method computes tranformed coordinates only, not transformed direction vectors
  3165. * @param x define the x coordinate of the source vector
  3166. * @param y define the y coordinate of the source vector
  3167. * @param z define the z coordinate of the source vector
  3168. * @param transformation defines the transformation matrix
  3169. * @param result defines the Vector3 where to store the result
  3170. */
  3171. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3172. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3173. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3174. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3175. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3176. result.x = rx / rw;
  3177. result.y = ry / rw;
  3178. result.z = rz / rw;
  3179. };
  3180. /**
  3181. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3182. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3183. * @param vector defines the Vector3 to transform
  3184. * @param transformation defines the transformation matrix
  3185. * @returns the new Vector3
  3186. */
  3187. Vector3.TransformNormal = function (vector, transformation) {
  3188. var result = Vector3.Zero();
  3189. Vector3.TransformNormalToRef(vector, transformation, result);
  3190. return result;
  3191. };
  3192. /**
  3193. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3194. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3195. * @param vector defines the Vector3 to transform
  3196. * @param transformation defines the transformation matrix
  3197. * @param result defines the Vector3 where to store the result
  3198. */
  3199. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3200. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3201. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3202. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3203. result.x = x;
  3204. result.y = y;
  3205. result.z = z;
  3206. };
  3207. /**
  3208. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3209. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3210. * @param x define the x coordinate of the source vector
  3211. * @param y define the y coordinate of the source vector
  3212. * @param z define the z coordinate of the source vector
  3213. * @param transformation defines the transformation matrix
  3214. * @param result defines the Vector3 where to store the result
  3215. */
  3216. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3217. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3218. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3219. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3220. };
  3221. /**
  3222. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3223. * @param value1 defines the first control point
  3224. * @param value2 defines the second control point
  3225. * @param value3 defines the third control point
  3226. * @param value4 defines the fourth control point
  3227. * @param amount defines the amount on the spline to use
  3228. * @returns the new Vector3
  3229. */
  3230. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3231. var squared = amount * amount;
  3232. var cubed = amount * squared;
  3233. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3234. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3235. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3236. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3237. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3238. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3239. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3240. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3241. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3242. return new Vector3(x, y, z);
  3243. };
  3244. /**
  3245. * 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"
  3246. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3247. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3248. * @param value defines the current value
  3249. * @param min defines the lower range value
  3250. * @param max defines the upper range value
  3251. * @returns the new Vector3
  3252. */
  3253. Vector3.Clamp = function (value, min, max) {
  3254. var x = value.x;
  3255. x = (x > max.x) ? max.x : x;
  3256. x = (x < min.x) ? min.x : x;
  3257. var y = value.y;
  3258. y = (y > max.y) ? max.y : y;
  3259. y = (y < min.y) ? min.y : y;
  3260. var z = value.z;
  3261. z = (z > max.z) ? max.z : z;
  3262. z = (z < min.z) ? min.z : z;
  3263. return new Vector3(x, y, z);
  3264. };
  3265. /**
  3266. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3267. * @param value1 defines the first control point
  3268. * @param tangent1 defines the first tangent vector
  3269. * @param value2 defines the second control point
  3270. * @param tangent2 defines the second tangent vector
  3271. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3272. * @returns the new Vector3
  3273. */
  3274. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3275. var squared = amount * amount;
  3276. var cubed = amount * squared;
  3277. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3278. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3279. var part3 = (cubed - (2.0 * squared)) + amount;
  3280. var part4 = cubed - squared;
  3281. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3282. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3283. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3284. return new Vector3(x, y, z);
  3285. };
  3286. /**
  3287. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3288. * @param start defines the start value
  3289. * @param end defines the end value
  3290. * @param amount max defines amount between both (between 0 and 1)
  3291. * @returns the new Vector3
  3292. */
  3293. Vector3.Lerp = function (start, end, amount) {
  3294. var result = new Vector3(0, 0, 0);
  3295. Vector3.LerpToRef(start, end, amount, result);
  3296. return result;
  3297. };
  3298. /**
  3299. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3300. * @param start defines the start value
  3301. * @param end defines the end value
  3302. * @param amount max defines amount between both (between 0 and 1)
  3303. * @param result defines the Vector3 where to store the result
  3304. */
  3305. Vector3.LerpToRef = function (start, end, amount, result) {
  3306. result.x = start.x + ((end.x - start.x) * amount);
  3307. result.y = start.y + ((end.y - start.y) * amount);
  3308. result.z = start.z + ((end.z - start.z) * amount);
  3309. };
  3310. /**
  3311. * Returns the dot product (float) between the vectors "left" and "right"
  3312. * @param left defines the left operand
  3313. * @param right defines the right operand
  3314. * @returns the dot product
  3315. */
  3316. Vector3.Dot = function (left, right) {
  3317. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3318. };
  3319. /**
  3320. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3321. * The cross product is then orthogonal to both "left" and "right"
  3322. * @param left defines the left operand
  3323. * @param right defines the right operand
  3324. * @returns the cross product
  3325. */
  3326. Vector3.Cross = function (left, right) {
  3327. var result = Vector3.Zero();
  3328. Vector3.CrossToRef(left, right, result);
  3329. return result;
  3330. };
  3331. /**
  3332. * Sets the passed vector "result" with the cross product of "left" and "right"
  3333. * The cross product is then orthogonal to both "left" and "right"
  3334. * @param left defines the left operand
  3335. * @param right defines the right operand
  3336. * @param result defines the Vector3 where to store the result
  3337. */
  3338. Vector3.CrossToRef = function (left, right, result) {
  3339. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3340. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3341. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3342. result.copyFrom(MathTmp.Vector3[0]);
  3343. };
  3344. /**
  3345. * Returns a new Vector3 as the normalization of the passed vector
  3346. * @param vector defines the Vector3 to normalize
  3347. * @returns the new Vector3
  3348. */
  3349. Vector3.Normalize = function (vector) {
  3350. var result = Vector3.Zero();
  3351. Vector3.NormalizeToRef(vector, result);
  3352. return result;
  3353. };
  3354. /**
  3355. * Sets the passed vector "result" with the normalization of the passed first vector
  3356. * @param vector defines the Vector3 to normalize
  3357. * @param result defines the Vector3 where to store the result
  3358. */
  3359. Vector3.NormalizeToRef = function (vector, result) {
  3360. result.copyFrom(vector);
  3361. result.normalize();
  3362. };
  3363. /**
  3364. * Project a Vector3 onto screen space
  3365. * @param vector defines the Vector3 to project
  3366. * @param world defines the world matrix to use
  3367. * @param transform defines the transform (view x projection) matrix to use
  3368. * @param viewport defines the screen viewport to use
  3369. * @returns the new Vector3
  3370. */
  3371. Vector3.Project = function (vector, world, transform, viewport) {
  3372. var cw = viewport.width;
  3373. var ch = viewport.height;
  3374. var cx = viewport.x;
  3375. var cy = viewport.y;
  3376. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3377. 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);
  3378. var matrix = MathTmp.Matrix[0];
  3379. world.multiplyToRef(transform, matrix);
  3380. matrix.multiplyToRef(viewportMatrix, matrix);
  3381. return Vector3.TransformCoordinates(vector, matrix);
  3382. };
  3383. /**
  3384. * Unproject from screen space to object space
  3385. * @param source defines the screen space Vector3 to use
  3386. * @param viewportWidth defines the current width of the viewport
  3387. * @param viewportHeight defines the current height of the viewport
  3388. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3389. * @param transform defines the transform (view x projection) matrix to use
  3390. * @returns the new Vector3
  3391. */
  3392. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3393. var matrix = MathTmp.Matrix[0];
  3394. world.multiplyToRef(transform, matrix);
  3395. matrix.invert();
  3396. source.x = source.x / viewportWidth * 2 - 1;
  3397. source.y = -(source.y / viewportHeight * 2 - 1);
  3398. var vector = Vector3.TransformCoordinates(source, matrix);
  3399. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3400. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3401. vector = vector.scale(1.0 / num);
  3402. }
  3403. return vector;
  3404. };
  3405. /**
  3406. * Unproject from screen space to object space
  3407. * @param source defines the screen space Vector3 to use
  3408. * @param viewportWidth defines the current width of the viewport
  3409. * @param viewportHeight defines the current height of the viewport
  3410. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3411. * @param view defines the view matrix to use
  3412. * @param projection defines the projection matrix to use
  3413. * @returns the new Vector3
  3414. */
  3415. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3416. var result = Vector3.Zero();
  3417. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3418. return result;
  3419. };
  3420. /**
  3421. * Unproject from screen space to object space
  3422. * @param source defines the screen space Vector3 to use
  3423. * @param viewportWidth defines the current width of the viewport
  3424. * @param viewportHeight defines the current height of the viewport
  3425. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3426. * @param view defines the view matrix to use
  3427. * @param projection defines the projection matrix to use
  3428. * @param result defines the Vector3 where to store the result
  3429. */
  3430. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3431. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3432. };
  3433. /**
  3434. * Unproject from screen space to object space
  3435. * @param sourceX defines the screen space x coordinate to use
  3436. * @param sourceY defines the screen space y coordinate to use
  3437. * @param sourceZ defines the screen space z coordinate to use
  3438. * @param viewportWidth defines the current width of the viewport
  3439. * @param viewportHeight defines the current height of the viewport
  3440. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3441. * @param view defines the view matrix to use
  3442. * @param projection defines the projection matrix to use
  3443. * @param result defines the Vector3 where to store the result
  3444. */
  3445. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3446. var matrix = MathTmp.Matrix[0];
  3447. world.multiplyToRef(view, matrix);
  3448. matrix.multiplyToRef(projection, matrix);
  3449. matrix.invert();
  3450. var screenSource = MathTmp.Vector3[0];
  3451. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3452. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3453. screenSource.z = 2 * sourceZ - 1.0;
  3454. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3455. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3456. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3457. result.scaleInPlace(1.0 / num);
  3458. }
  3459. };
  3460. /**
  3461. * Gets the minimal coordinate values between two Vector3
  3462. * @param left defines the first operand
  3463. * @param right defines the second operand
  3464. * @returns the new Vector3
  3465. */
  3466. Vector3.Minimize = function (left, right) {
  3467. var min = left.clone();
  3468. min.minimizeInPlace(right);
  3469. return min;
  3470. };
  3471. /**
  3472. * Gets the maximal coordinate values between two Vector3
  3473. * @param left defines the first operand
  3474. * @param right defines the second operand
  3475. * @returns the new Vector3
  3476. */
  3477. Vector3.Maximize = function (left, right) {
  3478. var max = left.clone();
  3479. max.maximizeInPlace(right);
  3480. return max;
  3481. };
  3482. /**
  3483. * Returns the distance between the vectors "value1" and "value2"
  3484. * @param value1 defines the first operand
  3485. * @param value2 defines the second operand
  3486. * @returns the distance
  3487. */
  3488. Vector3.Distance = function (value1, value2) {
  3489. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3490. };
  3491. /**
  3492. * Returns the squared distance between the vectors "value1" and "value2"
  3493. * @param value1 defines the first operand
  3494. * @param value2 defines the second operand
  3495. * @returns the squared distance
  3496. */
  3497. Vector3.DistanceSquared = function (value1, value2) {
  3498. var x = value1.x - value2.x;
  3499. var y = value1.y - value2.y;
  3500. var z = value1.z - value2.z;
  3501. return (x * x) + (y * y) + (z * z);
  3502. };
  3503. /**
  3504. * Returns a new Vector3 located at the center between "value1" and "value2"
  3505. * @param value1 defines the first operand
  3506. * @param value2 defines the second operand
  3507. * @returns the new Vector3
  3508. */
  3509. Vector3.Center = function (value1, value2) {
  3510. var center = value1.add(value2);
  3511. center.scaleInPlace(0.5);
  3512. return center;
  3513. };
  3514. /**
  3515. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3516. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3517. * to something in order to rotate it from its local system to the given target system
  3518. * Note: axis1, axis2 and axis3 are normalized during this operation
  3519. * @param axis1 defines the first axis
  3520. * @param axis2 defines the second axis
  3521. * @param axis3 defines the third axis
  3522. * @returns a new Vector3
  3523. */
  3524. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3525. var rotation = Vector3.Zero();
  3526. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3527. return rotation;
  3528. };
  3529. /**
  3530. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3531. * @param axis1 defines the first axis
  3532. * @param axis2 defines the second axis
  3533. * @param axis3 defines the third axis
  3534. * @param ref defines the Vector3 where to store the result
  3535. */
  3536. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3537. var quat = MathTmp.Quaternion[0];
  3538. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3539. quat.toEulerAnglesToRef(ref);
  3540. };
  3541. return Vector3;
  3542. }());
  3543. BABYLON.Vector3 = Vector3;
  3544. //Vector4 class created for EulerAngle class conversion to Quaternion
  3545. var Vector4 = /** @class */ (function () {
  3546. /**
  3547. * Creates a Vector4 object from the passed floats.
  3548. */
  3549. function Vector4(x, y, z, w) {
  3550. this.x = x;
  3551. this.y = y;
  3552. this.z = z;
  3553. this.w = w;
  3554. }
  3555. /**
  3556. * Returns the string with the Vector4 coordinates.
  3557. */
  3558. Vector4.prototype.toString = function () {
  3559. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3560. };
  3561. /**
  3562. * Returns the string "Vector4".
  3563. */
  3564. Vector4.prototype.getClassName = function () {
  3565. return "Vector4";
  3566. };
  3567. /**
  3568. * Returns the Vector4 hash code.
  3569. */
  3570. Vector4.prototype.getHashCode = function () {
  3571. var hash = this.x || 0;
  3572. hash = (hash * 397) ^ (this.y || 0);
  3573. hash = (hash * 397) ^ (this.z || 0);
  3574. hash = (hash * 397) ^ (this.w || 0);
  3575. return hash;
  3576. };
  3577. // Operators
  3578. /**
  3579. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3580. */
  3581. Vector4.prototype.asArray = function () {
  3582. var result = new Array();
  3583. this.toArray(result, 0);
  3584. return result;
  3585. };
  3586. /**
  3587. * Populates the passed array from the passed index with the Vector4 coordinates.
  3588. * Returns the Vector4.
  3589. */
  3590. Vector4.prototype.toArray = function (array, index) {
  3591. if (index === undefined) {
  3592. index = 0;
  3593. }
  3594. array[index] = this.x;
  3595. array[index + 1] = this.y;
  3596. array[index + 2] = this.z;
  3597. array[index + 3] = this.w;
  3598. return this;
  3599. };
  3600. /**
  3601. * Adds the passed vector to the current Vector4.
  3602. * Returns the updated Vector4.
  3603. */
  3604. Vector4.prototype.addInPlace = function (otherVector) {
  3605. this.x += otherVector.x;
  3606. this.y += otherVector.y;
  3607. this.z += otherVector.z;
  3608. this.w += otherVector.w;
  3609. return this;
  3610. };
  3611. /**
  3612. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3613. */
  3614. Vector4.prototype.add = function (otherVector) {
  3615. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3616. };
  3617. /**
  3618. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3619. * Returns the current Vector4.
  3620. */
  3621. Vector4.prototype.addToRef = function (otherVector, result) {
  3622. result.x = this.x + otherVector.x;
  3623. result.y = this.y + otherVector.y;
  3624. result.z = this.z + otherVector.z;
  3625. result.w = this.w + otherVector.w;
  3626. return this;
  3627. };
  3628. /**
  3629. * Subtract in place the passed vector from the current Vector4.
  3630. * Returns the updated Vector4.
  3631. */
  3632. Vector4.prototype.subtractInPlace = function (otherVector) {
  3633. this.x -= otherVector.x;
  3634. this.y -= otherVector.y;
  3635. this.z -= otherVector.z;
  3636. this.w -= otherVector.w;
  3637. return this;
  3638. };
  3639. /**
  3640. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3641. */
  3642. Vector4.prototype.subtract = function (otherVector) {
  3643. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3644. };
  3645. /**
  3646. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3647. * Returns the current Vector4.
  3648. */
  3649. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3650. result.x = this.x - otherVector.x;
  3651. result.y = this.y - otherVector.y;
  3652. result.z = this.z - otherVector.z;
  3653. result.w = this.w - otherVector.w;
  3654. return this;
  3655. };
  3656. /**
  3657. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3658. */
  3659. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3660. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3661. };
  3662. /**
  3663. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3664. * Returns the current Vector4.
  3665. */
  3666. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3667. result.x = this.x - x;
  3668. result.y = this.y - y;
  3669. result.z = this.z - z;
  3670. result.w = this.w - w;
  3671. return this;
  3672. };
  3673. /**
  3674. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3675. */
  3676. Vector4.prototype.negate = function () {
  3677. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3678. };
  3679. /**
  3680. * Multiplies the current Vector4 coordinates by scale (float).
  3681. * Returns the updated Vector4.
  3682. */
  3683. Vector4.prototype.scaleInPlace = function (scale) {
  3684. this.x *= scale;
  3685. this.y *= scale;
  3686. this.z *= scale;
  3687. this.w *= scale;
  3688. return this;
  3689. };
  3690. /**
  3691. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3692. */
  3693. Vector4.prototype.scale = function (scale) {
  3694. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3695. };
  3696. /**
  3697. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3698. * Returns the current Vector4.
  3699. */
  3700. Vector4.prototype.scaleToRef = function (scale, result) {
  3701. result.x = this.x * scale;
  3702. result.y = this.y * scale;
  3703. result.z = this.z * scale;
  3704. result.w = this.w * scale;
  3705. return this;
  3706. };
  3707. /**
  3708. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3709. */
  3710. Vector4.prototype.equals = function (otherVector) {
  3711. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3712. };
  3713. /**
  3714. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3715. */
  3716. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3717. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3718. return otherVector
  3719. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3720. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3721. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3722. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3723. };
  3724. /**
  3725. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3726. */
  3727. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3728. return this.x === x && this.y === y && this.z === z && this.w === w;
  3729. };
  3730. /**
  3731. * Multiplies in place the current Vector4 by the passed one.
  3732. * Returns the updated Vector4.
  3733. */
  3734. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3735. this.x *= otherVector.x;
  3736. this.y *= otherVector.y;
  3737. this.z *= otherVector.z;
  3738. this.w *= otherVector.w;
  3739. return this;
  3740. };
  3741. /**
  3742. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3743. */
  3744. Vector4.prototype.multiply = function (otherVector) {
  3745. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3746. };
  3747. /**
  3748. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3749. * Returns the current Vector4.
  3750. */
  3751. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3752. result.x = this.x * otherVector.x;
  3753. result.y = this.y * otherVector.y;
  3754. result.z = this.z * otherVector.z;
  3755. result.w = this.w * otherVector.w;
  3756. return this;
  3757. };
  3758. /**
  3759. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3760. */
  3761. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3762. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3763. };
  3764. /**
  3765. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3766. */
  3767. Vector4.prototype.divide = function (otherVector) {
  3768. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3769. };
  3770. /**
  3771. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3772. * Returns the current Vector4.
  3773. */
  3774. Vector4.prototype.divideToRef = function (otherVector, result) {
  3775. result.x = this.x / otherVector.x;
  3776. result.y = this.y / otherVector.y;
  3777. result.z = this.z / otherVector.z;
  3778. result.w = this.w / otherVector.w;
  3779. return this;
  3780. };
  3781. /**
  3782. * Divides the current Vector3 coordinates by the passed ones.
  3783. * @returns the updated Vector3.
  3784. */
  3785. Vector4.prototype.divideInPlace = function (otherVector) {
  3786. return this.divideToRef(otherVector, this);
  3787. };
  3788. /**
  3789. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3790. * @param other defines the second operand
  3791. * @returns the current updated Vector4
  3792. */
  3793. Vector4.prototype.minimizeInPlace = function (other) {
  3794. if (other.x < this.x)
  3795. this.x = other.x;
  3796. if (other.y < this.y)
  3797. this.y = other.y;
  3798. if (other.z < this.z)
  3799. this.z = other.z;
  3800. if (other.w < this.w)
  3801. this.w = other.w;
  3802. return this;
  3803. };
  3804. /**
  3805. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3806. * @param other defines the second operand
  3807. * @returns the current updated Vector4
  3808. */
  3809. Vector4.prototype.maximizeInPlace = function (other) {
  3810. if (other.x > this.x)
  3811. this.x = other.x;
  3812. if (other.y > this.y)
  3813. this.y = other.y;
  3814. if (other.z > this.z)
  3815. this.z = other.z;
  3816. if (other.w > this.w)
  3817. this.w = other.w;
  3818. return this;
  3819. };
  3820. // Properties
  3821. /**
  3822. * Returns the Vector4 length (float).
  3823. */
  3824. Vector4.prototype.length = function () {
  3825. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3826. };
  3827. /**
  3828. * Returns the Vector4 squared length (float).
  3829. */
  3830. Vector4.prototype.lengthSquared = function () {
  3831. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3832. };
  3833. // Methods
  3834. /**
  3835. * Normalizes in place the Vector4.
  3836. * Returns the updated Vector4.
  3837. */
  3838. Vector4.prototype.normalize = function () {
  3839. var len = this.length();
  3840. if (len === 0)
  3841. return this;
  3842. var num = 1.0 / len;
  3843. this.x *= num;
  3844. this.y *= num;
  3845. this.z *= num;
  3846. this.w *= num;
  3847. return this;
  3848. };
  3849. /**
  3850. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  3851. */
  3852. Vector4.prototype.toVector3 = function () {
  3853. return new Vector3(this.x, this.y, this.z);
  3854. };
  3855. /**
  3856. * Returns a new Vector4 copied from the current one.
  3857. */
  3858. Vector4.prototype.clone = function () {
  3859. return new Vector4(this.x, this.y, this.z, this.w);
  3860. };
  3861. /**
  3862. * Updates the current Vector4 with the passed one coordinates.
  3863. * Returns the updated Vector4.
  3864. */
  3865. Vector4.prototype.copyFrom = function (source) {
  3866. this.x = source.x;
  3867. this.y = source.y;
  3868. this.z = source.z;
  3869. this.w = source.w;
  3870. return this;
  3871. };
  3872. /**
  3873. * Updates the current Vector4 coordinates with the passed floats.
  3874. * Returns the updated Vector4.
  3875. */
  3876. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  3877. this.x = x;
  3878. this.y = y;
  3879. this.z = z;
  3880. this.w = w;
  3881. return this;
  3882. };
  3883. /**
  3884. * Updates the current Vector4 coordinates with the passed floats.
  3885. * Returns the updated Vector4.
  3886. */
  3887. Vector4.prototype.set = function (x, y, z, w) {
  3888. return this.copyFromFloats(x, y, z, w);
  3889. };
  3890. // Statics
  3891. /**
  3892. * Returns a new Vector4 set from the starting index of the passed array.
  3893. */
  3894. Vector4.FromArray = function (array, offset) {
  3895. if (!offset) {
  3896. offset = 0;
  3897. }
  3898. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  3899. };
  3900. /**
  3901. * Updates the passed vector "result" from the starting index of the passed array.
  3902. */
  3903. Vector4.FromArrayToRef = function (array, offset, result) {
  3904. result.x = array[offset];
  3905. result.y = array[offset + 1];
  3906. result.z = array[offset + 2];
  3907. result.w = array[offset + 3];
  3908. };
  3909. /**
  3910. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  3911. */
  3912. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  3913. Vector4.FromArrayToRef(array, offset, result);
  3914. };
  3915. /**
  3916. * Updates the passed vector "result" coordinates from the passed floats.
  3917. */
  3918. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  3919. result.x = x;
  3920. result.y = y;
  3921. result.z = z;
  3922. result.w = w;
  3923. };
  3924. /**
  3925. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  3926. */
  3927. Vector4.Zero = function () {
  3928. return new Vector4(0.0, 0.0, 0.0, 0.0);
  3929. };
  3930. /**
  3931. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  3932. */
  3933. Vector4.One = function () {
  3934. return new Vector4(1.0, 1.0, 1.0, 1.0);
  3935. };
  3936. /**
  3937. * Returns a new normalized Vector4 from the passed one.
  3938. */
  3939. Vector4.Normalize = function (vector) {
  3940. var result = Vector4.Zero();
  3941. Vector4.NormalizeToRef(vector, result);
  3942. return result;
  3943. };
  3944. /**
  3945. * Updates the passed vector "result" from the normalization of the passed one.
  3946. */
  3947. Vector4.NormalizeToRef = function (vector, result) {
  3948. result.copyFrom(vector);
  3949. result.normalize();
  3950. };
  3951. Vector4.Minimize = function (left, right) {
  3952. var min = left.clone();
  3953. min.minimizeInPlace(right);
  3954. return min;
  3955. };
  3956. Vector4.Maximize = function (left, right) {
  3957. var max = left.clone();
  3958. max.maximizeInPlace(right);
  3959. return max;
  3960. };
  3961. /**
  3962. * Returns the distance (float) between the vectors "value1" and "value2".
  3963. */
  3964. Vector4.Distance = function (value1, value2) {
  3965. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  3966. };
  3967. /**
  3968. * Returns the squared distance (float) between the vectors "value1" and "value2".
  3969. */
  3970. Vector4.DistanceSquared = function (value1, value2) {
  3971. var x = value1.x - value2.x;
  3972. var y = value1.y - value2.y;
  3973. var z = value1.z - value2.z;
  3974. var w = value1.w - value2.w;
  3975. return (x * x) + (y * y) + (z * z) + (w * w);
  3976. };
  3977. /**
  3978. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  3979. */
  3980. Vector4.Center = function (value1, value2) {
  3981. var center = value1.add(value2);
  3982. center.scaleInPlace(0.5);
  3983. return center;
  3984. };
  3985. /**
  3986. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  3987. * This methods computes transformed normalized direction vectors only.
  3988. */
  3989. Vector4.TransformNormal = function (vector, transformation) {
  3990. var result = Vector4.Zero();
  3991. Vector4.TransformNormalToRef(vector, transformation, result);
  3992. return result;
  3993. };
  3994. /**
  3995. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  3996. * This methods computes transformed normalized direction vectors only.
  3997. */
  3998. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  3999. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4000. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4001. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4002. result.x = x;
  4003. result.y = y;
  4004. result.z = z;
  4005. result.w = vector.w;
  4006. };
  4007. /**
  4008. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4009. * This methods computes transformed normalized direction vectors only.
  4010. */
  4011. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4012. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4013. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4014. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4015. result.w = w;
  4016. };
  4017. return Vector4;
  4018. }());
  4019. BABYLON.Vector4 = Vector4;
  4020. var Size = /** @class */ (function () {
  4021. /**
  4022. * Creates a Size object from the passed width and height (floats).
  4023. */
  4024. function Size(width, height) {
  4025. this.width = width;
  4026. this.height = height;
  4027. }
  4028. // Returns a string with the Size width and height.
  4029. Size.prototype.toString = function () {
  4030. return "{W: " + this.width + ", H: " + this.height + "}";
  4031. };
  4032. /**
  4033. * Returns the string "Size"
  4034. */
  4035. Size.prototype.getClassName = function () {
  4036. return "Size";
  4037. };
  4038. /**
  4039. * Returns the Size hash code.
  4040. */
  4041. Size.prototype.getHashCode = function () {
  4042. var hash = this.width || 0;
  4043. hash = (hash * 397) ^ (this.height || 0);
  4044. return hash;
  4045. };
  4046. /**
  4047. * Updates the current size from the passed one.
  4048. * Returns the updated Size.
  4049. */
  4050. Size.prototype.copyFrom = function (src) {
  4051. this.width = src.width;
  4052. this.height = src.height;
  4053. };
  4054. /**
  4055. * Updates in place the current Size from the passed floats.
  4056. * Returns the updated Size.
  4057. */
  4058. Size.prototype.copyFromFloats = function (width, height) {
  4059. this.width = width;
  4060. this.height = height;
  4061. return this;
  4062. };
  4063. /**
  4064. * Updates in place the current Size from the passed floats.
  4065. * Returns the updated Size.
  4066. */
  4067. Size.prototype.set = function (width, height) {
  4068. return this.copyFromFloats(width, height);
  4069. };
  4070. /**
  4071. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4072. */
  4073. Size.prototype.multiplyByFloats = function (w, h) {
  4074. return new Size(this.width * w, this.height * h);
  4075. };
  4076. /**
  4077. * Returns a new Size copied from the passed one.
  4078. */
  4079. Size.prototype.clone = function () {
  4080. return new Size(this.width, this.height);
  4081. };
  4082. /**
  4083. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4084. */
  4085. Size.prototype.equals = function (other) {
  4086. if (!other) {
  4087. return false;
  4088. }
  4089. return (this.width === other.width) && (this.height === other.height);
  4090. };
  4091. Object.defineProperty(Size.prototype, "surface", {
  4092. /**
  4093. * Returns the surface of the Size : width * height (float).
  4094. */
  4095. get: function () {
  4096. return this.width * this.height;
  4097. },
  4098. enumerable: true,
  4099. configurable: true
  4100. });
  4101. /**
  4102. * Returns a new Size set to (0.0, 0.0)
  4103. */
  4104. Size.Zero = function () {
  4105. return new Size(0.0, 0.0);
  4106. };
  4107. /**
  4108. * Returns a new Size set as the addition result of the current Size and the passed one.
  4109. */
  4110. Size.prototype.add = function (otherSize) {
  4111. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4112. return r;
  4113. };
  4114. /**
  4115. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4116. */
  4117. Size.prototype.subtract = function (otherSize) {
  4118. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4119. return r;
  4120. };
  4121. /**
  4122. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4123. */
  4124. Size.Lerp = function (start, end, amount) {
  4125. var w = start.width + ((end.width - start.width) * amount);
  4126. var h = start.height + ((end.height - start.height) * amount);
  4127. return new Size(w, h);
  4128. };
  4129. return Size;
  4130. }());
  4131. BABYLON.Size = Size;
  4132. var Quaternion = /** @class */ (function () {
  4133. /**
  4134. * Creates a new Quaternion from the passed floats.
  4135. */
  4136. function Quaternion(x, y, z, w) {
  4137. if (x === void 0) { x = 0.0; }
  4138. if (y === void 0) { y = 0.0; }
  4139. if (z === void 0) { z = 0.0; }
  4140. if (w === void 0) { w = 1.0; }
  4141. this.x = x;
  4142. this.y = y;
  4143. this.z = z;
  4144. this.w = w;
  4145. }
  4146. /**
  4147. * Returns a string with the Quaternion coordinates.
  4148. */
  4149. Quaternion.prototype.toString = function () {
  4150. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4151. };
  4152. /**
  4153. * Returns the string "Quaternion".
  4154. */
  4155. Quaternion.prototype.getClassName = function () {
  4156. return "Quaternion";
  4157. };
  4158. /**
  4159. * Returns the Quaternion hash code.
  4160. */
  4161. Quaternion.prototype.getHashCode = function () {
  4162. var hash = this.x || 0;
  4163. hash = (hash * 397) ^ (this.y || 0);
  4164. hash = (hash * 397) ^ (this.z || 0);
  4165. hash = (hash * 397) ^ (this.w || 0);
  4166. return hash;
  4167. };
  4168. /**
  4169. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4170. */
  4171. Quaternion.prototype.asArray = function () {
  4172. return [this.x, this.y, this.z, this.w];
  4173. };
  4174. /**
  4175. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4176. */
  4177. Quaternion.prototype.equals = function (otherQuaternion) {
  4178. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4179. };
  4180. /**
  4181. * Returns a new Quaternion copied from the current one.
  4182. */
  4183. Quaternion.prototype.clone = function () {
  4184. return new Quaternion(this.x, this.y, this.z, this.w);
  4185. };
  4186. /**
  4187. * Updates the current Quaternion from the passed one coordinates.
  4188. * Returns the updated Quaterion.
  4189. */
  4190. Quaternion.prototype.copyFrom = function (other) {
  4191. this.x = other.x;
  4192. this.y = other.y;
  4193. this.z = other.z;
  4194. this.w = other.w;
  4195. return this;
  4196. };
  4197. /**
  4198. * Updates the current Quaternion from the passed float coordinates.
  4199. * Returns the updated Quaterion.
  4200. */
  4201. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4202. this.x = x;
  4203. this.y = y;
  4204. this.z = z;
  4205. this.w = w;
  4206. return this;
  4207. };
  4208. /**
  4209. * Updates the current Quaternion from the passed float coordinates.
  4210. * Returns the updated Quaterion.
  4211. */
  4212. Quaternion.prototype.set = function (x, y, z, w) {
  4213. return this.copyFromFloats(x, y, z, w);
  4214. };
  4215. /**
  4216. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4217. */
  4218. Quaternion.prototype.add = function (other) {
  4219. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4220. };
  4221. /**
  4222. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4223. */
  4224. Quaternion.prototype.subtract = function (other) {
  4225. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4226. };
  4227. /**
  4228. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4229. */
  4230. Quaternion.prototype.scale = function (value) {
  4231. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4232. };
  4233. /**
  4234. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4235. */
  4236. Quaternion.prototype.multiply = function (q1) {
  4237. var result = new Quaternion(0, 0, 0, 1.0);
  4238. this.multiplyToRef(q1, result);
  4239. return result;
  4240. };
  4241. /**
  4242. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4243. * Returns the current Quaternion.
  4244. */
  4245. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4246. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4247. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4248. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4249. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4250. result.copyFromFloats(x, y, z, w);
  4251. return this;
  4252. };
  4253. /**
  4254. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4255. * Returns the updated Quaternion.
  4256. */
  4257. Quaternion.prototype.multiplyInPlace = function (q1) {
  4258. this.multiplyToRef(q1, this);
  4259. return this;
  4260. };
  4261. /**
  4262. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4263. * Returns the current Quaternion.
  4264. */
  4265. Quaternion.prototype.conjugateToRef = function (ref) {
  4266. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4267. return this;
  4268. };
  4269. /**
  4270. * Conjugates in place the current Quaternion.
  4271. * Returns the updated Quaternion.
  4272. */
  4273. Quaternion.prototype.conjugateInPlace = function () {
  4274. this.x *= -1;
  4275. this.y *= -1;
  4276. this.z *= -1;
  4277. return this;
  4278. };
  4279. /**
  4280. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4281. */
  4282. Quaternion.prototype.conjugate = function () {
  4283. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4284. return result;
  4285. };
  4286. /**
  4287. * Returns the Quaternion length (float).
  4288. */
  4289. Quaternion.prototype.length = function () {
  4290. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4291. };
  4292. /**
  4293. * Normalize in place the current Quaternion.
  4294. * Returns the updated Quaternion.
  4295. */
  4296. Quaternion.prototype.normalize = function () {
  4297. var length = 1.0 / this.length();
  4298. this.x *= length;
  4299. this.y *= length;
  4300. this.z *= length;
  4301. this.w *= length;
  4302. return this;
  4303. };
  4304. /**
  4305. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  4306. */
  4307. Quaternion.prototype.toEulerAngles = function (order) {
  4308. if (order === void 0) { order = "YZX"; }
  4309. var result = Vector3.Zero();
  4310. this.toEulerAnglesToRef(result, order);
  4311. return result;
  4312. };
  4313. /**
  4314. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  4315. * Returns the current Quaternion.
  4316. */
  4317. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4318. if (order === void 0) { order = "YZX"; }
  4319. var qz = this.z;
  4320. var qx = this.x;
  4321. var qy = this.y;
  4322. var qw = this.w;
  4323. var sqw = qw * qw;
  4324. var sqz = qz * qz;
  4325. var sqx = qx * qx;
  4326. var sqy = qy * qy;
  4327. var zAxisY = qy * qz - qx * qw;
  4328. var limit = .4999999;
  4329. if (zAxisY < -limit) {
  4330. result.y = 2 * Math.atan2(qy, qw);
  4331. result.x = Math.PI / 2;
  4332. result.z = 0;
  4333. }
  4334. else if (zAxisY > limit) {
  4335. result.y = 2 * Math.atan2(qy, qw);
  4336. result.x = -Math.PI / 2;
  4337. result.z = 0;
  4338. }
  4339. else {
  4340. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4341. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4342. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4343. }
  4344. return this;
  4345. };
  4346. /**
  4347. * Updates the passed rotation matrix with the current Quaternion values.
  4348. * Returns the current Quaternion.
  4349. */
  4350. Quaternion.prototype.toRotationMatrix = function (result) {
  4351. var xx = this.x * this.x;
  4352. var yy = this.y * this.y;
  4353. var zz = this.z * this.z;
  4354. var xy = this.x * this.y;
  4355. var zw = this.z * this.w;
  4356. var zx = this.z * this.x;
  4357. var yw = this.y * this.w;
  4358. var yz = this.y * this.z;
  4359. var xw = this.x * this.w;
  4360. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4361. result.m[1] = 2.0 * (xy + zw);
  4362. result.m[2] = 2.0 * (zx - yw);
  4363. result.m[3] = 0;
  4364. result.m[4] = 2.0 * (xy - zw);
  4365. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4366. result.m[6] = 2.0 * (yz + xw);
  4367. result.m[7] = 0;
  4368. result.m[8] = 2.0 * (zx + yw);
  4369. result.m[9] = 2.0 * (yz - xw);
  4370. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4371. result.m[11] = 0;
  4372. result.m[12] = 0;
  4373. result.m[13] = 0;
  4374. result.m[14] = 0;
  4375. result.m[15] = 1.0;
  4376. result._markAsUpdated();
  4377. return this;
  4378. };
  4379. /**
  4380. * Updates the current Quaternion from the passed rotation matrix values.
  4381. * Returns the updated Quaternion.
  4382. */
  4383. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4384. Quaternion.FromRotationMatrixToRef(matrix, this);
  4385. return this;
  4386. };
  4387. // Statics
  4388. /**
  4389. * Returns a new Quaternion set from the passed rotation matrix values.
  4390. */
  4391. Quaternion.FromRotationMatrix = function (matrix) {
  4392. var result = new Quaternion();
  4393. Quaternion.FromRotationMatrixToRef(matrix, result);
  4394. return result;
  4395. };
  4396. /**
  4397. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4398. */
  4399. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4400. var data = matrix.m;
  4401. var m11 = data[0], m12 = data[4], m13 = data[8];
  4402. var m21 = data[1], m22 = data[5], m23 = data[9];
  4403. var m31 = data[2], m32 = data[6], m33 = data[10];
  4404. var trace = m11 + m22 + m33;
  4405. var s;
  4406. if (trace > 0) {
  4407. s = 0.5 / Math.sqrt(trace + 1.0);
  4408. result.w = 0.25 / s;
  4409. result.x = (m32 - m23) * s;
  4410. result.y = (m13 - m31) * s;
  4411. result.z = (m21 - m12) * s;
  4412. }
  4413. else if (m11 > m22 && m11 > m33) {
  4414. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4415. result.w = (m32 - m23) / s;
  4416. result.x = 0.25 * s;
  4417. result.y = (m12 + m21) / s;
  4418. result.z = (m13 + m31) / s;
  4419. }
  4420. else if (m22 > m33) {
  4421. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4422. result.w = (m13 - m31) / s;
  4423. result.x = (m12 + m21) / s;
  4424. result.y = 0.25 * s;
  4425. result.z = (m23 + m32) / s;
  4426. }
  4427. else {
  4428. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4429. result.w = (m21 - m12) / s;
  4430. result.x = (m13 + m31) / s;
  4431. result.y = (m23 + m32) / s;
  4432. result.z = 0.25 * s;
  4433. }
  4434. };
  4435. /**
  4436. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4437. */
  4438. Quaternion.Zero = function () {
  4439. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4440. };
  4441. /**
  4442. * Returns a new Quaternion as the inverted current Quaternion.
  4443. */
  4444. Quaternion.Inverse = function (q) {
  4445. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4446. };
  4447. /**
  4448. * Returns the identity Quaternion.
  4449. */
  4450. Quaternion.Identity = function () {
  4451. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4452. };
  4453. Quaternion.IsIdentity = function (quaternion) {
  4454. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4455. };
  4456. /**
  4457. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4458. */
  4459. Quaternion.RotationAxis = function (axis, angle) {
  4460. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4461. };
  4462. /**
  4463. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4464. */
  4465. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4466. var sin = Math.sin(angle / 2);
  4467. axis.normalize();
  4468. result.w = Math.cos(angle / 2);
  4469. result.x = axis.x * sin;
  4470. result.y = axis.y * sin;
  4471. result.z = axis.z * sin;
  4472. return result;
  4473. };
  4474. /**
  4475. * Retuns a new Quaternion set from the starting index of the passed array.
  4476. */
  4477. Quaternion.FromArray = function (array, offset) {
  4478. if (!offset) {
  4479. offset = 0;
  4480. }
  4481. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4482. };
  4483. /**
  4484. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4485. */
  4486. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4487. var q = new Quaternion();
  4488. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4489. return q;
  4490. };
  4491. /**
  4492. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4493. */
  4494. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4495. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4496. var halfRoll = roll * 0.5;
  4497. var halfPitch = pitch * 0.5;
  4498. var halfYaw = yaw * 0.5;
  4499. var sinRoll = Math.sin(halfRoll);
  4500. var cosRoll = Math.cos(halfRoll);
  4501. var sinPitch = Math.sin(halfPitch);
  4502. var cosPitch = Math.cos(halfPitch);
  4503. var sinYaw = Math.sin(halfYaw);
  4504. var cosYaw = Math.cos(halfYaw);
  4505. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4506. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4507. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4508. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4509. };
  4510. /**
  4511. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4512. */
  4513. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4514. var result = new Quaternion();
  4515. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4516. return result;
  4517. };
  4518. /**
  4519. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4520. */
  4521. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4522. // Produces a quaternion from Euler angles in the z-x-z orientation
  4523. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4524. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4525. var halfBeta = beta * 0.5;
  4526. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4527. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4528. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4529. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4530. };
  4531. /**
  4532. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4533. * cf to Vector3.RotationFromAxis() documentation.
  4534. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4535. */
  4536. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4537. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4538. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4539. return quat;
  4540. };
  4541. /**
  4542. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4543. * cf to Vector3.RotationFromAxis() documentation.
  4544. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4545. */
  4546. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4547. var rotMat = MathTmp.Matrix[0];
  4548. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4549. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4550. };
  4551. Quaternion.Slerp = function (left, right, amount) {
  4552. var result = Quaternion.Identity();
  4553. Quaternion.SlerpToRef(left, right, amount, result);
  4554. return result;
  4555. };
  4556. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4557. var num2;
  4558. var num3;
  4559. var num = amount;
  4560. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4561. var flag = false;
  4562. if (num4 < 0) {
  4563. flag = true;
  4564. num4 = -num4;
  4565. }
  4566. if (num4 > 0.999999) {
  4567. num3 = 1 - num;
  4568. num2 = flag ? -num : num;
  4569. }
  4570. else {
  4571. var num5 = Math.acos(num4);
  4572. var num6 = (1.0 / Math.sin(num5));
  4573. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4574. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4575. }
  4576. result.x = (num3 * left.x) + (num2 * right.x);
  4577. result.y = (num3 * left.y) + (num2 * right.y);
  4578. result.z = (num3 * left.z) + (num2 * right.z);
  4579. result.w = (num3 * left.w) + (num2 * right.w);
  4580. };
  4581. /**
  4582. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4583. */
  4584. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4585. var squared = amount * amount;
  4586. var cubed = amount * squared;
  4587. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4588. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4589. var part3 = (cubed - (2.0 * squared)) + amount;
  4590. var part4 = cubed - squared;
  4591. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4592. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4593. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4594. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4595. return new Quaternion(x, y, z, w);
  4596. };
  4597. return Quaternion;
  4598. }());
  4599. BABYLON.Quaternion = Quaternion;
  4600. var Matrix = /** @class */ (function () {
  4601. function Matrix() {
  4602. this._isIdentity = false;
  4603. this._isIdentityDirty = true;
  4604. this.m = new Float32Array(16);
  4605. this._markAsUpdated();
  4606. }
  4607. Matrix.prototype._markAsUpdated = function () {
  4608. this.updateFlag = Matrix._updateFlagSeed++;
  4609. this._isIdentityDirty = true;
  4610. };
  4611. // Properties
  4612. /**
  4613. * Boolean : True is the matrix is the identity matrix
  4614. */
  4615. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4616. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4617. if (this._isIdentityDirty) {
  4618. this._isIdentityDirty = false;
  4619. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4620. this._isIdentity = false;
  4621. }
  4622. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4623. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4624. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4625. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4626. this._isIdentity = false;
  4627. }
  4628. else {
  4629. this._isIdentity = true;
  4630. }
  4631. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4632. this._isIdentity = false;
  4633. }
  4634. }
  4635. return this._isIdentity;
  4636. };
  4637. /**
  4638. * Returns the matrix determinant (float).
  4639. */
  4640. Matrix.prototype.determinant = function () {
  4641. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4642. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4643. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4644. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4645. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4646. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4647. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4648. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4649. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4650. };
  4651. // Methods
  4652. /**
  4653. * Returns the matrix underlying array.
  4654. */
  4655. Matrix.prototype.toArray = function () {
  4656. return this.m;
  4657. };
  4658. /**
  4659. * Returns the matrix underlying array.
  4660. */
  4661. Matrix.prototype.asArray = function () {
  4662. return this.toArray();
  4663. };
  4664. /**
  4665. * Inverts in place the Matrix.
  4666. * Returns the Matrix inverted.
  4667. */
  4668. Matrix.prototype.invert = function () {
  4669. this.invertToRef(this);
  4670. return this;
  4671. };
  4672. /**
  4673. * Sets all the matrix elements to zero.
  4674. * Returns the Matrix.
  4675. */
  4676. Matrix.prototype.reset = function () {
  4677. for (var index = 0; index < 16; index++) {
  4678. this.m[index] = 0.0;
  4679. }
  4680. this._markAsUpdated();
  4681. return this;
  4682. };
  4683. /**
  4684. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4685. */
  4686. Matrix.prototype.add = function (other) {
  4687. var result = new Matrix();
  4688. this.addToRef(other, result);
  4689. return result;
  4690. };
  4691. /**
  4692. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4693. * Returns the Matrix.
  4694. */
  4695. Matrix.prototype.addToRef = function (other, result) {
  4696. for (var index = 0; index < 16; index++) {
  4697. result.m[index] = this.m[index] + other.m[index];
  4698. }
  4699. result._markAsUpdated();
  4700. return this;
  4701. };
  4702. /**
  4703. * Adds in place the passed matrix to the current Matrix.
  4704. * Returns the updated Matrix.
  4705. */
  4706. Matrix.prototype.addToSelf = function (other) {
  4707. for (var index = 0; index < 16; index++) {
  4708. this.m[index] += other.m[index];
  4709. }
  4710. this._markAsUpdated();
  4711. return this;
  4712. };
  4713. /**
  4714. * Sets the passed matrix with the current inverted Matrix.
  4715. * Returns the unmodified current Matrix.
  4716. */
  4717. Matrix.prototype.invertToRef = function (other) {
  4718. var l1 = this.m[0];
  4719. var l2 = this.m[1];
  4720. var l3 = this.m[2];
  4721. var l4 = this.m[3];
  4722. var l5 = this.m[4];
  4723. var l6 = this.m[5];
  4724. var l7 = this.m[6];
  4725. var l8 = this.m[7];
  4726. var l9 = this.m[8];
  4727. var l10 = this.m[9];
  4728. var l11 = this.m[10];
  4729. var l12 = this.m[11];
  4730. var l13 = this.m[12];
  4731. var l14 = this.m[13];
  4732. var l15 = this.m[14];
  4733. var l16 = this.m[15];
  4734. var l17 = (l11 * l16) - (l12 * l15);
  4735. var l18 = (l10 * l16) - (l12 * l14);
  4736. var l19 = (l10 * l15) - (l11 * l14);
  4737. var l20 = (l9 * l16) - (l12 * l13);
  4738. var l21 = (l9 * l15) - (l11 * l13);
  4739. var l22 = (l9 * l14) - (l10 * l13);
  4740. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4741. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4742. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4743. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4744. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4745. var l28 = (l7 * l16) - (l8 * l15);
  4746. var l29 = (l6 * l16) - (l8 * l14);
  4747. var l30 = (l6 * l15) - (l7 * l14);
  4748. var l31 = (l5 * l16) - (l8 * l13);
  4749. var l32 = (l5 * l15) - (l7 * l13);
  4750. var l33 = (l5 * l14) - (l6 * l13);
  4751. var l34 = (l7 * l12) - (l8 * l11);
  4752. var l35 = (l6 * l12) - (l8 * l10);
  4753. var l36 = (l6 * l11) - (l7 * l10);
  4754. var l37 = (l5 * l12) - (l8 * l9);
  4755. var l38 = (l5 * l11) - (l7 * l9);
  4756. var l39 = (l5 * l10) - (l6 * l9);
  4757. other.m[0] = l23 * l27;
  4758. other.m[4] = l24 * l27;
  4759. other.m[8] = l25 * l27;
  4760. other.m[12] = l26 * l27;
  4761. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4762. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4763. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4764. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4765. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4766. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4767. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4768. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4769. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4770. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4771. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4772. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4773. other._markAsUpdated();
  4774. return this;
  4775. };
  4776. /**
  4777. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4778. * Returns the updated Matrix.
  4779. */
  4780. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4781. this.m[12] = x;
  4782. this.m[13] = y;
  4783. this.m[14] = z;
  4784. this._markAsUpdated();
  4785. return this;
  4786. };
  4787. /**
  4788. * Inserts the translation vector in the current Matrix.
  4789. * Returns the updated Matrix.
  4790. */
  4791. Matrix.prototype.setTranslation = function (vector3) {
  4792. this.m[12] = vector3.x;
  4793. this.m[13] = vector3.y;
  4794. this.m[14] = vector3.z;
  4795. this._markAsUpdated();
  4796. return this;
  4797. };
  4798. /**
  4799. * Returns a new Vector3 as the extracted translation from the Matrix.
  4800. */
  4801. Matrix.prototype.getTranslation = function () {
  4802. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4803. };
  4804. /**
  4805. * Fill a Vector3 with the extracted translation from the Matrix.
  4806. */
  4807. Matrix.prototype.getTranslationToRef = function (result) {
  4808. result.x = this.m[12];
  4809. result.y = this.m[13];
  4810. result.z = this.m[14];
  4811. return this;
  4812. };
  4813. /**
  4814. * Remove rotation and scaling part from the Matrix.
  4815. * Returns the updated Matrix.
  4816. */
  4817. Matrix.prototype.removeRotationAndScaling = function () {
  4818. this.setRowFromFloats(0, 1, 0, 0, 0);
  4819. this.setRowFromFloats(1, 0, 1, 0, 0);
  4820. this.setRowFromFloats(2, 0, 0, 1, 0);
  4821. return this;
  4822. };
  4823. /**
  4824. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  4825. */
  4826. Matrix.prototype.multiply = function (other) {
  4827. var result = new Matrix();
  4828. this.multiplyToRef(other, result);
  4829. return result;
  4830. };
  4831. /**
  4832. * Updates the current Matrix from the passed one values.
  4833. * Returns the updated Matrix.
  4834. */
  4835. Matrix.prototype.copyFrom = function (other) {
  4836. for (var index = 0; index < 16; index++) {
  4837. this.m[index] = other.m[index];
  4838. }
  4839. this._markAsUpdated();
  4840. return this;
  4841. };
  4842. /**
  4843. * Populates the passed array from the starting index with the Matrix values.
  4844. * Returns the Matrix.
  4845. */
  4846. Matrix.prototype.copyToArray = function (array, offset) {
  4847. if (offset === void 0) { offset = 0; }
  4848. for (var index = 0; index < 16; index++) {
  4849. array[offset + index] = this.m[index];
  4850. }
  4851. return this;
  4852. };
  4853. /**
  4854. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  4855. */
  4856. Matrix.prototype.multiplyToRef = function (other, result) {
  4857. this.multiplyToArray(other, result.m, 0);
  4858. result._markAsUpdated();
  4859. return this;
  4860. };
  4861. /**
  4862. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  4863. */
  4864. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  4865. var tm0 = this.m[0];
  4866. var tm1 = this.m[1];
  4867. var tm2 = this.m[2];
  4868. var tm3 = this.m[3];
  4869. var tm4 = this.m[4];
  4870. var tm5 = this.m[5];
  4871. var tm6 = this.m[6];
  4872. var tm7 = this.m[7];
  4873. var tm8 = this.m[8];
  4874. var tm9 = this.m[9];
  4875. var tm10 = this.m[10];
  4876. var tm11 = this.m[11];
  4877. var tm12 = this.m[12];
  4878. var tm13 = this.m[13];
  4879. var tm14 = this.m[14];
  4880. var tm15 = this.m[15];
  4881. var om0 = other.m[0];
  4882. var om1 = other.m[1];
  4883. var om2 = other.m[2];
  4884. var om3 = other.m[3];
  4885. var om4 = other.m[4];
  4886. var om5 = other.m[5];
  4887. var om6 = other.m[6];
  4888. var om7 = other.m[7];
  4889. var om8 = other.m[8];
  4890. var om9 = other.m[9];
  4891. var om10 = other.m[10];
  4892. var om11 = other.m[11];
  4893. var om12 = other.m[12];
  4894. var om13 = other.m[13];
  4895. var om14 = other.m[14];
  4896. var om15 = other.m[15];
  4897. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  4898. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  4899. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  4900. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  4901. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  4902. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  4903. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  4904. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  4905. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  4906. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  4907. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  4908. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  4909. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  4910. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  4911. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  4912. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  4913. return this;
  4914. };
  4915. /**
  4916. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  4917. */
  4918. Matrix.prototype.equals = function (value) {
  4919. return value &&
  4920. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  4921. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  4922. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  4923. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  4924. };
  4925. /**
  4926. * Returns a new Matrix from the current Matrix.
  4927. */
  4928. Matrix.prototype.clone = function () {
  4929. 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]);
  4930. };
  4931. /**
  4932. * Returns the string "Matrix"
  4933. */
  4934. Matrix.prototype.getClassName = function () {
  4935. return "Matrix";
  4936. };
  4937. /**
  4938. * Returns the Matrix hash code.
  4939. */
  4940. Matrix.prototype.getHashCode = function () {
  4941. var hash = this.m[0] || 0;
  4942. for (var i = 1; i < 16; i++) {
  4943. hash = (hash * 397) ^ (this.m[i] || 0);
  4944. }
  4945. return hash;
  4946. };
  4947. /**
  4948. * Decomposes the current Matrix into :
  4949. * - a scale vector3 passed as a reference to update,
  4950. * - a rotation quaternion passed as a reference to update,
  4951. * - a translation vector3 passed as a reference to update.
  4952. * Returns the true if operation was successful.
  4953. */
  4954. Matrix.prototype.decompose = function (scale, rotation, translation) {
  4955. translation.x = this.m[12];
  4956. translation.y = this.m[13];
  4957. translation.z = this.m[14];
  4958. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  4959. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  4960. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  4961. if (this.determinant() <= 0) {
  4962. scale.y *= -1;
  4963. }
  4964. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  4965. rotation.x = 0;
  4966. rotation.y = 0;
  4967. rotation.z = 0;
  4968. rotation.w = 1;
  4969. return false;
  4970. }
  4971. 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]);
  4972. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  4973. return true;
  4974. };
  4975. /**
  4976. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  4977. * @param ref matrix to store the result
  4978. */
  4979. Matrix.prototype.toNormalMatrix = function (ref) {
  4980. this.invertToRef(ref);
  4981. ref.transpose();
  4982. var m = ref.m;
  4983. 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);
  4984. };
  4985. /**
  4986. * Returns a new Matrix as the extracted rotation matrix from the current one.
  4987. */
  4988. Matrix.prototype.getRotationMatrix = function () {
  4989. var result = Matrix.Identity();
  4990. this.getRotationMatrixToRef(result);
  4991. return result;
  4992. };
  4993. /**
  4994. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  4995. * Returns the current Matrix.
  4996. */
  4997. Matrix.prototype.getRotationMatrixToRef = function (result) {
  4998. var m = this.m;
  4999. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5000. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5001. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5002. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5003. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5004. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5005. 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);
  5006. return this;
  5007. };
  5008. // Statics
  5009. /**
  5010. * Returns a new Matrix set from the starting index of the passed array.
  5011. */
  5012. Matrix.FromArray = function (array, offset) {
  5013. var result = new Matrix();
  5014. if (!offset) {
  5015. offset = 0;
  5016. }
  5017. Matrix.FromArrayToRef(array, offset, result);
  5018. return result;
  5019. };
  5020. /**
  5021. * Sets the passed "result" matrix from the starting index of the passed array.
  5022. */
  5023. Matrix.FromArrayToRef = function (array, offset, result) {
  5024. for (var index = 0; index < 16; index++) {
  5025. result.m[index] = array[index + offset];
  5026. }
  5027. result._markAsUpdated();
  5028. };
  5029. /**
  5030. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5031. */
  5032. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5033. for (var index = 0; index < 16; index++) {
  5034. result.m[index] = array[index + offset] * scale;
  5035. }
  5036. result._markAsUpdated();
  5037. };
  5038. /**
  5039. * Sets the passed matrix "result" with the 16 passed floats.
  5040. */
  5041. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5042. result.m[0] = initialM11;
  5043. result.m[1] = initialM12;
  5044. result.m[2] = initialM13;
  5045. result.m[3] = initialM14;
  5046. result.m[4] = initialM21;
  5047. result.m[5] = initialM22;
  5048. result.m[6] = initialM23;
  5049. result.m[7] = initialM24;
  5050. result.m[8] = initialM31;
  5051. result.m[9] = initialM32;
  5052. result.m[10] = initialM33;
  5053. result.m[11] = initialM34;
  5054. result.m[12] = initialM41;
  5055. result.m[13] = initialM42;
  5056. result.m[14] = initialM43;
  5057. result.m[15] = initialM44;
  5058. result._markAsUpdated();
  5059. };
  5060. /**
  5061. * Returns the index-th row of the current matrix as a new Vector4.
  5062. */
  5063. Matrix.prototype.getRow = function (index) {
  5064. if (index < 0 || index > 3) {
  5065. return null;
  5066. }
  5067. var i = index * 4;
  5068. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5069. };
  5070. /**
  5071. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5072. * Returns the updated Matrix.
  5073. */
  5074. Matrix.prototype.setRow = function (index, row) {
  5075. if (index < 0 || index > 3) {
  5076. return this;
  5077. }
  5078. var i = index * 4;
  5079. this.m[i + 0] = row.x;
  5080. this.m[i + 1] = row.y;
  5081. this.m[i + 2] = row.z;
  5082. this.m[i + 3] = row.w;
  5083. this._markAsUpdated();
  5084. return this;
  5085. };
  5086. /**
  5087. * Compute the transpose of the matrix.
  5088. * Returns a new Matrix.
  5089. */
  5090. Matrix.prototype.transpose = function () {
  5091. return Matrix.Transpose(this);
  5092. };
  5093. /**
  5094. * Compute the transpose of the matrix.
  5095. * Returns the current matrix.
  5096. */
  5097. Matrix.prototype.transposeToRef = function (result) {
  5098. Matrix.TransposeToRef(this, result);
  5099. return this;
  5100. };
  5101. /**
  5102. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5103. * Returns the updated Matrix.
  5104. */
  5105. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5106. if (index < 0 || index > 3) {
  5107. return this;
  5108. }
  5109. var i = index * 4;
  5110. this.m[i + 0] = x;
  5111. this.m[i + 1] = y;
  5112. this.m[i + 2] = z;
  5113. this.m[i + 3] = w;
  5114. this._markAsUpdated();
  5115. return this;
  5116. };
  5117. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5118. /**
  5119. * Static identity matrix to be used as readonly matrix
  5120. * Must not be updated.
  5121. */
  5122. get: function () {
  5123. return Matrix._identityReadOnly;
  5124. },
  5125. enumerable: true,
  5126. configurable: true
  5127. });
  5128. /**
  5129. * Returns a new Matrix set from the 16 passed floats.
  5130. */
  5131. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5132. var result = new Matrix();
  5133. result.m[0] = initialM11;
  5134. result.m[1] = initialM12;
  5135. result.m[2] = initialM13;
  5136. result.m[3] = initialM14;
  5137. result.m[4] = initialM21;
  5138. result.m[5] = initialM22;
  5139. result.m[6] = initialM23;
  5140. result.m[7] = initialM24;
  5141. result.m[8] = initialM31;
  5142. result.m[9] = initialM32;
  5143. result.m[10] = initialM33;
  5144. result.m[11] = initialM34;
  5145. result.m[12] = initialM41;
  5146. result.m[13] = initialM42;
  5147. result.m[14] = initialM43;
  5148. result.m[15] = initialM44;
  5149. return result;
  5150. };
  5151. /**
  5152. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5153. */
  5154. Matrix.Compose = function (scale, rotation, translation) {
  5155. var result = Matrix.Identity();
  5156. Matrix.ComposeToRef(scale, rotation, translation, result);
  5157. return result;
  5158. };
  5159. /**
  5160. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5161. */
  5162. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5163. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5164. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5165. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5166. result.setTranslation(translation);
  5167. };
  5168. /**
  5169. * Returns a new indentity Matrix.
  5170. */
  5171. Matrix.Identity = function () {
  5172. 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);
  5173. };
  5174. /**
  5175. * Sets the passed "result" as an identity matrix.
  5176. */
  5177. Matrix.IdentityToRef = function (result) {
  5178. 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);
  5179. };
  5180. /**
  5181. * Returns a new zero Matrix.
  5182. */
  5183. Matrix.Zero = function () {
  5184. 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);
  5185. };
  5186. /**
  5187. * Returns a new rotation matrix for "angle" radians around the X axis.
  5188. */
  5189. Matrix.RotationX = function (angle) {
  5190. var result = new Matrix();
  5191. Matrix.RotationXToRef(angle, result);
  5192. return result;
  5193. };
  5194. /**
  5195. * Returns a new Matrix as the passed inverted one.
  5196. */
  5197. Matrix.Invert = function (source) {
  5198. var result = new Matrix();
  5199. source.invertToRef(result);
  5200. return result;
  5201. };
  5202. /**
  5203. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5204. */
  5205. Matrix.RotationXToRef = function (angle, result) {
  5206. var s = Math.sin(angle);
  5207. var c = Math.cos(angle);
  5208. result.m[0] = 1.0;
  5209. result.m[15] = 1.0;
  5210. result.m[5] = c;
  5211. result.m[10] = c;
  5212. result.m[9] = -s;
  5213. result.m[6] = s;
  5214. result.m[1] = 0.0;
  5215. result.m[2] = 0.0;
  5216. result.m[3] = 0.0;
  5217. result.m[4] = 0.0;
  5218. result.m[7] = 0.0;
  5219. result.m[8] = 0.0;
  5220. result.m[11] = 0.0;
  5221. result.m[12] = 0.0;
  5222. result.m[13] = 0.0;
  5223. result.m[14] = 0.0;
  5224. result._markAsUpdated();
  5225. };
  5226. /**
  5227. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5228. */
  5229. Matrix.RotationY = function (angle) {
  5230. var result = new Matrix();
  5231. Matrix.RotationYToRef(angle, result);
  5232. return result;
  5233. };
  5234. /**
  5235. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5236. */
  5237. Matrix.RotationYToRef = function (angle, result) {
  5238. var s = Math.sin(angle);
  5239. var c = Math.cos(angle);
  5240. result.m[5] = 1.0;
  5241. result.m[15] = 1.0;
  5242. result.m[0] = c;
  5243. result.m[2] = -s;
  5244. result.m[8] = s;
  5245. result.m[10] = c;
  5246. result.m[1] = 0.0;
  5247. result.m[3] = 0.0;
  5248. result.m[4] = 0.0;
  5249. result.m[6] = 0.0;
  5250. result.m[7] = 0.0;
  5251. result.m[9] = 0.0;
  5252. result.m[11] = 0.0;
  5253. result.m[12] = 0.0;
  5254. result.m[13] = 0.0;
  5255. result.m[14] = 0.0;
  5256. result._markAsUpdated();
  5257. };
  5258. /**
  5259. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5260. */
  5261. Matrix.RotationZ = function (angle) {
  5262. var result = new Matrix();
  5263. Matrix.RotationZToRef(angle, result);
  5264. return result;
  5265. };
  5266. /**
  5267. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5268. */
  5269. Matrix.RotationZToRef = function (angle, result) {
  5270. var s = Math.sin(angle);
  5271. var c = Math.cos(angle);
  5272. result.m[10] = 1.0;
  5273. result.m[15] = 1.0;
  5274. result.m[0] = c;
  5275. result.m[1] = s;
  5276. result.m[4] = -s;
  5277. result.m[5] = c;
  5278. result.m[2] = 0.0;
  5279. result.m[3] = 0.0;
  5280. result.m[6] = 0.0;
  5281. result.m[7] = 0.0;
  5282. result.m[8] = 0.0;
  5283. result.m[9] = 0.0;
  5284. result.m[11] = 0.0;
  5285. result.m[12] = 0.0;
  5286. result.m[13] = 0.0;
  5287. result.m[14] = 0.0;
  5288. result._markAsUpdated();
  5289. };
  5290. /**
  5291. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5292. */
  5293. Matrix.RotationAxis = function (axis, angle) {
  5294. var result = Matrix.Zero();
  5295. Matrix.RotationAxisToRef(axis, angle, result);
  5296. return result;
  5297. };
  5298. /**
  5299. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5300. */
  5301. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5302. var s = Math.sin(-angle);
  5303. var c = Math.cos(-angle);
  5304. var c1 = 1 - c;
  5305. axis.normalize();
  5306. result.m[0] = (axis.x * axis.x) * c1 + c;
  5307. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5308. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5309. result.m[3] = 0.0;
  5310. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5311. result.m[5] = (axis.y * axis.y) * c1 + c;
  5312. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5313. result.m[7] = 0.0;
  5314. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5315. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5316. result.m[10] = (axis.z * axis.z) * c1 + c;
  5317. result.m[11] = 0.0;
  5318. result.m[15] = 1.0;
  5319. result._markAsUpdated();
  5320. };
  5321. /**
  5322. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5323. */
  5324. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5325. var result = new Matrix();
  5326. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5327. return result;
  5328. };
  5329. /**
  5330. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5331. */
  5332. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5333. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5334. this._tempQuaternion.toRotationMatrix(result);
  5335. };
  5336. /**
  5337. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5338. */
  5339. Matrix.Scaling = function (x, y, z) {
  5340. var result = Matrix.Zero();
  5341. Matrix.ScalingToRef(x, y, z, result);
  5342. return result;
  5343. };
  5344. /**
  5345. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5346. */
  5347. Matrix.ScalingToRef = function (x, y, z, result) {
  5348. result.m[0] = x;
  5349. result.m[1] = 0.0;
  5350. result.m[2] = 0.0;
  5351. result.m[3] = 0.0;
  5352. result.m[4] = 0.0;
  5353. result.m[5] = y;
  5354. result.m[6] = 0.0;
  5355. result.m[7] = 0.0;
  5356. result.m[8] = 0.0;
  5357. result.m[9] = 0.0;
  5358. result.m[10] = z;
  5359. result.m[11] = 0.0;
  5360. result.m[12] = 0.0;
  5361. result.m[13] = 0.0;
  5362. result.m[14] = 0.0;
  5363. result.m[15] = 1.0;
  5364. result._markAsUpdated();
  5365. };
  5366. /**
  5367. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5368. */
  5369. Matrix.Translation = function (x, y, z) {
  5370. var result = Matrix.Identity();
  5371. Matrix.TranslationToRef(x, y, z, result);
  5372. return result;
  5373. };
  5374. /**
  5375. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5376. */
  5377. Matrix.TranslationToRef = function (x, y, z, result) {
  5378. 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);
  5379. };
  5380. /**
  5381. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  5382. */
  5383. Matrix.Lerp = function (startValue, endValue, gradient) {
  5384. var result = Matrix.Zero();
  5385. for (var index = 0; index < 16; index++) {
  5386. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5387. }
  5388. result._markAsUpdated();
  5389. return result;
  5390. };
  5391. /**
  5392. * Returns a new Matrix whose values are computed by :
  5393. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5394. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5395. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5396. */
  5397. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5398. var startScale = new Vector3(0, 0, 0);
  5399. var startRotation = new Quaternion();
  5400. var startTranslation = new Vector3(0, 0, 0);
  5401. startValue.decompose(startScale, startRotation, startTranslation);
  5402. var endScale = new Vector3(0, 0, 0);
  5403. var endRotation = new Quaternion();
  5404. var endTranslation = new Vector3(0, 0, 0);
  5405. endValue.decompose(endScale, endRotation, endTranslation);
  5406. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5407. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5408. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5409. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5410. };
  5411. /**
  5412. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5413. * This methods works for a Left-Handed system.
  5414. */
  5415. Matrix.LookAtLH = function (eye, target, up) {
  5416. var result = Matrix.Zero();
  5417. Matrix.LookAtLHToRef(eye, target, up, result);
  5418. return result;
  5419. };
  5420. /**
  5421. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5422. * This methods works for a Left-Handed system.
  5423. */
  5424. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5425. // Z axis
  5426. target.subtractToRef(eye, this._zAxis);
  5427. this._zAxis.normalize();
  5428. // X axis
  5429. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5430. if (this._xAxis.lengthSquared() === 0) {
  5431. this._xAxis.x = 1.0;
  5432. }
  5433. else {
  5434. this._xAxis.normalize();
  5435. }
  5436. // Y axis
  5437. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5438. this._yAxis.normalize();
  5439. // Eye angles
  5440. var ex = -Vector3.Dot(this._xAxis, eye);
  5441. var ey = -Vector3.Dot(this._yAxis, eye);
  5442. var ez = -Vector3.Dot(this._zAxis, eye);
  5443. 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);
  5444. };
  5445. /**
  5446. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5447. * This methods works for a Right-Handed system.
  5448. */
  5449. Matrix.LookAtRH = function (eye, target, up) {
  5450. var result = Matrix.Zero();
  5451. Matrix.LookAtRHToRef(eye, target, up, result);
  5452. return result;
  5453. };
  5454. /**
  5455. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5456. * This methods works for a Left-Handed system.
  5457. */
  5458. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5459. // Z axis
  5460. eye.subtractToRef(target, this._zAxis);
  5461. this._zAxis.normalize();
  5462. // X axis
  5463. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5464. if (this._xAxis.lengthSquared() === 0) {
  5465. this._xAxis.x = 1.0;
  5466. }
  5467. else {
  5468. this._xAxis.normalize();
  5469. }
  5470. // Y axis
  5471. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5472. this._yAxis.normalize();
  5473. // Eye angles
  5474. var ex = -Vector3.Dot(this._xAxis, eye);
  5475. var ey = -Vector3.Dot(this._yAxis, eye);
  5476. var ez = -Vector3.Dot(this._zAxis, eye);
  5477. 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);
  5478. };
  5479. /**
  5480. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5481. */
  5482. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5483. var matrix = Matrix.Zero();
  5484. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5485. return matrix;
  5486. };
  5487. /**
  5488. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5489. */
  5490. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5491. var n = znear;
  5492. var f = zfar;
  5493. var a = 2.0 / width;
  5494. var b = 2.0 / height;
  5495. var c = 2.0 / (f - n);
  5496. var d = -(f + n) / (f - n);
  5497. 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);
  5498. };
  5499. /**
  5500. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5501. */
  5502. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5503. var matrix = Matrix.Zero();
  5504. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5505. return matrix;
  5506. };
  5507. /**
  5508. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5509. */
  5510. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5511. var n = znear;
  5512. var f = zfar;
  5513. var a = 2.0 / (right - left);
  5514. var b = 2.0 / (top - bottom);
  5515. var c = 2.0 / (f - n);
  5516. var d = -(f + n) / (f - n);
  5517. var i0 = (left + right) / (left - right);
  5518. var i1 = (top + bottom) / (bottom - top);
  5519. 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);
  5520. };
  5521. /**
  5522. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5523. */
  5524. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5525. var matrix = Matrix.Zero();
  5526. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5527. return matrix;
  5528. };
  5529. /**
  5530. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5531. */
  5532. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5533. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5534. result.m[10] *= -1.0;
  5535. };
  5536. /**
  5537. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5538. */
  5539. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5540. var matrix = Matrix.Zero();
  5541. var n = znear;
  5542. var f = zfar;
  5543. var a = 2.0 * n / width;
  5544. var b = 2.0 * n / height;
  5545. var c = (f + n) / (f - n);
  5546. var d = -2.0 * f * n / (f - n);
  5547. 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);
  5548. return matrix;
  5549. };
  5550. /**
  5551. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5552. */
  5553. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5554. var matrix = Matrix.Zero();
  5555. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5556. return matrix;
  5557. };
  5558. /**
  5559. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5560. */
  5561. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5562. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5563. var n = znear;
  5564. var f = zfar;
  5565. var t = 1.0 / (Math.tan(fov * 0.5));
  5566. var a = isVerticalFovFixed ? (t / aspect) : t;
  5567. var b = isVerticalFovFixed ? t : (t * aspect);
  5568. var c = (f + n) / (f - n);
  5569. var d = -2.0 * f * n / (f - n);
  5570. 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);
  5571. };
  5572. /**
  5573. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5574. */
  5575. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5576. var matrix = Matrix.Zero();
  5577. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5578. return matrix;
  5579. };
  5580. /**
  5581. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5582. */
  5583. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5584. //alternatively this could be expressed as:
  5585. // m = PerspectiveFovLHToRef
  5586. // m[10] *= -1.0;
  5587. // m[11] *= -1.0;
  5588. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5589. var n = znear;
  5590. var f = zfar;
  5591. var t = 1.0 / (Math.tan(fov * 0.5));
  5592. var a = isVerticalFovFixed ? (t / aspect) : t;
  5593. var b = isVerticalFovFixed ? t : (t * aspect);
  5594. var c = -(f + n) / (f - n);
  5595. var d = -2 * f * n / (f - n);
  5596. 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);
  5597. };
  5598. /**
  5599. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5600. */
  5601. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5602. if (rightHanded === void 0) { rightHanded = false; }
  5603. var rightHandedFactor = rightHanded ? -1 : 1;
  5604. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5605. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5606. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5607. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5608. var xScale = 2.0 / (leftTan + rightTan);
  5609. var yScale = 2.0 / (upTan + downTan);
  5610. result.m[0] = xScale;
  5611. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5612. result.m[5] = yScale;
  5613. result.m[6] = result.m[7] = 0.0;
  5614. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5615. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5616. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5617. result.m[10] = -zfar / (znear - zfar);
  5618. result.m[11] = 1.0 * rightHandedFactor;
  5619. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5620. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5621. // result.m[14] = (znear * zfar) / (znear - zfar);
  5622. result._markAsUpdated();
  5623. };
  5624. /**
  5625. * Returns the final transformation matrix : world * view * projection * viewport
  5626. */
  5627. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5628. var cw = viewport.width;
  5629. var ch = viewport.height;
  5630. var cx = viewport.x;
  5631. var cy = viewport.y;
  5632. 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);
  5633. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5634. };
  5635. /**
  5636. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5637. */
  5638. Matrix.GetAsMatrix2x2 = function (matrix) {
  5639. return new Float32Array([
  5640. matrix.m[0], matrix.m[1],
  5641. matrix.m[4], matrix.m[5]
  5642. ]);
  5643. };
  5644. /**
  5645. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5646. */
  5647. Matrix.GetAsMatrix3x3 = function (matrix) {
  5648. return new Float32Array([
  5649. matrix.m[0], matrix.m[1], matrix.m[2],
  5650. matrix.m[4], matrix.m[5], matrix.m[6],
  5651. matrix.m[8], matrix.m[9], matrix.m[10]
  5652. ]);
  5653. };
  5654. /**
  5655. * Compute the transpose of the passed Matrix.
  5656. * Returns a new Matrix.
  5657. */
  5658. Matrix.Transpose = function (matrix) {
  5659. var result = new Matrix();
  5660. Matrix.TransposeToRef(matrix, result);
  5661. return result;
  5662. };
  5663. /**
  5664. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5665. */
  5666. Matrix.TransposeToRef = function (matrix, result) {
  5667. result.m[0] = matrix.m[0];
  5668. result.m[1] = matrix.m[4];
  5669. result.m[2] = matrix.m[8];
  5670. result.m[3] = matrix.m[12];
  5671. result.m[4] = matrix.m[1];
  5672. result.m[5] = matrix.m[5];
  5673. result.m[6] = matrix.m[9];
  5674. result.m[7] = matrix.m[13];
  5675. result.m[8] = matrix.m[2];
  5676. result.m[9] = matrix.m[6];
  5677. result.m[10] = matrix.m[10];
  5678. result.m[11] = matrix.m[14];
  5679. result.m[12] = matrix.m[3];
  5680. result.m[13] = matrix.m[7];
  5681. result.m[14] = matrix.m[11];
  5682. result.m[15] = matrix.m[15];
  5683. };
  5684. /**
  5685. * Returns a new Matrix as the reflection matrix across the passed plane.
  5686. */
  5687. Matrix.Reflection = function (plane) {
  5688. var matrix = new Matrix();
  5689. Matrix.ReflectionToRef(plane, matrix);
  5690. return matrix;
  5691. };
  5692. /**
  5693. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5694. */
  5695. Matrix.ReflectionToRef = function (plane, result) {
  5696. plane.normalize();
  5697. var x = plane.normal.x;
  5698. var y = plane.normal.y;
  5699. var z = plane.normal.z;
  5700. var temp = -2 * x;
  5701. var temp2 = -2 * y;
  5702. var temp3 = -2 * z;
  5703. result.m[0] = (temp * x) + 1;
  5704. result.m[1] = temp2 * x;
  5705. result.m[2] = temp3 * x;
  5706. result.m[3] = 0.0;
  5707. result.m[4] = temp * y;
  5708. result.m[5] = (temp2 * y) + 1;
  5709. result.m[6] = temp3 * y;
  5710. result.m[7] = 0.0;
  5711. result.m[8] = temp * z;
  5712. result.m[9] = temp2 * z;
  5713. result.m[10] = (temp3 * z) + 1;
  5714. result.m[11] = 0.0;
  5715. result.m[12] = temp * plane.d;
  5716. result.m[13] = temp2 * plane.d;
  5717. result.m[14] = temp3 * plane.d;
  5718. result.m[15] = 1.0;
  5719. result._markAsUpdated();
  5720. };
  5721. /**
  5722. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5723. */
  5724. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5725. result.m[0] = xaxis.x;
  5726. result.m[1] = xaxis.y;
  5727. result.m[2] = xaxis.z;
  5728. result.m[3] = 0.0;
  5729. result.m[4] = yaxis.x;
  5730. result.m[5] = yaxis.y;
  5731. result.m[6] = yaxis.z;
  5732. result.m[7] = 0.0;
  5733. result.m[8] = zaxis.x;
  5734. result.m[9] = zaxis.y;
  5735. result.m[10] = zaxis.z;
  5736. result.m[11] = 0.0;
  5737. result.m[12] = 0.0;
  5738. result.m[13] = 0.0;
  5739. result.m[14] = 0.0;
  5740. result.m[15] = 1.0;
  5741. result._markAsUpdated();
  5742. };
  5743. /**
  5744. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5745. */
  5746. Matrix.FromQuaternionToRef = function (quat, result) {
  5747. var xx = quat.x * quat.x;
  5748. var yy = quat.y * quat.y;
  5749. var zz = quat.z * quat.z;
  5750. var xy = quat.x * quat.y;
  5751. var zw = quat.z * quat.w;
  5752. var zx = quat.z * quat.x;
  5753. var yw = quat.y * quat.w;
  5754. var yz = quat.y * quat.z;
  5755. var xw = quat.x * quat.w;
  5756. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5757. result.m[1] = 2.0 * (xy + zw);
  5758. result.m[2] = 2.0 * (zx - yw);
  5759. result.m[3] = 0.0;
  5760. result.m[4] = 2.0 * (xy - zw);
  5761. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5762. result.m[6] = 2.0 * (yz + xw);
  5763. result.m[7] = 0.0;
  5764. result.m[8] = 2.0 * (zx + yw);
  5765. result.m[9] = 2.0 * (yz - xw);
  5766. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5767. result.m[11] = 0.0;
  5768. result.m[12] = 0.0;
  5769. result.m[13] = 0.0;
  5770. result.m[14] = 0.0;
  5771. result.m[15] = 1.0;
  5772. result._markAsUpdated();
  5773. };
  5774. Matrix._tempQuaternion = new Quaternion();
  5775. Matrix._xAxis = Vector3.Zero();
  5776. Matrix._yAxis = Vector3.Zero();
  5777. Matrix._zAxis = Vector3.Zero();
  5778. Matrix._updateFlagSeed = 0;
  5779. Matrix._identityReadOnly = Matrix.Identity();
  5780. return Matrix;
  5781. }());
  5782. BABYLON.Matrix = Matrix;
  5783. var Plane = /** @class */ (function () {
  5784. /**
  5785. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  5786. */
  5787. function Plane(a, b, c, d) {
  5788. this.normal = new Vector3(a, b, c);
  5789. this.d = d;
  5790. }
  5791. /**
  5792. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  5793. */
  5794. Plane.prototype.asArray = function () {
  5795. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  5796. };
  5797. // Methods
  5798. /**
  5799. * Returns a new plane copied from the current Plane.
  5800. */
  5801. Plane.prototype.clone = function () {
  5802. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  5803. };
  5804. /**
  5805. * Returns the string "Plane".
  5806. */
  5807. Plane.prototype.getClassName = function () {
  5808. return "Plane";
  5809. };
  5810. /**
  5811. * Returns the Plane hash code.
  5812. */
  5813. Plane.prototype.getHashCode = function () {
  5814. var hash = this.normal.getHashCode();
  5815. hash = (hash * 397) ^ (this.d || 0);
  5816. return hash;
  5817. };
  5818. /**
  5819. * Normalize the current Plane in place.
  5820. * Returns the updated Plane.
  5821. */
  5822. Plane.prototype.normalize = function () {
  5823. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  5824. var magnitude = 0.0;
  5825. if (norm !== 0) {
  5826. magnitude = 1.0 / norm;
  5827. }
  5828. this.normal.x *= magnitude;
  5829. this.normal.y *= magnitude;
  5830. this.normal.z *= magnitude;
  5831. this.d *= magnitude;
  5832. return this;
  5833. };
  5834. /**
  5835. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  5836. */
  5837. Plane.prototype.transform = function (transformation) {
  5838. var transposedMatrix = Matrix.Transpose(transformation);
  5839. var x = this.normal.x;
  5840. var y = this.normal.y;
  5841. var z = this.normal.z;
  5842. var d = this.d;
  5843. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  5844. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  5845. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  5846. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  5847. return new Plane(normalX, normalY, normalZ, finalD);
  5848. };
  5849. /**
  5850. * Returns the dot product (float) of the point coordinates and the plane normal.
  5851. */
  5852. Plane.prototype.dotCoordinate = function (point) {
  5853. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  5854. };
  5855. /**
  5856. * Updates the current Plane from the plane defined by the three passed points.
  5857. * Returns the updated Plane.
  5858. */
  5859. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  5860. var x1 = point2.x - point1.x;
  5861. var y1 = point2.y - point1.y;
  5862. var z1 = point2.z - point1.z;
  5863. var x2 = point3.x - point1.x;
  5864. var y2 = point3.y - point1.y;
  5865. var z2 = point3.z - point1.z;
  5866. var yz = (y1 * z2) - (z1 * y2);
  5867. var xz = (z1 * x2) - (x1 * z2);
  5868. var xy = (x1 * y2) - (y1 * x2);
  5869. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  5870. var invPyth;
  5871. if (pyth !== 0) {
  5872. invPyth = 1.0 / pyth;
  5873. }
  5874. else {
  5875. invPyth = 0.0;
  5876. }
  5877. this.normal.x = yz * invPyth;
  5878. this.normal.y = xz * invPyth;
  5879. this.normal.z = xy * invPyth;
  5880. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  5881. return this;
  5882. };
  5883. /**
  5884. * Boolean : True is the vector "direction" is the same side than the plane normal.
  5885. */
  5886. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  5887. var dot = Vector3.Dot(this.normal, direction);
  5888. return (dot <= epsilon);
  5889. };
  5890. /**
  5891. * Returns the signed distance (float) from the passed point to the Plane.
  5892. */
  5893. Plane.prototype.signedDistanceTo = function (point) {
  5894. return Vector3.Dot(point, this.normal) + this.d;
  5895. };
  5896. // Statics
  5897. /**
  5898. * Returns a new Plane from the passed array.
  5899. */
  5900. Plane.FromArray = function (array) {
  5901. return new Plane(array[0], array[1], array[2], array[3]);
  5902. };
  5903. /**
  5904. * Returns a new Plane defined by the three passed points.
  5905. */
  5906. Plane.FromPoints = function (point1, point2, point3) {
  5907. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5908. result.copyFromPoints(point1, point2, point3);
  5909. return result;
  5910. };
  5911. /**
  5912. * Returns a new Plane the normal vector to this plane at the passed origin point.
  5913. * Note : the vector "normal" is updated because normalized.
  5914. */
  5915. Plane.FromPositionAndNormal = function (origin, normal) {
  5916. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  5917. normal.normalize();
  5918. result.normal = normal;
  5919. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5920. return result;
  5921. };
  5922. /**
  5923. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  5924. */
  5925. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  5926. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  5927. return Vector3.Dot(point, normal) + d;
  5928. };
  5929. return Plane;
  5930. }());
  5931. BABYLON.Plane = Plane;
  5932. var Viewport = /** @class */ (function () {
  5933. /**
  5934. * Creates a Viewport object located at (x, y) and sized (width, height).
  5935. */
  5936. function Viewport(x, y, width, height) {
  5937. this.x = x;
  5938. this.y = y;
  5939. this.width = width;
  5940. this.height = height;
  5941. }
  5942. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  5943. if (renderWidthOrEngine.getRenderWidth) {
  5944. var engine = renderWidthOrEngine;
  5945. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  5946. }
  5947. var renderWidth = renderWidthOrEngine;
  5948. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  5949. };
  5950. /**
  5951. * Returns a new Viewport copied from the current one.
  5952. */
  5953. Viewport.prototype.clone = function () {
  5954. return new Viewport(this.x, this.y, this.width, this.height);
  5955. };
  5956. return Viewport;
  5957. }());
  5958. BABYLON.Viewport = Viewport;
  5959. var Frustum = /** @class */ (function () {
  5960. function Frustum() {
  5961. }
  5962. /**
  5963. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  5964. */
  5965. Frustum.GetPlanes = function (transform) {
  5966. var frustumPlanes = [];
  5967. for (var index = 0; index < 6; index++) {
  5968. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  5969. }
  5970. Frustum.GetPlanesToRef(transform, frustumPlanes);
  5971. return frustumPlanes;
  5972. };
  5973. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  5974. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  5975. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  5976. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  5977. frustumPlane.d = transform.m[15] + transform.m[14];
  5978. frustumPlane.normalize();
  5979. };
  5980. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  5981. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  5982. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  5983. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  5984. frustumPlane.d = transform.m[15] - transform.m[14];
  5985. frustumPlane.normalize();
  5986. };
  5987. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  5988. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  5989. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  5990. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  5991. frustumPlane.d = transform.m[15] + transform.m[12];
  5992. frustumPlane.normalize();
  5993. };
  5994. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  5995. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  5996. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  5997. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  5998. frustumPlane.d = transform.m[15] - transform.m[12];
  5999. frustumPlane.normalize();
  6000. };
  6001. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6002. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6003. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6004. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6005. frustumPlane.d = transform.m[15] - transform.m[13];
  6006. frustumPlane.normalize();
  6007. };
  6008. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6009. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6010. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6011. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6012. frustumPlane.d = transform.m[15] + transform.m[13];
  6013. frustumPlane.normalize();
  6014. };
  6015. /**
  6016. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6017. */
  6018. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6019. // Near
  6020. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6021. // Far
  6022. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6023. // Left
  6024. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6025. // Right
  6026. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6027. // Top
  6028. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6029. // Bottom
  6030. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6031. };
  6032. return Frustum;
  6033. }());
  6034. BABYLON.Frustum = Frustum;
  6035. var Space;
  6036. (function (Space) {
  6037. Space[Space["LOCAL"] = 0] = "LOCAL";
  6038. Space[Space["WORLD"] = 1] = "WORLD";
  6039. Space[Space["BONE"] = 2] = "BONE";
  6040. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6041. var Axis = /** @class */ (function () {
  6042. function Axis() {
  6043. }
  6044. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6045. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6046. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6047. return Axis;
  6048. }());
  6049. BABYLON.Axis = Axis;
  6050. ;
  6051. var BezierCurve = /** @class */ (function () {
  6052. function BezierCurve() {
  6053. }
  6054. /**
  6055. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6056. */
  6057. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6058. // Extract X (which is equal to time here)
  6059. var f0 = 1 - 3 * x2 + 3 * x1;
  6060. var f1 = 3 * x2 - 6 * x1;
  6061. var f2 = 3 * x1;
  6062. var refinedT = t;
  6063. for (var i = 0; i < 5; i++) {
  6064. var refinedT2 = refinedT * refinedT;
  6065. var refinedT3 = refinedT2 * refinedT;
  6066. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6067. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6068. refinedT -= (x - t) * slope;
  6069. refinedT = Math.min(1, Math.max(0, refinedT));
  6070. }
  6071. // Resolve cubic bezier for the given x
  6072. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6073. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6074. Math.pow(refinedT, 3);
  6075. };
  6076. return BezierCurve;
  6077. }());
  6078. BABYLON.BezierCurve = BezierCurve;
  6079. var Orientation;
  6080. (function (Orientation) {
  6081. Orientation[Orientation["CW"] = 0] = "CW";
  6082. Orientation[Orientation["CCW"] = 1] = "CCW";
  6083. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6084. var Angle = /** @class */ (function () {
  6085. /**
  6086. * Creates an Angle object of "radians" radians (float).
  6087. */
  6088. function Angle(radians) {
  6089. var _this = this;
  6090. /**
  6091. * Returns the Angle value in degrees (float).
  6092. */
  6093. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6094. /**
  6095. * Returns the Angle value in radians (float).
  6096. */
  6097. this.radians = function () { return _this._radians; };
  6098. this._radians = radians;
  6099. if (this._radians < 0.0)
  6100. this._radians += (2.0 * Math.PI);
  6101. }
  6102. /**
  6103. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6104. */
  6105. Angle.BetweenTwoPoints = function (a, b) {
  6106. var delta = b.subtract(a);
  6107. var theta = Math.atan2(delta.y, delta.x);
  6108. return new Angle(theta);
  6109. };
  6110. /**
  6111. * Returns a new Angle object from the passed float in radians.
  6112. */
  6113. Angle.FromRadians = function (radians) {
  6114. return new Angle(radians);
  6115. };
  6116. /**
  6117. * Returns a new Angle object from the passed float in degrees.
  6118. */
  6119. Angle.FromDegrees = function (degrees) {
  6120. return new Angle(degrees * Math.PI / 180.0);
  6121. };
  6122. return Angle;
  6123. }());
  6124. BABYLON.Angle = Angle;
  6125. var Arc2 = /** @class */ (function () {
  6126. /**
  6127. * Creates an Arc object from the three passed points : start, middle and end.
  6128. */
  6129. function Arc2(startPoint, midPoint, endPoint) {
  6130. this.startPoint = startPoint;
  6131. this.midPoint = midPoint;
  6132. this.endPoint = endPoint;
  6133. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6134. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6135. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6136. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6137. 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);
  6138. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6139. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6140. var a1 = this.startAngle.degrees();
  6141. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6142. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6143. // angles correction
  6144. if (a2 - a1 > +180.0)
  6145. a2 -= 360.0;
  6146. if (a2 - a1 < -180.0)
  6147. a2 += 360.0;
  6148. if (a3 - a2 > +180.0)
  6149. a3 -= 360.0;
  6150. if (a3 - a2 < -180.0)
  6151. a3 += 360.0;
  6152. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6153. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6154. }
  6155. return Arc2;
  6156. }());
  6157. BABYLON.Arc2 = Arc2;
  6158. var Path2 = /** @class */ (function () {
  6159. /**
  6160. * Creates a Path2 object from the starting 2D coordinates x and y.
  6161. */
  6162. function Path2(x, y) {
  6163. this._points = new Array();
  6164. this._length = 0.0;
  6165. this.closed = false;
  6166. this._points.push(new Vector2(x, y));
  6167. }
  6168. /**
  6169. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6170. * Returns the updated Path2.
  6171. */
  6172. Path2.prototype.addLineTo = function (x, y) {
  6173. if (this.closed) {
  6174. return this;
  6175. }
  6176. var newPoint = new Vector2(x, y);
  6177. var previousPoint = this._points[this._points.length - 1];
  6178. this._points.push(newPoint);
  6179. this._length += newPoint.subtract(previousPoint).length();
  6180. return this;
  6181. };
  6182. /**
  6183. * 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.
  6184. * Returns the updated Path2.
  6185. */
  6186. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6187. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6188. if (this.closed) {
  6189. return this;
  6190. }
  6191. var startPoint = this._points[this._points.length - 1];
  6192. var midPoint = new Vector2(midX, midY);
  6193. var endPoint = new Vector2(endX, endY);
  6194. var arc = new Arc2(startPoint, midPoint, endPoint);
  6195. var increment = arc.angle.radians() / numberOfSegments;
  6196. if (arc.orientation === Orientation.CW)
  6197. increment *= -1;
  6198. var currentAngle = arc.startAngle.radians() + increment;
  6199. for (var i = 0; i < numberOfSegments; i++) {
  6200. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6201. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6202. this.addLineTo(x, y);
  6203. currentAngle += increment;
  6204. }
  6205. return this;
  6206. };
  6207. /**
  6208. * Closes the Path2.
  6209. * Returns the Path2.
  6210. */
  6211. Path2.prototype.close = function () {
  6212. this.closed = true;
  6213. return this;
  6214. };
  6215. /**
  6216. * Returns the Path2 total length (float).
  6217. */
  6218. Path2.prototype.length = function () {
  6219. var result = this._length;
  6220. if (!this.closed) {
  6221. var lastPoint = this._points[this._points.length - 1];
  6222. var firstPoint = this._points[0];
  6223. result += (firstPoint.subtract(lastPoint).length());
  6224. }
  6225. return result;
  6226. };
  6227. /**
  6228. * Returns the Path2 internal array of points.
  6229. */
  6230. Path2.prototype.getPoints = function () {
  6231. return this._points;
  6232. };
  6233. /**
  6234. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6235. */
  6236. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6237. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6238. return Vector2.Zero();
  6239. }
  6240. var lengthPosition = normalizedLengthPosition * this.length();
  6241. var previousOffset = 0;
  6242. for (var i = 0; i < this._points.length; i++) {
  6243. var j = (i + 1) % this._points.length;
  6244. var a = this._points[i];
  6245. var b = this._points[j];
  6246. var bToA = b.subtract(a);
  6247. var nextOffset = (bToA.length() + previousOffset);
  6248. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6249. var dir = bToA.normalize();
  6250. var localOffset = lengthPosition - previousOffset;
  6251. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6252. }
  6253. previousOffset = nextOffset;
  6254. }
  6255. return Vector2.Zero();
  6256. };
  6257. /**
  6258. * Returns a new Path2 starting at the coordinates (x, y).
  6259. */
  6260. Path2.StartingAt = function (x, y) {
  6261. return new Path2(x, y);
  6262. };
  6263. return Path2;
  6264. }());
  6265. BABYLON.Path2 = Path2;
  6266. var Path3D = /** @class */ (function () {
  6267. /**
  6268. * new Path3D(path, normal, raw)
  6269. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6270. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6271. * path : an array of Vector3, the curve axis of the Path3D
  6272. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6273. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6274. */
  6275. function Path3D(path, firstNormal, raw) {
  6276. if (firstNormal === void 0) { firstNormal = null; }
  6277. this.path = path;
  6278. this._curve = new Array();
  6279. this._distances = new Array();
  6280. this._tangents = new Array();
  6281. this._normals = new Array();
  6282. this._binormals = new Array();
  6283. for (var p = 0; p < path.length; p++) {
  6284. this._curve[p] = path[p].clone(); // hard copy
  6285. }
  6286. this._raw = raw || false;
  6287. this._compute(firstNormal);
  6288. }
  6289. /**
  6290. * Returns the Path3D array of successive Vector3 designing its curve.
  6291. */
  6292. Path3D.prototype.getCurve = function () {
  6293. return this._curve;
  6294. };
  6295. /**
  6296. * Returns an array populated with tangent vectors on each Path3D curve point.
  6297. */
  6298. Path3D.prototype.getTangents = function () {
  6299. return this._tangents;
  6300. };
  6301. /**
  6302. * Returns an array populated with normal vectors on each Path3D curve point.
  6303. */
  6304. Path3D.prototype.getNormals = function () {
  6305. return this._normals;
  6306. };
  6307. /**
  6308. * Returns an array populated with binormal vectors on each Path3D curve point.
  6309. */
  6310. Path3D.prototype.getBinormals = function () {
  6311. return this._binormals;
  6312. };
  6313. /**
  6314. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6315. */
  6316. Path3D.prototype.getDistances = function () {
  6317. return this._distances;
  6318. };
  6319. /**
  6320. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6321. * Returns the same object updated.
  6322. */
  6323. Path3D.prototype.update = function (path, firstNormal) {
  6324. if (firstNormal === void 0) { firstNormal = null; }
  6325. for (var p = 0; p < path.length; p++) {
  6326. this._curve[p].x = path[p].x;
  6327. this._curve[p].y = path[p].y;
  6328. this._curve[p].z = path[p].z;
  6329. }
  6330. this._compute(firstNormal);
  6331. return this;
  6332. };
  6333. // private function compute() : computes tangents, normals and binormals
  6334. Path3D.prototype._compute = function (firstNormal) {
  6335. var l = this._curve.length;
  6336. // first and last tangents
  6337. this._tangents[0] = this._getFirstNonNullVector(0);
  6338. if (!this._raw) {
  6339. this._tangents[0].normalize();
  6340. }
  6341. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6342. if (!this._raw) {
  6343. this._tangents[l - 1].normalize();
  6344. }
  6345. // normals and binormals at first point : arbitrary vector with _normalVector()
  6346. var tg0 = this._tangents[0];
  6347. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6348. this._normals[0] = pp0;
  6349. if (!this._raw) {
  6350. this._normals[0].normalize();
  6351. }
  6352. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6353. if (!this._raw) {
  6354. this._binormals[0].normalize();
  6355. }
  6356. this._distances[0] = 0.0;
  6357. // normals and binormals : next points
  6358. var prev; // previous vector (segment)
  6359. var cur; // current vector (segment)
  6360. var curTang; // current tangent
  6361. // previous normal
  6362. var prevBinor; // previous binormal
  6363. for (var i = 1; i < l; i++) {
  6364. // tangents
  6365. prev = this._getLastNonNullVector(i);
  6366. if (i < l - 1) {
  6367. cur = this._getFirstNonNullVector(i);
  6368. this._tangents[i] = prev.add(cur);
  6369. this._tangents[i].normalize();
  6370. }
  6371. this._distances[i] = this._distances[i - 1] + prev.length();
  6372. // normals and binormals
  6373. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6374. curTang = this._tangents[i];
  6375. prevBinor = this._binormals[i - 1];
  6376. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6377. if (!this._raw) {
  6378. this._normals[i].normalize();
  6379. }
  6380. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6381. if (!this._raw) {
  6382. this._binormals[i].normalize();
  6383. }
  6384. }
  6385. };
  6386. // private function getFirstNonNullVector(index)
  6387. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6388. Path3D.prototype._getFirstNonNullVector = function (index) {
  6389. var i = 1;
  6390. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6391. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6392. i++;
  6393. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6394. }
  6395. return nNVector;
  6396. };
  6397. // private function getLastNonNullVector(index)
  6398. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6399. Path3D.prototype._getLastNonNullVector = function (index) {
  6400. var i = 1;
  6401. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6402. while (nLVector.length() === 0 && index > i + 1) {
  6403. i++;
  6404. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6405. }
  6406. return nLVector;
  6407. };
  6408. // private function normalVector(v0, vt, va) :
  6409. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6410. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6411. Path3D.prototype._normalVector = function (v0, vt, va) {
  6412. var normal0;
  6413. var tgl = vt.length();
  6414. if (tgl === 0.0) {
  6415. tgl = 1.0;
  6416. }
  6417. if (va === undefined || va === null) {
  6418. var point;
  6419. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6420. point = new Vector3(0.0, -1.0, 0.0);
  6421. }
  6422. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6423. point = new Vector3(1.0, 0.0, 0.0);
  6424. }
  6425. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6426. point = new Vector3(0.0, 0.0, 1.0);
  6427. }
  6428. else {
  6429. point = Vector3.Zero();
  6430. }
  6431. normal0 = Vector3.Cross(vt, point);
  6432. }
  6433. else {
  6434. normal0 = Vector3.Cross(vt, va);
  6435. Vector3.CrossToRef(normal0, vt, normal0);
  6436. }
  6437. normal0.normalize();
  6438. return normal0;
  6439. };
  6440. return Path3D;
  6441. }());
  6442. BABYLON.Path3D = Path3D;
  6443. var Curve3 = /** @class */ (function () {
  6444. /**
  6445. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6446. * A Curve3 is designed from a series of successive Vector3.
  6447. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6448. */
  6449. function Curve3(points) {
  6450. this._length = 0.0;
  6451. this._points = points;
  6452. this._length = this._computeLength(points);
  6453. }
  6454. /**
  6455. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6456. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6457. * @param v1 (Vector3) the control point
  6458. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6459. * @param nbPoints (integer) the wanted number of points in the curve
  6460. */
  6461. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6462. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6463. var bez = new Array();
  6464. var equation = function (t, val0, val1, val2) {
  6465. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6466. return res;
  6467. };
  6468. for (var i = 0; i <= nbPoints; i++) {
  6469. 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)));
  6470. }
  6471. return new Curve3(bez);
  6472. };
  6473. /**
  6474. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6475. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6476. * @param v1 (Vector3) the first control point
  6477. * @param v2 (Vector3) the second control point
  6478. * @param v3 (Vector3) the end point of the Cubic Bezier
  6479. * @param nbPoints (integer) the wanted number of points in the curve
  6480. */
  6481. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6482. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6483. var bez = new Array();
  6484. var equation = function (t, val0, val1, val2, val3) {
  6485. 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;
  6486. return res;
  6487. };
  6488. for (var i = 0; i <= nbPoints; i++) {
  6489. 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)));
  6490. }
  6491. return new Curve3(bez);
  6492. };
  6493. /**
  6494. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6495. * @param p1 (Vector3) the origin point of the Hermite Spline
  6496. * @param t1 (Vector3) the tangent vector at the origin point
  6497. * @param p2 (Vector3) the end point of the Hermite Spline
  6498. * @param t2 (Vector3) the tangent vector at the end point
  6499. * @param nbPoints (integer) the wanted number of points in the curve
  6500. */
  6501. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6502. var hermite = new Array();
  6503. var step = 1.0 / nbPoints;
  6504. for (var i = 0; i <= nbPoints; i++) {
  6505. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6506. }
  6507. return new Curve3(hermite);
  6508. };
  6509. /**
  6510. * Returns a Curve3 object along a CatmullRom Spline curve :
  6511. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6512. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6513. */
  6514. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6515. var totalPoints = new Array();
  6516. totalPoints.push(points[0].clone());
  6517. Array.prototype.push.apply(totalPoints, points);
  6518. totalPoints.push(points[points.length - 1].clone());
  6519. var catmullRom = new Array();
  6520. var step = 1.0 / nbPoints;
  6521. var amount = 0.0;
  6522. for (var i = 0; i < totalPoints.length - 3; i++) {
  6523. amount = 0;
  6524. for (var c = 0; c < nbPoints; c++) {
  6525. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6526. amount += step;
  6527. }
  6528. }
  6529. i--;
  6530. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6531. return new Curve3(catmullRom);
  6532. };
  6533. /**
  6534. * Returns the Curve3 stored array of successive Vector3
  6535. */
  6536. Curve3.prototype.getPoints = function () {
  6537. return this._points;
  6538. };
  6539. /**
  6540. * Returns the computed length (float) of the curve.
  6541. */
  6542. Curve3.prototype.length = function () {
  6543. return this._length;
  6544. };
  6545. /**
  6546. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6547. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6548. * curveA and curveB keep unchanged.
  6549. */
  6550. Curve3.prototype.continue = function (curve) {
  6551. var lastPoint = this._points[this._points.length - 1];
  6552. var continuedPoints = this._points.slice();
  6553. var curvePoints = curve.getPoints();
  6554. for (var i = 1; i < curvePoints.length; i++) {
  6555. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6556. }
  6557. var continuedCurve = new Curve3(continuedPoints);
  6558. return continuedCurve;
  6559. };
  6560. Curve3.prototype._computeLength = function (path) {
  6561. var l = 0;
  6562. for (var i = 1; i < path.length; i++) {
  6563. l += (path[i].subtract(path[i - 1])).length();
  6564. }
  6565. return l;
  6566. };
  6567. return Curve3;
  6568. }());
  6569. BABYLON.Curve3 = Curve3;
  6570. // Vertex formats
  6571. var PositionNormalVertex = /** @class */ (function () {
  6572. function PositionNormalVertex(position, normal) {
  6573. if (position === void 0) { position = Vector3.Zero(); }
  6574. if (normal === void 0) { normal = Vector3.Up(); }
  6575. this.position = position;
  6576. this.normal = normal;
  6577. }
  6578. PositionNormalVertex.prototype.clone = function () {
  6579. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6580. };
  6581. return PositionNormalVertex;
  6582. }());
  6583. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6584. var PositionNormalTextureVertex = /** @class */ (function () {
  6585. function PositionNormalTextureVertex(position, normal, uv) {
  6586. if (position === void 0) { position = Vector3.Zero(); }
  6587. if (normal === void 0) { normal = Vector3.Up(); }
  6588. if (uv === void 0) { uv = Vector2.Zero(); }
  6589. this.position = position;
  6590. this.normal = normal;
  6591. this.uv = uv;
  6592. }
  6593. PositionNormalTextureVertex.prototype.clone = function () {
  6594. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6595. };
  6596. return PositionNormalTextureVertex;
  6597. }());
  6598. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6599. // Temporary pre-allocated objects for engine internal use
  6600. // usage in any internal function :
  6601. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6602. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6603. var Tmp = /** @class */ (function () {
  6604. function Tmp() {
  6605. }
  6606. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6607. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6608. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6609. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6610. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6611. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6612. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6613. Matrix.Zero(), Matrix.Zero(),
  6614. Matrix.Zero(), Matrix.Zero(),
  6615. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6616. return Tmp;
  6617. }());
  6618. BABYLON.Tmp = Tmp;
  6619. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6620. var MathTmp = /** @class */ (function () {
  6621. function MathTmp() {
  6622. }
  6623. MathTmp.Vector3 = [Vector3.Zero()];
  6624. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6625. MathTmp.Quaternion = [Quaternion.Zero()];
  6626. return MathTmp;
  6627. }());
  6628. })(BABYLON || (BABYLON = {}));
  6629. //# sourceMappingURL=babylon.math.js.map
  6630. var BABYLON;
  6631. (function (BABYLON) {
  6632. var Scalar = /** @class */ (function () {
  6633. function Scalar() {
  6634. }
  6635. /**
  6636. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6637. */
  6638. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6639. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6640. var num = a - b;
  6641. return -epsilon <= num && num <= epsilon;
  6642. };
  6643. /**
  6644. * Returns a string : the upper case translation of the number i to hexadecimal.
  6645. */
  6646. Scalar.ToHex = function (i) {
  6647. var str = i.toString(16);
  6648. if (i <= 15) {
  6649. return ("0" + str).toUpperCase();
  6650. }
  6651. return str.toUpperCase();
  6652. };
  6653. /**
  6654. * Returns -1 if value is negative and +1 is value is positive.
  6655. * Returns the value itself if it's equal to zero.
  6656. */
  6657. Scalar.Sign = function (value) {
  6658. value = +value; // convert to a number
  6659. if (value === 0 || isNaN(value))
  6660. return value;
  6661. return value > 0 ? 1 : -1;
  6662. };
  6663. /**
  6664. * Returns the value itself if it's between min and max.
  6665. * Returns min if the value is lower than min.
  6666. * Returns max if the value is greater than max.
  6667. */
  6668. Scalar.Clamp = function (value, min, max) {
  6669. if (min === void 0) { min = 0; }
  6670. if (max === void 0) { max = 1; }
  6671. return Math.min(max, Math.max(min, value));
  6672. };
  6673. /**
  6674. * Returns the log2 of value.
  6675. */
  6676. Scalar.Log2 = function (value) {
  6677. return Math.log(value) * Math.LOG2E;
  6678. };
  6679. /**
  6680. * Loops the value, so that it is never larger than length and never smaller than 0.
  6681. *
  6682. * This is similar to the modulo operator but it works with floating point numbers.
  6683. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6684. * With t = 5 and length = 2.5, the result would be 0.0.
  6685. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6686. */
  6687. Scalar.Repeat = function (value, length) {
  6688. return value - Math.floor(value / length) * length;
  6689. };
  6690. /**
  6691. * Normalize the value between 0.0 and 1.0 using min and max values
  6692. */
  6693. Scalar.Normalize = function (value, min, max) {
  6694. return (value - min) / (max - min);
  6695. };
  6696. /**
  6697. * Denormalize the value from 0.0 and 1.0 using min and max values
  6698. */
  6699. Scalar.Denormalize = function (normalized, min, max) {
  6700. return (normalized * (max - min) + min);
  6701. };
  6702. /**
  6703. * Calculates the shortest difference between two given angles given in degrees.
  6704. */
  6705. Scalar.DeltaAngle = function (current, target) {
  6706. var num = Scalar.Repeat(target - current, 360.0);
  6707. if (num > 180.0) {
  6708. num -= 360.0;
  6709. }
  6710. return num;
  6711. };
  6712. /**
  6713. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6714. *
  6715. * The returned value will move back and forth between 0 and length
  6716. */
  6717. Scalar.PingPong = function (tx, length) {
  6718. var t = Scalar.Repeat(tx, length * 2.0);
  6719. return length - Math.abs(t - length);
  6720. };
  6721. /**
  6722. * Interpolates between min and max with smoothing at the limits.
  6723. *
  6724. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6725. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6726. */
  6727. Scalar.SmoothStep = function (from, to, tx) {
  6728. var t = Scalar.Clamp(tx);
  6729. t = -2.0 * t * t * t + 3.0 * t * t;
  6730. return to * t + from * (1.0 - t);
  6731. };
  6732. /**
  6733. * Moves a value current towards target.
  6734. *
  6735. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6736. * Negative values of maxDelta pushes the value away from target.
  6737. */
  6738. Scalar.MoveTowards = function (current, target, maxDelta) {
  6739. var result = 0;
  6740. if (Math.abs(target - current) <= maxDelta) {
  6741. result = target;
  6742. }
  6743. else {
  6744. result = current + Scalar.Sign(target - current) * maxDelta;
  6745. }
  6746. return result;
  6747. };
  6748. /**
  6749. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6750. *
  6751. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6752. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6753. */
  6754. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  6755. var num = Scalar.DeltaAngle(current, target);
  6756. var result = 0;
  6757. if (-maxDelta < num && num < maxDelta) {
  6758. result = target;
  6759. }
  6760. else {
  6761. target = current + num;
  6762. result = Scalar.MoveTowards(current, target, maxDelta);
  6763. }
  6764. return result;
  6765. };
  6766. /**
  6767. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  6768. */
  6769. Scalar.Lerp = function (start, end, amount) {
  6770. return start + ((end - start) * amount);
  6771. };
  6772. /**
  6773. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6774. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  6775. */
  6776. Scalar.LerpAngle = function (start, end, amount) {
  6777. var num = Scalar.Repeat(end - start, 360.0);
  6778. if (num > 180.0) {
  6779. num -= 360.0;
  6780. }
  6781. return start + num * Scalar.Clamp(amount);
  6782. };
  6783. /**
  6784. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  6785. */
  6786. Scalar.InverseLerp = function (a, b, value) {
  6787. var result = 0;
  6788. if (a != b) {
  6789. result = Scalar.Clamp((value - a) / (b - a));
  6790. }
  6791. else {
  6792. result = 0.0;
  6793. }
  6794. return result;
  6795. };
  6796. /**
  6797. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  6798. */
  6799. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  6800. var squared = amount * amount;
  6801. var cubed = amount * squared;
  6802. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  6803. var part2 = (-2.0 * cubed) + (3.0 * squared);
  6804. var part3 = (cubed - (2.0 * squared)) + amount;
  6805. var part4 = cubed - squared;
  6806. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  6807. };
  6808. /**
  6809. * Returns a random float number between and min and max values
  6810. */
  6811. Scalar.RandomRange = function (min, max) {
  6812. if (min === max)
  6813. return min;
  6814. return ((Math.random() * (max - min)) + min);
  6815. };
  6816. /**
  6817. * This function returns percentage of a number in a given range.
  6818. *
  6819. * RangeToPercent(40,20,60) will return 0.5 (50%)
  6820. * RangeToPercent(34,0,100) will return 0.34 (34%)
  6821. */
  6822. Scalar.RangeToPercent = function (number, min, max) {
  6823. return ((number - min) / (max - min));
  6824. };
  6825. /**
  6826. * This function returns number that corresponds to the percentage in a given range.
  6827. *
  6828. * PercentToRange(0.34,0,100) will return 34.
  6829. */
  6830. Scalar.PercentToRange = function (percent, min, max) {
  6831. return ((max - min) * percent + min);
  6832. };
  6833. /**
  6834. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  6835. * @param angle The angle to normalize in radian.
  6836. * @return The converted angle.
  6837. */
  6838. Scalar.NormalizeRadians = function (angle) {
  6839. // More precise but slower version kept for reference.
  6840. // angle = angle % Tools.TwoPi;
  6841. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  6842. //if (angle > Math.PI) {
  6843. // angle -= Tools.TwoPi;
  6844. //}
  6845. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  6846. return angle;
  6847. };
  6848. /**
  6849. * Two pi constants convenient for computation.
  6850. */
  6851. Scalar.TwoPi = Math.PI * 2;
  6852. return Scalar;
  6853. }());
  6854. BABYLON.Scalar = Scalar;
  6855. })(BABYLON || (BABYLON = {}));
  6856. //# sourceMappingURL=babylon.math.scalar.js.map
  6857. //# sourceMappingURL=babylon.mixins.js.map
  6858. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  6859. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  6860. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  6861. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  6862. //# sourceMappingURL=babylon.webgl2.js.map
  6863. var BABYLON;
  6864. (function (BABYLON) {
  6865. var __decoratorInitialStore = {};
  6866. var __mergedStore = {};
  6867. var _copySource = function (creationFunction, source, instanciate) {
  6868. var destination = creationFunction();
  6869. // Tags
  6870. if (BABYLON.Tags) {
  6871. BABYLON.Tags.AddTagsTo(destination, source.tags);
  6872. }
  6873. var classStore = getMergedStore(destination);
  6874. // Properties
  6875. for (var property in classStore) {
  6876. var propertyDescriptor = classStore[property];
  6877. var sourceProperty = source[property];
  6878. var propertyType = propertyDescriptor.type;
  6879. if (sourceProperty !== undefined && sourceProperty !== null) {
  6880. switch (propertyType) {
  6881. case 0: // Value
  6882. case 6:// Mesh reference
  6883. destination[property] = sourceProperty;
  6884. break;
  6885. case 1:// Texture
  6886. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  6887. break;
  6888. case 2: // Color3
  6889. case 3: // FresnelParameters
  6890. case 4: // Vector2
  6891. case 5: // Vector3
  6892. case 7: // Color Curves
  6893. case 10:// Quaternion
  6894. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  6895. break;
  6896. }
  6897. }
  6898. }
  6899. return destination;
  6900. };
  6901. function getDirectStore(target) {
  6902. var classKey = target.getClassName();
  6903. if (!__decoratorInitialStore[classKey]) {
  6904. __decoratorInitialStore[classKey] = {};
  6905. }
  6906. return __decoratorInitialStore[classKey];
  6907. }
  6908. /**
  6909. * Return the list of properties flagged as serializable
  6910. * @param target: host object
  6911. */
  6912. function getMergedStore(target) {
  6913. var classKey = target.getClassName();
  6914. if (__mergedStore[classKey]) {
  6915. return __mergedStore[classKey];
  6916. }
  6917. __mergedStore[classKey] = {};
  6918. var store = __mergedStore[classKey];
  6919. var currentTarget = target;
  6920. var currentKey = classKey;
  6921. while (currentKey) {
  6922. var initialStore = __decoratorInitialStore[currentKey];
  6923. for (var property in initialStore) {
  6924. store[property] = initialStore[property];
  6925. }
  6926. var parent_1 = void 0;
  6927. var done = false;
  6928. do {
  6929. parent_1 = Object.getPrototypeOf(currentTarget);
  6930. if (!parent_1.getClassName) {
  6931. done = true;
  6932. break;
  6933. }
  6934. if (parent_1.getClassName() !== currentKey) {
  6935. break;
  6936. }
  6937. currentTarget = parent_1;
  6938. } while (parent_1);
  6939. if (done) {
  6940. break;
  6941. }
  6942. currentKey = parent_1.getClassName();
  6943. currentTarget = parent_1;
  6944. }
  6945. return store;
  6946. }
  6947. function generateSerializableMember(type, sourceName) {
  6948. return function (target, propertyKey) {
  6949. var classStore = getDirectStore(target);
  6950. if (!classStore[propertyKey]) {
  6951. classStore[propertyKey] = { type: type, sourceName: sourceName };
  6952. }
  6953. };
  6954. }
  6955. function generateExpandMember(setCallback, targetKey) {
  6956. if (targetKey === void 0) { targetKey = null; }
  6957. return function (target, propertyKey) {
  6958. var key = targetKey || ("_" + propertyKey);
  6959. Object.defineProperty(target, propertyKey, {
  6960. get: function () {
  6961. return this[key];
  6962. },
  6963. set: function (value) {
  6964. if (this[key] === value) {
  6965. return;
  6966. }
  6967. this[key] = value;
  6968. target[setCallback].apply(this);
  6969. },
  6970. enumerable: true,
  6971. configurable: true
  6972. });
  6973. };
  6974. }
  6975. function expandToProperty(callback, targetKey) {
  6976. if (targetKey === void 0) { targetKey = null; }
  6977. return generateExpandMember(callback, targetKey);
  6978. }
  6979. BABYLON.expandToProperty = expandToProperty;
  6980. function serialize(sourceName) {
  6981. return generateSerializableMember(0, sourceName); // value member
  6982. }
  6983. BABYLON.serialize = serialize;
  6984. function serializeAsTexture(sourceName) {
  6985. return generateSerializableMember(1, sourceName); // texture member
  6986. }
  6987. BABYLON.serializeAsTexture = serializeAsTexture;
  6988. function serializeAsColor3(sourceName) {
  6989. return generateSerializableMember(2, sourceName); // color3 member
  6990. }
  6991. BABYLON.serializeAsColor3 = serializeAsColor3;
  6992. function serializeAsFresnelParameters(sourceName) {
  6993. return generateSerializableMember(3, sourceName); // fresnel parameters member
  6994. }
  6995. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  6996. function serializeAsVector2(sourceName) {
  6997. return generateSerializableMember(4, sourceName); // vector2 member
  6998. }
  6999. BABYLON.serializeAsVector2 = serializeAsVector2;
  7000. function serializeAsVector3(sourceName) {
  7001. return generateSerializableMember(5, sourceName); // vector3 member
  7002. }
  7003. BABYLON.serializeAsVector3 = serializeAsVector3;
  7004. function serializeAsMeshReference(sourceName) {
  7005. return generateSerializableMember(6, sourceName); // mesh reference member
  7006. }
  7007. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7008. function serializeAsColorCurves(sourceName) {
  7009. return generateSerializableMember(7, sourceName); // color curves
  7010. }
  7011. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7012. function serializeAsColor4(sourceName) {
  7013. return generateSerializableMember(8, sourceName); // color 4
  7014. }
  7015. BABYLON.serializeAsColor4 = serializeAsColor4;
  7016. function serializeAsImageProcessingConfiguration(sourceName) {
  7017. return generateSerializableMember(9, sourceName); // image processing
  7018. }
  7019. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7020. function serializeAsQuaternion(sourceName) {
  7021. return generateSerializableMember(10, sourceName); // quaternion member
  7022. }
  7023. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7024. var SerializationHelper = /** @class */ (function () {
  7025. function SerializationHelper() {
  7026. }
  7027. SerializationHelper.Serialize = function (entity, serializationObject) {
  7028. if (!serializationObject) {
  7029. serializationObject = {};
  7030. }
  7031. // Tags
  7032. if (BABYLON.Tags) {
  7033. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7034. }
  7035. var serializedProperties = getMergedStore(entity);
  7036. // Properties
  7037. for (var property in serializedProperties) {
  7038. var propertyDescriptor = serializedProperties[property];
  7039. var targetPropertyName = propertyDescriptor.sourceName || property;
  7040. var propertyType = propertyDescriptor.type;
  7041. var sourceProperty = entity[property];
  7042. if (sourceProperty !== undefined && sourceProperty !== null) {
  7043. switch (propertyType) {
  7044. case 0:// Value
  7045. serializationObject[targetPropertyName] = sourceProperty;
  7046. break;
  7047. case 1:// Texture
  7048. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7049. break;
  7050. case 2:// Color3
  7051. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7052. break;
  7053. case 3:// FresnelParameters
  7054. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7055. break;
  7056. case 4:// Vector2
  7057. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7058. break;
  7059. case 5:// Vector3
  7060. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7061. break;
  7062. case 6:// Mesh reference
  7063. serializationObject[targetPropertyName] = sourceProperty.id;
  7064. break;
  7065. case 7:// Color Curves
  7066. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7067. break;
  7068. case 8:// Color 4
  7069. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7070. break;
  7071. case 9:// Image Processing
  7072. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7073. break;
  7074. }
  7075. }
  7076. }
  7077. return serializationObject;
  7078. };
  7079. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7080. if (rootUrl === void 0) { rootUrl = null; }
  7081. var destination = creationFunction();
  7082. if (!rootUrl) {
  7083. rootUrl = "";
  7084. }
  7085. // Tags
  7086. if (BABYLON.Tags) {
  7087. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7088. }
  7089. var classStore = getMergedStore(destination);
  7090. // Properties
  7091. for (var property in classStore) {
  7092. var propertyDescriptor = classStore[property];
  7093. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7094. var propertyType = propertyDescriptor.type;
  7095. if (sourceProperty !== undefined && sourceProperty !== null) {
  7096. var dest = destination;
  7097. switch (propertyType) {
  7098. case 0:// Value
  7099. dest[property] = sourceProperty;
  7100. break;
  7101. case 1:// Texture
  7102. if (scene) {
  7103. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7104. }
  7105. break;
  7106. case 2:// Color3
  7107. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7108. break;
  7109. case 3:// FresnelParameters
  7110. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7111. break;
  7112. case 4:// Vector2
  7113. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7114. break;
  7115. case 5:// Vector3
  7116. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7117. break;
  7118. case 6:// Mesh reference
  7119. if (scene) {
  7120. dest[property] = scene.getLastMeshByID(sourceProperty);
  7121. }
  7122. break;
  7123. case 7:// Color Curves
  7124. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7125. break;
  7126. case 8:// Color 4
  7127. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7128. break;
  7129. case 9:// Image Processing
  7130. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7131. break;
  7132. }
  7133. }
  7134. }
  7135. return destination;
  7136. };
  7137. SerializationHelper.Clone = function (creationFunction, source) {
  7138. return _copySource(creationFunction, source, false);
  7139. };
  7140. SerializationHelper.Instanciate = function (creationFunction, source) {
  7141. return _copySource(creationFunction, source, true);
  7142. };
  7143. return SerializationHelper;
  7144. }());
  7145. BABYLON.SerializationHelper = SerializationHelper;
  7146. })(BABYLON || (BABYLON = {}));
  7147. //# sourceMappingURL=babylon.decorators.js.map
  7148. var BABYLON;
  7149. (function (BABYLON) {
  7150. /**
  7151. * Wrapper class for promise with external resolve and reject.
  7152. */
  7153. var Deferred = /** @class */ (function () {
  7154. /**
  7155. * Constructor for this deferred object.
  7156. */
  7157. function Deferred() {
  7158. var _this = this;
  7159. this.promise = new Promise(function (resolve, reject) {
  7160. _this._resolve = resolve;
  7161. _this._reject = reject;
  7162. });
  7163. }
  7164. Object.defineProperty(Deferred.prototype, "resolve", {
  7165. /**
  7166. * The resolve method of the promise associated with this deferred object.
  7167. */
  7168. get: function () {
  7169. return this._resolve;
  7170. },
  7171. enumerable: true,
  7172. configurable: true
  7173. });
  7174. Object.defineProperty(Deferred.prototype, "reject", {
  7175. /**
  7176. * The reject method of the promise associated with this deferred object.
  7177. */
  7178. get: function () {
  7179. return this._reject;
  7180. },
  7181. enumerable: true,
  7182. configurable: true
  7183. });
  7184. return Deferred;
  7185. }());
  7186. BABYLON.Deferred = Deferred;
  7187. })(BABYLON || (BABYLON = {}));
  7188. //# sourceMappingURL=babylon.deferred.js.map
  7189. var BABYLON;
  7190. (function (BABYLON) {
  7191. /**
  7192. * A class serves as a medium between the observable and its observers
  7193. */
  7194. var EventState = /** @class */ (function () {
  7195. /**
  7196. * Create a new EventState
  7197. * @param mask defines the mask associated with this state
  7198. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7199. * @param target defines the original target of the state
  7200. * @param currentTarget defines the current target of the state
  7201. */
  7202. function EventState(mask, skipNextObservers, target, currentTarget) {
  7203. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7204. this.initalize(mask, skipNextObservers, target, currentTarget);
  7205. }
  7206. /**
  7207. * Initialize the current event state
  7208. * @param mask defines the mask associated with this state
  7209. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7210. * @param target defines the original target of the state
  7211. * @param currentTarget defines the current target of the state
  7212. * @returns the current event state
  7213. */
  7214. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7215. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7216. this.mask = mask;
  7217. this.skipNextObservers = skipNextObservers;
  7218. this.target = target;
  7219. this.currentTarget = currentTarget;
  7220. return this;
  7221. };
  7222. return EventState;
  7223. }());
  7224. BABYLON.EventState = EventState;
  7225. /**
  7226. * Represent an Observer registered to a given Observable object.
  7227. */
  7228. var Observer = /** @class */ (function () {
  7229. /**
  7230. * Creates a new observer
  7231. * @param callback defines the callback to call when the observer is notified
  7232. * @param mask defines the mask of the observer (used to filter notifications)
  7233. * @param scope defines the current scope used to restore the JS context
  7234. */
  7235. function Observer(
  7236. /**
  7237. * Defines the callback to call when the observer is notified
  7238. */
  7239. callback,
  7240. /**
  7241. * Defines the mask of the observer (used to filter notifications)
  7242. */
  7243. mask,
  7244. /**
  7245. * Defines the current scope used to restore the JS context
  7246. */
  7247. scope) {
  7248. if (scope === void 0) { scope = null; }
  7249. this.callback = callback;
  7250. this.mask = mask;
  7251. this.scope = scope;
  7252. /** @ignore */
  7253. this._willBeUnregistered = false;
  7254. /**
  7255. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7256. */
  7257. this.unregisterOnNextCall = false;
  7258. }
  7259. return Observer;
  7260. }());
  7261. BABYLON.Observer = Observer;
  7262. /**
  7263. * Represent a list of observers registered to multiple Observables object.
  7264. */
  7265. var MultiObserver = /** @class */ (function () {
  7266. function MultiObserver() {
  7267. }
  7268. /**
  7269. * Release associated resources
  7270. */
  7271. MultiObserver.prototype.dispose = function () {
  7272. if (this._observers && this._observables) {
  7273. for (var index = 0; index < this._observers.length; index++) {
  7274. this._observables[index].remove(this._observers[index]);
  7275. }
  7276. }
  7277. this._observers = null;
  7278. this._observables = null;
  7279. };
  7280. /**
  7281. * Raise a callback when one of the observable will notify
  7282. * @param observables defines a list of observables to watch
  7283. * @param callback defines the callback to call on notification
  7284. * @param mask defines the mask used to filter notifications
  7285. * @param scope defines the current scope used to restore the JS context
  7286. * @returns the new MultiObserver
  7287. */
  7288. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7289. if (mask === void 0) { mask = -1; }
  7290. if (scope === void 0) { scope = null; }
  7291. var result = new MultiObserver();
  7292. result._observers = new Array();
  7293. result._observables = observables;
  7294. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7295. var observable = observables_1[_i];
  7296. var observer = observable.add(callback, mask, false, scope);
  7297. if (observer) {
  7298. result._observers.push(observer);
  7299. }
  7300. }
  7301. return result;
  7302. };
  7303. return MultiObserver;
  7304. }());
  7305. BABYLON.MultiObserver = MultiObserver;
  7306. /**
  7307. * The Observable class is a simple implementation of the Observable pattern.
  7308. * 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.
  7309. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7310. * 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).
  7311. * 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.
  7312. */
  7313. var Observable = /** @class */ (function () {
  7314. /**
  7315. * Creates a new observable
  7316. * @param onObserverAdded defines a callback to call when a new observer is added
  7317. */
  7318. function Observable(onObserverAdded) {
  7319. this._observers = new Array();
  7320. this._eventState = new EventState(0);
  7321. if (onObserverAdded) {
  7322. this._onObserverAdded = onObserverAdded;
  7323. }
  7324. }
  7325. /**
  7326. * Create a new Observer with the specified callback
  7327. * @param callback the callback that will be executed for that Observer
  7328. * @param mask the mask used to filter observers
  7329. * @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.
  7330. * @param scope optional scope for the callback to be called from
  7331. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7332. * @returns the new observer created for the callback
  7333. */
  7334. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7335. if (mask === void 0) { mask = -1; }
  7336. if (insertFirst === void 0) { insertFirst = false; }
  7337. if (scope === void 0) { scope = null; }
  7338. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7339. if (!callback) {
  7340. return null;
  7341. }
  7342. var observer = new Observer(callback, mask, scope);
  7343. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7344. if (insertFirst) {
  7345. this._observers.unshift(observer);
  7346. }
  7347. else {
  7348. this._observers.push(observer);
  7349. }
  7350. if (this._onObserverAdded) {
  7351. this._onObserverAdded(observer);
  7352. }
  7353. return observer;
  7354. };
  7355. /**
  7356. * Remove an Observer from the Observable object
  7357. * @param observer the instance of the Observer to remove
  7358. * @returns false if it doesn't belong to this Observable
  7359. */
  7360. Observable.prototype.remove = function (observer) {
  7361. if (!observer) {
  7362. return false;
  7363. }
  7364. var index = this._observers.indexOf(observer);
  7365. if (index !== -1) {
  7366. this._observers.splice(index, 1);
  7367. return true;
  7368. }
  7369. return false;
  7370. };
  7371. /**
  7372. * Remove a callback from the Observable object
  7373. * @param callback the callback to remove
  7374. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7375. * @returns false if it doesn't belong to this Observable
  7376. */
  7377. Observable.prototype.removeCallback = function (callback, scope) {
  7378. for (var index = 0; index < this._observers.length; index++) {
  7379. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7380. this._observers.splice(index, 1);
  7381. return true;
  7382. }
  7383. }
  7384. return false;
  7385. };
  7386. Observable.prototype._deferUnregister = function (observer) {
  7387. var _this = this;
  7388. observer.unregisterOnNextCall = false;
  7389. observer._willBeUnregistered = true;
  7390. BABYLON.Tools.SetImmediate(function () {
  7391. _this.remove(observer);
  7392. });
  7393. };
  7394. /**
  7395. * Notify all Observers by calling their respective callback with the given data
  7396. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7397. * @param eventData defines the data to send to all observers
  7398. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7399. * @param target defines the original target of the state
  7400. * @param currentTarget defines the current target of the state
  7401. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7402. */
  7403. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7404. if (mask === void 0) { mask = -1; }
  7405. if (!this._observers.length) {
  7406. return true;
  7407. }
  7408. var state = this._eventState;
  7409. state.mask = mask;
  7410. state.target = target;
  7411. state.currentTarget = currentTarget;
  7412. state.skipNextObservers = false;
  7413. state.lastReturnValue = eventData;
  7414. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7415. var obs = _a[_i];
  7416. if (obs._willBeUnregistered) {
  7417. continue;
  7418. }
  7419. if (obs.mask & mask) {
  7420. if (obs.scope) {
  7421. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7422. }
  7423. else {
  7424. state.lastReturnValue = obs.callback(eventData, state);
  7425. }
  7426. if (obs.unregisterOnNextCall) {
  7427. this._deferUnregister(obs);
  7428. }
  7429. }
  7430. if (state.skipNextObservers) {
  7431. return false;
  7432. }
  7433. }
  7434. return true;
  7435. };
  7436. /**
  7437. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7438. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7439. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7440. * and it is crucial that all callbacks will be executed.
  7441. * The order of the callbacks is kept, callbacks are not executed parallel.
  7442. *
  7443. * @param eventData The data to be sent to each callback
  7444. * @param mask is used to filter observers defaults to -1
  7445. * @param target defines the callback target (see EventState)
  7446. * @param currentTarget defines he current object in the bubbling phase
  7447. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7448. */
  7449. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7450. var _this = this;
  7451. if (mask === void 0) { mask = -1; }
  7452. // create an empty promise
  7453. var p = Promise.resolve(eventData);
  7454. // no observers? return this promise.
  7455. if (!this._observers.length) {
  7456. return p;
  7457. }
  7458. var state = this._eventState;
  7459. state.mask = mask;
  7460. state.target = target;
  7461. state.currentTarget = currentTarget;
  7462. state.skipNextObservers = false;
  7463. // execute one callback after another (not using Promise.all, the order is important)
  7464. this._observers.forEach(function (obs) {
  7465. if (state.skipNextObservers) {
  7466. return;
  7467. }
  7468. if (obs._willBeUnregistered) {
  7469. return;
  7470. }
  7471. if (obs.mask & mask) {
  7472. if (obs.scope) {
  7473. p = p.then(function (lastReturnedValue) {
  7474. state.lastReturnValue = lastReturnedValue;
  7475. return obs.callback.apply(obs.scope, [eventData, state]);
  7476. });
  7477. }
  7478. else {
  7479. p = p.then(function (lastReturnedValue) {
  7480. state.lastReturnValue = lastReturnedValue;
  7481. return obs.callback(eventData, state);
  7482. });
  7483. }
  7484. if (obs.unregisterOnNextCall) {
  7485. _this._deferUnregister(obs);
  7486. }
  7487. }
  7488. });
  7489. // return the eventData
  7490. return p.then(function () { return eventData; });
  7491. };
  7492. /**
  7493. * Notify a specific observer
  7494. * @param observer defines the observer to notify
  7495. * @param eventData defines the data to be sent to each callback
  7496. * @param mask is used to filter observers defaults to -1
  7497. */
  7498. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7499. if (mask === void 0) { mask = -1; }
  7500. var state = this._eventState;
  7501. state.mask = mask;
  7502. state.skipNextObservers = false;
  7503. observer.callback(eventData, state);
  7504. };
  7505. /**
  7506. * Gets a boolean indicating if the observable has at least one observer
  7507. * @returns true is the Observable has at least one Observer registered
  7508. */
  7509. Observable.prototype.hasObservers = function () {
  7510. return this._observers.length > 0;
  7511. };
  7512. /**
  7513. * Clear the list of observers
  7514. */
  7515. Observable.prototype.clear = function () {
  7516. this._observers = new Array();
  7517. this._onObserverAdded = null;
  7518. };
  7519. /**
  7520. * Clone the current observable
  7521. * @returns a new observable
  7522. */
  7523. Observable.prototype.clone = function () {
  7524. var result = new Observable();
  7525. result._observers = this._observers.slice(0);
  7526. return result;
  7527. };
  7528. /**
  7529. * Does this observable handles observer registered with a given mask
  7530. * @param mask defines the mask to be tested
  7531. * @return whether or not one observer registered with the given mask is handeled
  7532. **/
  7533. Observable.prototype.hasSpecificMask = function (mask) {
  7534. if (mask === void 0) { mask = -1; }
  7535. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7536. var obs = _a[_i];
  7537. if (obs.mask & mask || obs.mask === mask) {
  7538. return true;
  7539. }
  7540. }
  7541. return false;
  7542. };
  7543. return Observable;
  7544. }());
  7545. BABYLON.Observable = Observable;
  7546. })(BABYLON || (BABYLON = {}));
  7547. //# sourceMappingURL=babylon.observable.js.map
  7548. var BABYLON;
  7549. (function (BABYLON) {
  7550. var SmartArray = /** @class */ (function () {
  7551. function SmartArray(capacity) {
  7552. this.length = 0;
  7553. this.data = new Array(capacity);
  7554. this._id = SmartArray._GlobalId++;
  7555. }
  7556. SmartArray.prototype.push = function (value) {
  7557. this.data[this.length++] = value;
  7558. if (this.length > this.data.length) {
  7559. this.data.length *= 2;
  7560. }
  7561. };
  7562. SmartArray.prototype.forEach = function (func) {
  7563. for (var index = 0; index < this.length; index++) {
  7564. func(this.data[index]);
  7565. }
  7566. };
  7567. SmartArray.prototype.sort = function (compareFn) {
  7568. this.data.sort(compareFn);
  7569. };
  7570. SmartArray.prototype.reset = function () {
  7571. this.length = 0;
  7572. };
  7573. SmartArray.prototype.dispose = function () {
  7574. this.reset();
  7575. if (this.data) {
  7576. this.data.length = 0;
  7577. this.data = [];
  7578. }
  7579. };
  7580. SmartArray.prototype.concat = function (array) {
  7581. if (array.length === 0) {
  7582. return;
  7583. }
  7584. if (this.length + array.length > this.data.length) {
  7585. this.data.length = (this.length + array.length) * 2;
  7586. }
  7587. for (var index = 0; index < array.length; index++) {
  7588. this.data[this.length++] = (array.data || array)[index];
  7589. }
  7590. };
  7591. SmartArray.prototype.indexOf = function (value) {
  7592. var position = this.data.indexOf(value);
  7593. if (position >= this.length) {
  7594. return -1;
  7595. }
  7596. return position;
  7597. };
  7598. SmartArray.prototype.contains = function (value) {
  7599. return this.data.indexOf(value) !== -1;
  7600. };
  7601. // Statics
  7602. SmartArray._GlobalId = 0;
  7603. return SmartArray;
  7604. }());
  7605. BABYLON.SmartArray = SmartArray;
  7606. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7607. __extends(SmartArrayNoDuplicate, _super);
  7608. function SmartArrayNoDuplicate() {
  7609. var _this = _super !== null && _super.apply(this, arguments) || this;
  7610. _this._duplicateId = 0;
  7611. return _this;
  7612. }
  7613. SmartArrayNoDuplicate.prototype.push = function (value) {
  7614. _super.prototype.push.call(this, value);
  7615. if (!value.__smartArrayFlags) {
  7616. value.__smartArrayFlags = {};
  7617. }
  7618. value.__smartArrayFlags[this._id] = this._duplicateId;
  7619. };
  7620. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7621. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7622. return false;
  7623. }
  7624. this.push(value);
  7625. return true;
  7626. };
  7627. SmartArrayNoDuplicate.prototype.reset = function () {
  7628. _super.prototype.reset.call(this);
  7629. this._duplicateId++;
  7630. };
  7631. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7632. if (array.length === 0) {
  7633. return;
  7634. }
  7635. if (this.length + array.length > this.data.length) {
  7636. this.data.length = (this.length + array.length) * 2;
  7637. }
  7638. for (var index = 0; index < array.length; index++) {
  7639. var item = (array.data || array)[index];
  7640. this.pushNoDuplicate(item);
  7641. }
  7642. };
  7643. return SmartArrayNoDuplicate;
  7644. }(SmartArray));
  7645. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7646. })(BABYLON || (BABYLON = {}));
  7647. //# sourceMappingURL=babylon.smartArray.js.map
  7648. var BABYLON;
  7649. (function (BABYLON) {
  7650. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7651. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7652. var LoadFileError = /** @class */ (function (_super) {
  7653. __extends(LoadFileError, _super);
  7654. function LoadFileError(message, request) {
  7655. var _this = _super.call(this, message) || this;
  7656. _this.request = request;
  7657. _this.name = "LoadFileError";
  7658. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7659. return _this;
  7660. }
  7661. // Polyfill for Object.setPrototypeOf if necessary.
  7662. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7663. return LoadFileError;
  7664. }(Error));
  7665. BABYLON.LoadFileError = LoadFileError;
  7666. var RetryStrategy = /** @class */ (function () {
  7667. function RetryStrategy() {
  7668. }
  7669. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7670. if (maxRetries === void 0) { maxRetries = 3; }
  7671. if (baseInterval === void 0) { baseInterval = 500; }
  7672. return function (url, request, retryIndex) {
  7673. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7674. return -1;
  7675. }
  7676. return Math.pow(2, retryIndex) * baseInterval;
  7677. };
  7678. };
  7679. return RetryStrategy;
  7680. }());
  7681. BABYLON.RetryStrategy = RetryStrategy;
  7682. // Screenshots
  7683. var screenshotCanvas;
  7684. var cloneValue = function (source, destinationObject) {
  7685. if (!source)
  7686. return null;
  7687. if (source instanceof BABYLON.Mesh) {
  7688. return null;
  7689. }
  7690. if (source instanceof BABYLON.SubMesh) {
  7691. return source.clone(destinationObject);
  7692. }
  7693. else if (source.clone) {
  7694. return source.clone();
  7695. }
  7696. return null;
  7697. };
  7698. var Tools = /** @class */ (function () {
  7699. function Tools() {
  7700. }
  7701. /**
  7702. * Interpolates between a and b via alpha
  7703. * @param a The lower value (returned when alpha = 0)
  7704. * @param b The upper value (returned when alpha = 1)
  7705. * @param alpha The interpolation-factor
  7706. * @return The mixed value
  7707. */
  7708. Tools.Mix = function (a, b, alpha) {
  7709. return a * (1 - alpha) + b * alpha;
  7710. };
  7711. Tools.Instantiate = function (className) {
  7712. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7713. return Tools.RegisteredExternalClasses[className];
  7714. }
  7715. var arr = className.split(".");
  7716. var fn = (window || this);
  7717. for (var i = 0, len = arr.length; i < len; i++) {
  7718. fn = fn[arr[i]];
  7719. }
  7720. if (typeof fn !== "function") {
  7721. return null;
  7722. }
  7723. return fn;
  7724. };
  7725. /**
  7726. * Provides a slice function that will work even on IE
  7727. * @param data defines the array to slice
  7728. * @returns the new sliced array
  7729. */
  7730. Tools.Slice = function (data) {
  7731. if (data.slice) {
  7732. return data.slice();
  7733. }
  7734. return Array.prototype.slice.call(data);
  7735. };
  7736. Tools.SetImmediate = function (action) {
  7737. if (window.setImmediate) {
  7738. window.setImmediate(action);
  7739. }
  7740. else {
  7741. setTimeout(action, 1);
  7742. }
  7743. };
  7744. Tools.IsExponentOfTwo = function (value) {
  7745. var count = 1;
  7746. do {
  7747. count *= 2;
  7748. } while (count < value);
  7749. return count === value;
  7750. };
  7751. /**
  7752. * Find the next highest power of two.
  7753. * @param x Number to start search from.
  7754. * @return Next highest power of two.
  7755. */
  7756. Tools.CeilingPOT = function (x) {
  7757. x--;
  7758. x |= x >> 1;
  7759. x |= x >> 2;
  7760. x |= x >> 4;
  7761. x |= x >> 8;
  7762. x |= x >> 16;
  7763. x++;
  7764. return x;
  7765. };
  7766. /**
  7767. * Find the next lowest power of two.
  7768. * @param x Number to start search from.
  7769. * @return Next lowest power of two.
  7770. */
  7771. Tools.FloorPOT = function (x) {
  7772. x = x | (x >> 1);
  7773. x = x | (x >> 2);
  7774. x = x | (x >> 4);
  7775. x = x | (x >> 8);
  7776. x = x | (x >> 16);
  7777. return x - (x >> 1);
  7778. };
  7779. /**
  7780. * Find the nearest power of two.
  7781. * @param x Number to start search from.
  7782. * @return Next nearest power of two.
  7783. */
  7784. Tools.NearestPOT = function (x) {
  7785. var c = Tools.CeilingPOT(x);
  7786. var f = Tools.FloorPOT(x);
  7787. return (c - x) > (x - f) ? f : c;
  7788. };
  7789. Tools.GetExponentOfTwo = function (value, max, mode) {
  7790. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  7791. var pot;
  7792. switch (mode) {
  7793. case BABYLON.Engine.SCALEMODE_FLOOR:
  7794. pot = Tools.FloorPOT(value);
  7795. break;
  7796. case BABYLON.Engine.SCALEMODE_NEAREST:
  7797. pot = Tools.NearestPOT(value);
  7798. break;
  7799. case BABYLON.Engine.SCALEMODE_CEILING:
  7800. default:
  7801. pot = Tools.CeilingPOT(value);
  7802. break;
  7803. }
  7804. return Math.min(pot, max);
  7805. };
  7806. Tools.GetFilename = function (path) {
  7807. var index = path.lastIndexOf("/");
  7808. if (index < 0)
  7809. return path;
  7810. return path.substring(index + 1);
  7811. };
  7812. /**
  7813. * Extracts the "folder" part of a path (everything before the filename).
  7814. * @param uri The URI to extract the info from
  7815. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  7816. * @returns The "folder" part of the path
  7817. */
  7818. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  7819. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  7820. var index = uri.lastIndexOf("/");
  7821. if (index < 0) {
  7822. if (returnUnchangedIfNoSlash) {
  7823. return uri;
  7824. }
  7825. return "";
  7826. }
  7827. return uri.substring(0, index + 1);
  7828. };
  7829. Tools.GetDOMTextContent = function (element) {
  7830. var result = "";
  7831. var child = element.firstChild;
  7832. while (child) {
  7833. if (child.nodeType === 3) {
  7834. result += child.textContent;
  7835. }
  7836. child = child.nextSibling;
  7837. }
  7838. return result;
  7839. };
  7840. Tools.ToDegrees = function (angle) {
  7841. return angle * 180 / Math.PI;
  7842. };
  7843. Tools.ToRadians = function (angle) {
  7844. return angle * Math.PI / 180;
  7845. };
  7846. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  7847. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  7848. var output = "";
  7849. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  7850. var i = 0;
  7851. var bytes = new Uint8Array(buffer);
  7852. while (i < bytes.length) {
  7853. chr1 = bytes[i++];
  7854. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  7855. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  7856. enc1 = chr1 >> 2;
  7857. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  7858. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  7859. enc4 = chr3 & 63;
  7860. if (isNaN(chr2)) {
  7861. enc3 = enc4 = 64;
  7862. }
  7863. else if (isNaN(chr3)) {
  7864. enc4 = 64;
  7865. }
  7866. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  7867. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  7868. }
  7869. return "data:image/png;base64," + output;
  7870. };
  7871. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  7872. if (bias === void 0) { bias = null; }
  7873. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7874. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7875. for (var index = indexStart; index < indexStart + indexCount; index++) {
  7876. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  7877. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7878. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7879. }
  7880. if (bias) {
  7881. minimum.x -= minimum.x * bias.x + bias.y;
  7882. minimum.y -= minimum.y * bias.x + bias.y;
  7883. minimum.z -= minimum.z * bias.x + bias.y;
  7884. maximum.x += maximum.x * bias.x + bias.y;
  7885. maximum.y += maximum.y * bias.x + bias.y;
  7886. maximum.z += maximum.z * bias.x + bias.y;
  7887. }
  7888. return {
  7889. minimum: minimum,
  7890. maximum: maximum
  7891. };
  7892. };
  7893. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  7894. if (bias === void 0) { bias = null; }
  7895. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7896. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  7897. if (!stride) {
  7898. stride = 3;
  7899. }
  7900. for (var index = start; index < start + count; index++) {
  7901. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  7902. minimum = BABYLON.Vector3.Minimize(current, minimum);
  7903. maximum = BABYLON.Vector3.Maximize(current, maximum);
  7904. }
  7905. if (bias) {
  7906. minimum.x -= minimum.x * bias.x + bias.y;
  7907. minimum.y -= minimum.y * bias.x + bias.y;
  7908. minimum.z -= minimum.z * bias.x + bias.y;
  7909. maximum.x += maximum.x * bias.x + bias.y;
  7910. maximum.y += maximum.y * bias.x + bias.y;
  7911. maximum.z += maximum.z * bias.x + bias.y;
  7912. }
  7913. return {
  7914. minimum: minimum,
  7915. maximum: maximum
  7916. };
  7917. };
  7918. Tools.Vector2ArrayFeeder = function (array) {
  7919. return function (index) {
  7920. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  7921. var length = isFloatArray ? array.length / 2 : array.length;
  7922. if (index >= length) {
  7923. return null;
  7924. }
  7925. if (isFloatArray) {
  7926. var fa = array;
  7927. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  7928. }
  7929. var a = array;
  7930. return a[index];
  7931. };
  7932. };
  7933. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  7934. if (bias === void 0) { bias = null; }
  7935. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  7936. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  7937. var i = 0;
  7938. var cur = feeder(i++);
  7939. while (cur) {
  7940. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  7941. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  7942. cur = feeder(i++);
  7943. }
  7944. if (bias) {
  7945. minimum.x -= minimum.x * bias.x + bias.y;
  7946. minimum.y -= minimum.y * bias.x + bias.y;
  7947. maximum.x += maximum.x * bias.x + bias.y;
  7948. maximum.y += maximum.y * bias.x + bias.y;
  7949. }
  7950. return {
  7951. minimum: minimum,
  7952. maximum: maximum
  7953. };
  7954. };
  7955. Tools.MakeArray = function (obj, allowsNullUndefined) {
  7956. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  7957. return null;
  7958. return Array.isArray(obj) ? obj : [obj];
  7959. };
  7960. // Misc.
  7961. Tools.GetPointerPrefix = function () {
  7962. var eventPrefix = "pointer";
  7963. // Check if pointer events are supported
  7964. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  7965. eventPrefix = "mouse";
  7966. }
  7967. return eventPrefix;
  7968. };
  7969. /**
  7970. * @param func - the function to be called
  7971. * @param requester - the object that will request the next frame. Falls back to window.
  7972. */
  7973. Tools.QueueNewFrame = function (func, requester) {
  7974. if (!Tools.IsWindowObjectExist()) {
  7975. return setTimeout(func, 16);
  7976. }
  7977. if (!requester) {
  7978. requester = window;
  7979. }
  7980. if (requester.requestAnimationFrame) {
  7981. return requester.requestAnimationFrame(func);
  7982. }
  7983. else if (requester.msRequestAnimationFrame) {
  7984. return requester.msRequestAnimationFrame(func);
  7985. }
  7986. else if (requester.webkitRequestAnimationFrame) {
  7987. return requester.webkitRequestAnimationFrame(func);
  7988. }
  7989. else if (requester.mozRequestAnimationFrame) {
  7990. return requester.mozRequestAnimationFrame(func);
  7991. }
  7992. else if (requester.oRequestAnimationFrame) {
  7993. return requester.oRequestAnimationFrame(func);
  7994. }
  7995. else {
  7996. return window.setTimeout(func, 16);
  7997. }
  7998. };
  7999. Tools.RequestFullscreen = function (element) {
  8000. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8001. if (!requestFunction)
  8002. return;
  8003. requestFunction.call(element);
  8004. };
  8005. Tools.ExitFullscreen = function () {
  8006. if (document.exitFullscreen) {
  8007. document.exitFullscreen();
  8008. }
  8009. else if (document.mozCancelFullScreen) {
  8010. document.mozCancelFullScreen();
  8011. }
  8012. else if (document.webkitCancelFullScreen) {
  8013. document.webkitCancelFullScreen();
  8014. }
  8015. else if (document.msCancelFullScreen) {
  8016. document.msCancelFullScreen();
  8017. }
  8018. };
  8019. Tools.SetCorsBehavior = function (url, element) {
  8020. if (url && url.indexOf("data:") === 0) {
  8021. return;
  8022. }
  8023. if (Tools.CorsBehavior) {
  8024. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8025. element.crossOrigin = Tools.CorsBehavior;
  8026. }
  8027. else {
  8028. var result = Tools.CorsBehavior(url);
  8029. if (result) {
  8030. element.crossOrigin = result;
  8031. }
  8032. }
  8033. }
  8034. };
  8035. // External files
  8036. Tools.CleanUrl = function (url) {
  8037. url = url.replace(/#/mg, "%23");
  8038. return url;
  8039. };
  8040. Tools.LoadImage = function (url, onLoad, onError, database) {
  8041. if (url instanceof ArrayBuffer) {
  8042. url = Tools.EncodeArrayBufferTobase64(url);
  8043. }
  8044. url = Tools.CleanUrl(url);
  8045. url = Tools.PreprocessUrl(url);
  8046. var img = new Image();
  8047. Tools.SetCorsBehavior(url, img);
  8048. var loadHandler = function () {
  8049. img.removeEventListener("load", loadHandler);
  8050. img.removeEventListener("error", errorHandler);
  8051. onLoad(img);
  8052. };
  8053. var errorHandler = function (err) {
  8054. img.removeEventListener("load", loadHandler);
  8055. img.removeEventListener("error", errorHandler);
  8056. Tools.Error("Error while trying to load image: " + url);
  8057. if (onError) {
  8058. onError("Error while trying to load image: " + url, err);
  8059. }
  8060. };
  8061. img.addEventListener("load", loadHandler);
  8062. img.addEventListener("error", errorHandler);
  8063. var noIndexedDB = function () {
  8064. img.src = url;
  8065. };
  8066. var loadFromIndexedDB = function () {
  8067. if (database) {
  8068. database.loadImageFromDB(url, img);
  8069. }
  8070. };
  8071. //ANY database to do!
  8072. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8073. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8074. }
  8075. else {
  8076. if (url.indexOf("file:") !== -1) {
  8077. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8078. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8079. try {
  8080. var blobURL;
  8081. try {
  8082. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8083. }
  8084. catch (ex) {
  8085. // Chrome doesn't support oneTimeOnly parameter
  8086. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8087. }
  8088. img.src = blobURL;
  8089. }
  8090. catch (e) {
  8091. img.src = "";
  8092. }
  8093. return img;
  8094. }
  8095. }
  8096. noIndexedDB();
  8097. }
  8098. return img;
  8099. };
  8100. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8101. url = Tools.CleanUrl(url);
  8102. url = Tools.PreprocessUrl(url);
  8103. // If file and file input are set
  8104. if (url.indexOf("file:") !== -1) {
  8105. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8106. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8107. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8108. }
  8109. }
  8110. var loadUrl = Tools.BaseUrl + url;
  8111. var aborted = false;
  8112. var fileRequest = {
  8113. onCompleteObservable: new BABYLON.Observable(),
  8114. abort: function () { return aborted = true; },
  8115. };
  8116. var requestFile = function () {
  8117. var request = new XMLHttpRequest();
  8118. var retryHandle = null;
  8119. fileRequest.abort = function () {
  8120. aborted = true;
  8121. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8122. request.abort();
  8123. }
  8124. if (retryHandle !== null) {
  8125. clearTimeout(retryHandle);
  8126. retryHandle = null;
  8127. }
  8128. };
  8129. var retryLoop = function (retryIndex) {
  8130. request.open('GET', loadUrl, true);
  8131. if (useArrayBuffer) {
  8132. request.responseType = "arraybuffer";
  8133. }
  8134. if (onProgress) {
  8135. request.addEventListener("progress", onProgress);
  8136. }
  8137. var onLoadEnd = function () {
  8138. request.removeEventListener("loadend", onLoadEnd);
  8139. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8140. fileRequest.onCompleteObservable.clear();
  8141. };
  8142. request.addEventListener("loadend", onLoadEnd);
  8143. var onReadyStateChange = function () {
  8144. if (aborted) {
  8145. return;
  8146. }
  8147. // In case of undefined state in some browsers.
  8148. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8149. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8150. request.removeEventListener("readystatechange", onReadyStateChange);
  8151. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8152. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8153. return;
  8154. }
  8155. var retryStrategy = Tools.DefaultRetryStrategy;
  8156. if (retryStrategy) {
  8157. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8158. if (waitTime !== -1) {
  8159. // Prevent the request from completing for retry.
  8160. request.removeEventListener("loadend", onLoadEnd);
  8161. request = new XMLHttpRequest();
  8162. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8163. return;
  8164. }
  8165. }
  8166. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8167. if (onError) {
  8168. onError(request, e);
  8169. }
  8170. else {
  8171. throw e;
  8172. }
  8173. }
  8174. };
  8175. request.addEventListener("readystatechange", onReadyStateChange);
  8176. request.send();
  8177. };
  8178. retryLoop(0);
  8179. };
  8180. // Caching all files
  8181. if (database && database.enableSceneOffline) {
  8182. var noIndexedDB_1 = function () {
  8183. if (!aborted) {
  8184. requestFile();
  8185. }
  8186. };
  8187. var loadFromIndexedDB = function () {
  8188. // TODO: database needs to support aborting and should return a IFileRequest
  8189. if (aborted) {
  8190. return;
  8191. }
  8192. if (database) {
  8193. database.loadFileFromDB(url, function (data) {
  8194. if (!aborted) {
  8195. onSuccess(data);
  8196. }
  8197. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8198. }, onProgress ? function (event) {
  8199. if (!aborted) {
  8200. onProgress(event);
  8201. }
  8202. } : undefined, noIndexedDB_1, useArrayBuffer);
  8203. }
  8204. };
  8205. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8206. }
  8207. else {
  8208. requestFile();
  8209. }
  8210. return fileRequest;
  8211. };
  8212. /**
  8213. * Load a script (identified by an url). When the url returns, the
  8214. * content of this file is added into a new script element, attached to the DOM (body element)
  8215. */
  8216. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8217. var head = document.getElementsByTagName('head')[0];
  8218. var script = document.createElement('script');
  8219. script.type = 'text/javascript';
  8220. script.src = scriptUrl;
  8221. script.onload = function () {
  8222. if (onSuccess) {
  8223. onSuccess();
  8224. }
  8225. };
  8226. script.onerror = function (e) {
  8227. if (onError) {
  8228. onError("Unable to load script", e);
  8229. }
  8230. };
  8231. head.appendChild(script);
  8232. };
  8233. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8234. var reader = new FileReader();
  8235. var request = {
  8236. onCompleteObservable: new BABYLON.Observable(),
  8237. abort: function () { return reader.abort(); },
  8238. };
  8239. reader.onloadend = function (e) {
  8240. request.onCompleteObservable.notifyObservers(request);
  8241. };
  8242. reader.onload = function (e) {
  8243. //target doesn't have result from ts 1.3
  8244. callback(e.target['result']);
  8245. };
  8246. reader.onprogress = progressCallback;
  8247. reader.readAsDataURL(fileToLoad);
  8248. return request;
  8249. };
  8250. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8251. var reader = new FileReader();
  8252. var request = {
  8253. onCompleteObservable: new BABYLON.Observable(),
  8254. abort: function () { return reader.abort(); },
  8255. };
  8256. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8257. reader.onerror = function (e) {
  8258. Tools.Log("Error while reading file: " + fileToLoad.name);
  8259. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8260. };
  8261. reader.onload = function (e) {
  8262. //target doesn't have result from ts 1.3
  8263. callback(e.target['result']);
  8264. };
  8265. if (progressCallBack) {
  8266. reader.onprogress = progressCallBack;
  8267. }
  8268. if (!useArrayBuffer) {
  8269. // Asynchronous read
  8270. reader.readAsText(fileToLoad);
  8271. }
  8272. else {
  8273. reader.readAsArrayBuffer(fileToLoad);
  8274. }
  8275. return request;
  8276. };
  8277. //returns a downloadable url to a file content.
  8278. Tools.FileAsURL = function (content) {
  8279. var fileBlob = new Blob([content]);
  8280. var url = window.URL || window.webkitURL;
  8281. var link = url.createObjectURL(fileBlob);
  8282. return link;
  8283. };
  8284. // Misc.
  8285. Tools.Format = function (value, decimals) {
  8286. if (decimals === void 0) { decimals = 2; }
  8287. return value.toFixed(decimals);
  8288. };
  8289. Tools.CheckExtends = function (v, min, max) {
  8290. if (v.x < min.x)
  8291. min.x = v.x;
  8292. if (v.y < min.y)
  8293. min.y = v.y;
  8294. if (v.z < min.z)
  8295. min.z = v.z;
  8296. if (v.x > max.x)
  8297. max.x = v.x;
  8298. if (v.y > max.y)
  8299. max.y = v.y;
  8300. if (v.z > max.z)
  8301. max.z = v.z;
  8302. };
  8303. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8304. for (var prop in source) {
  8305. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8306. continue;
  8307. }
  8308. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8309. continue;
  8310. }
  8311. var sourceValue = source[prop];
  8312. var typeOfSourceValue = typeof sourceValue;
  8313. if (typeOfSourceValue === "function") {
  8314. continue;
  8315. }
  8316. if (typeOfSourceValue === "object") {
  8317. if (sourceValue instanceof Array) {
  8318. destination[prop] = [];
  8319. if (sourceValue.length > 0) {
  8320. if (typeof sourceValue[0] == "object") {
  8321. for (var index = 0; index < sourceValue.length; index++) {
  8322. var clonedValue = cloneValue(sourceValue[index], destination);
  8323. if (destination[prop].indexOf(clonedValue) === -1) {
  8324. destination[prop].push(clonedValue);
  8325. }
  8326. }
  8327. }
  8328. else {
  8329. destination[prop] = sourceValue.slice(0);
  8330. }
  8331. }
  8332. }
  8333. else {
  8334. destination[prop] = cloneValue(sourceValue, destination);
  8335. }
  8336. }
  8337. else {
  8338. destination[prop] = sourceValue;
  8339. }
  8340. }
  8341. };
  8342. Tools.IsEmpty = function (obj) {
  8343. for (var i in obj) {
  8344. if (obj.hasOwnProperty(i)) {
  8345. return false;
  8346. }
  8347. }
  8348. return true;
  8349. };
  8350. Tools.RegisterTopRootEvents = function (events) {
  8351. for (var index = 0; index < events.length; index++) {
  8352. var event = events[index];
  8353. window.addEventListener(event.name, event.handler, false);
  8354. try {
  8355. if (window.parent) {
  8356. window.parent.addEventListener(event.name, event.handler, false);
  8357. }
  8358. }
  8359. catch (e) {
  8360. // Silently fails...
  8361. }
  8362. }
  8363. };
  8364. Tools.UnregisterTopRootEvents = function (events) {
  8365. for (var index = 0; index < events.length; index++) {
  8366. var event = events[index];
  8367. window.removeEventListener(event.name, event.handler);
  8368. try {
  8369. if (window.parent) {
  8370. window.parent.removeEventListener(event.name, event.handler);
  8371. }
  8372. }
  8373. catch (e) {
  8374. // Silently fails...
  8375. }
  8376. }
  8377. };
  8378. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8379. if (mimeType === void 0) { mimeType = "image/png"; }
  8380. // Read the contents of the framebuffer
  8381. var numberOfChannelsByLine = width * 4;
  8382. var halfHeight = height / 2;
  8383. //Reading datas from WebGL
  8384. var data = engine.readPixels(0, 0, width, height);
  8385. //To flip image on Y axis.
  8386. for (var i = 0; i < halfHeight; i++) {
  8387. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8388. var currentCell = j + i * numberOfChannelsByLine;
  8389. var targetLine = height - i - 1;
  8390. var targetCell = j + targetLine * numberOfChannelsByLine;
  8391. var temp = data[currentCell];
  8392. data[currentCell] = data[targetCell];
  8393. data[targetCell] = temp;
  8394. }
  8395. }
  8396. // Create a 2D canvas to store the result
  8397. if (!screenshotCanvas) {
  8398. screenshotCanvas = document.createElement('canvas');
  8399. }
  8400. screenshotCanvas.width = width;
  8401. screenshotCanvas.height = height;
  8402. var context = screenshotCanvas.getContext('2d');
  8403. if (context) {
  8404. // Copy the pixels to a 2D canvas
  8405. var imageData = context.createImageData(width, height);
  8406. var castData = (imageData.data);
  8407. castData.set(data);
  8408. context.putImageData(imageData, 0, 0);
  8409. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8410. }
  8411. };
  8412. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8413. if (mimeType === void 0) { mimeType = "image/png"; }
  8414. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8415. if (successCallback) {
  8416. successCallback(base64Image);
  8417. }
  8418. else {
  8419. // We need HTMLCanvasElement.toBlob for HD screenshots
  8420. if (!screenshotCanvas.toBlob) {
  8421. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8422. screenshotCanvas.toBlob = function (callback, type, quality) {
  8423. var _this = this;
  8424. setTimeout(function () {
  8425. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8426. for (var i = 0; i < len; i++) {
  8427. arr[i] = binStr.charCodeAt(i);
  8428. }
  8429. callback(new Blob([arr], { type: type || 'image/png' }));
  8430. });
  8431. };
  8432. }
  8433. screenshotCanvas.toBlob(function (blob) {
  8434. var url = URL.createObjectURL(blob);
  8435. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8436. if (("download" in document.createElement("a"))) {
  8437. var a = window.document.createElement("a");
  8438. a.href = url;
  8439. if (fileName) {
  8440. a.setAttribute("download", fileName);
  8441. }
  8442. else {
  8443. var date = new Date();
  8444. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8445. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8446. }
  8447. window.document.body.appendChild(a);
  8448. a.addEventListener("click", function () {
  8449. if (a.parentElement) {
  8450. a.parentElement.removeChild(a);
  8451. }
  8452. });
  8453. a.click();
  8454. }
  8455. else {
  8456. var newWindow = window.open("");
  8457. if (!newWindow)
  8458. return;
  8459. var img = newWindow.document.createElement("img");
  8460. img.onload = function () {
  8461. // no longer need to read the blob so it's revoked
  8462. URL.revokeObjectURL(url);
  8463. };
  8464. img.src = url;
  8465. newWindow.document.body.appendChild(img);
  8466. }
  8467. });
  8468. }
  8469. };
  8470. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8471. if (mimeType === void 0) { mimeType = "image/png"; }
  8472. var width;
  8473. var height;
  8474. // If a precision value is specified
  8475. if (size.precision) {
  8476. width = Math.round(engine.getRenderWidth() * size.precision);
  8477. height = Math.round(width / engine.getAspectRatio(camera));
  8478. }
  8479. else if (size.width && size.height) {
  8480. width = size.width;
  8481. height = size.height;
  8482. }
  8483. else if (size.width && !size.height) {
  8484. width = size.width;
  8485. height = Math.round(width / engine.getAspectRatio(camera));
  8486. }
  8487. else if (size.height && !size.width) {
  8488. height = size.height;
  8489. width = Math.round(height * engine.getAspectRatio(camera));
  8490. }
  8491. else if (!isNaN(size)) {
  8492. height = size;
  8493. width = size;
  8494. }
  8495. else {
  8496. Tools.Error("Invalid 'size' parameter !");
  8497. return;
  8498. }
  8499. if (!screenshotCanvas) {
  8500. screenshotCanvas = document.createElement('canvas');
  8501. }
  8502. screenshotCanvas.width = width;
  8503. screenshotCanvas.height = height;
  8504. var renderContext = screenshotCanvas.getContext("2d");
  8505. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8506. var newWidth = width;
  8507. var newHeight = newWidth / ratio;
  8508. if (newHeight > height) {
  8509. newHeight = height;
  8510. newWidth = newHeight * ratio;
  8511. }
  8512. var offsetX = Math.max(0, width - newWidth) / 2;
  8513. var offsetY = Math.max(0, height - newHeight) / 2;
  8514. var renderingCanvas = engine.getRenderingCanvas();
  8515. if (renderContext && renderingCanvas) {
  8516. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8517. }
  8518. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8519. };
  8520. /**
  8521. * Generates an image screenshot from the specified camera.
  8522. *
  8523. * @param engine The engine to use for rendering
  8524. * @param camera The camera to use for rendering
  8525. * @param size This parameter can be set to a single number or to an object with the
  8526. * following (optional) properties: precision, width, height. If a single number is passed,
  8527. * it will be used for both width and height. If an object is passed, the screenshot size
  8528. * will be derived from the parameters. The precision property is a multiplier allowing
  8529. * rendering at a higher or lower resolution.
  8530. * @param successCallback The callback receives a single parameter which contains the
  8531. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8532. * src parameter of an <img> to display it.
  8533. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8534. * Check your browser for supported MIME types.
  8535. * @param samples Texture samples (default: 1)
  8536. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8537. * @param fileName A name for for the downloaded file.
  8538. * @constructor
  8539. */
  8540. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8541. if (mimeType === void 0) { mimeType = "image/png"; }
  8542. if (samples === void 0) { samples = 1; }
  8543. if (antialiasing === void 0) { antialiasing = false; }
  8544. var width;
  8545. var height;
  8546. //If a precision value is specified
  8547. if (size.precision) {
  8548. width = Math.round(engine.getRenderWidth() * size.precision);
  8549. height = Math.round(width / engine.getAspectRatio(camera));
  8550. size = { width: width, height: height };
  8551. }
  8552. else if (size.width && size.height) {
  8553. width = size.width;
  8554. height = size.height;
  8555. }
  8556. else if (size.width && !size.height) {
  8557. width = size.width;
  8558. height = Math.round(width / engine.getAspectRatio(camera));
  8559. size = { width: width, height: height };
  8560. }
  8561. else if (size.height && !size.width) {
  8562. height = size.height;
  8563. width = Math.round(height * engine.getAspectRatio(camera));
  8564. size = { width: width, height: height };
  8565. }
  8566. else if (!isNaN(size)) {
  8567. height = size;
  8568. width = size;
  8569. }
  8570. else {
  8571. Tools.Error("Invalid 'size' parameter !");
  8572. return;
  8573. }
  8574. var scene = camera.getScene();
  8575. var previousCamera = null;
  8576. if (scene.activeCamera !== camera) {
  8577. previousCamera = scene.activeCamera;
  8578. scene.activeCamera = camera;
  8579. }
  8580. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8581. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8582. texture.renderList = null;
  8583. texture.samples = samples;
  8584. if (antialiasing) {
  8585. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8586. }
  8587. texture.onAfterRenderObservable.add(function () {
  8588. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8589. });
  8590. scene.incrementRenderId();
  8591. scene.resetCachedMaterial();
  8592. texture.render(true);
  8593. texture.dispose();
  8594. if (previousCamera) {
  8595. scene.activeCamera = previousCamera;
  8596. }
  8597. camera.getProjectionMatrix(true); // Force cache refresh;
  8598. };
  8599. // XHR response validator for local file scenario
  8600. Tools.ValidateXHRData = function (xhr, dataType) {
  8601. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8602. if (dataType === void 0) { dataType = 7; }
  8603. try {
  8604. if (dataType & 1) {
  8605. if (xhr.responseText && xhr.responseText.length > 0) {
  8606. return true;
  8607. }
  8608. else if (dataType === 1) {
  8609. return false;
  8610. }
  8611. }
  8612. if (dataType & 2) {
  8613. // Check header width and height since there is no "TGA" magic number
  8614. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8615. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8616. return true;
  8617. }
  8618. else if (dataType === 2) {
  8619. return false;
  8620. }
  8621. }
  8622. if (dataType & 4) {
  8623. // Check for the "DDS" magic number
  8624. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8625. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8626. return true;
  8627. }
  8628. else {
  8629. return false;
  8630. }
  8631. }
  8632. }
  8633. catch (e) {
  8634. // Global protection
  8635. }
  8636. return false;
  8637. };
  8638. /**
  8639. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8640. * Be aware Math.random() could cause collisions, but:
  8641. * "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"
  8642. */
  8643. Tools.RandomId = function () {
  8644. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8645. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8646. return v.toString(16);
  8647. });
  8648. };
  8649. /**
  8650. * Test if the given uri is a base64 string.
  8651. * @param uri The uri to test
  8652. * @return True if the uri is a base64 string or false otherwise.
  8653. */
  8654. Tools.IsBase64 = function (uri) {
  8655. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8656. };
  8657. /**
  8658. * Decode the given base64 uri.
  8659. * @param uri The uri to decode
  8660. * @return The decoded base64 data.
  8661. */
  8662. Tools.DecodeBase64 = function (uri) {
  8663. var decodedString = atob(uri.split(",")[1]);
  8664. var bufferLength = decodedString.length;
  8665. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8666. for (var i = 0; i < bufferLength; i++) {
  8667. bufferView[i] = decodedString.charCodeAt(i);
  8668. }
  8669. return bufferView.buffer;
  8670. };
  8671. Object.defineProperty(Tools, "NoneLogLevel", {
  8672. get: function () {
  8673. return Tools._NoneLogLevel;
  8674. },
  8675. enumerable: true,
  8676. configurable: true
  8677. });
  8678. Object.defineProperty(Tools, "MessageLogLevel", {
  8679. get: function () {
  8680. return Tools._MessageLogLevel;
  8681. },
  8682. enumerable: true,
  8683. configurable: true
  8684. });
  8685. Object.defineProperty(Tools, "WarningLogLevel", {
  8686. get: function () {
  8687. return Tools._WarningLogLevel;
  8688. },
  8689. enumerable: true,
  8690. configurable: true
  8691. });
  8692. Object.defineProperty(Tools, "ErrorLogLevel", {
  8693. get: function () {
  8694. return Tools._ErrorLogLevel;
  8695. },
  8696. enumerable: true,
  8697. configurable: true
  8698. });
  8699. Object.defineProperty(Tools, "AllLogLevel", {
  8700. get: function () {
  8701. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8702. },
  8703. enumerable: true,
  8704. configurable: true
  8705. });
  8706. Tools._AddLogEntry = function (entry) {
  8707. Tools._LogCache = entry + Tools._LogCache;
  8708. if (Tools.OnNewCacheEntry) {
  8709. Tools.OnNewCacheEntry(entry);
  8710. }
  8711. };
  8712. Tools._FormatMessage = function (message) {
  8713. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8714. var date = new Date();
  8715. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8716. };
  8717. Tools._LogDisabled = function (message) {
  8718. // nothing to do
  8719. };
  8720. Tools._LogEnabled = function (message) {
  8721. var formattedMessage = Tools._FormatMessage(message);
  8722. console.log("BJS - " + formattedMessage);
  8723. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8724. Tools._AddLogEntry(entry);
  8725. };
  8726. Tools._WarnDisabled = function (message) {
  8727. // nothing to do
  8728. };
  8729. Tools._WarnEnabled = function (message) {
  8730. var formattedMessage = Tools._FormatMessage(message);
  8731. console.warn("BJS - " + formattedMessage);
  8732. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8733. Tools._AddLogEntry(entry);
  8734. };
  8735. Tools._ErrorDisabled = function (message) {
  8736. // nothing to do
  8737. };
  8738. Tools._ErrorEnabled = function (message) {
  8739. Tools.errorsCount++;
  8740. var formattedMessage = Tools._FormatMessage(message);
  8741. console.error("BJS - " + formattedMessage);
  8742. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  8743. Tools._AddLogEntry(entry);
  8744. };
  8745. Object.defineProperty(Tools, "LogCache", {
  8746. get: function () {
  8747. return Tools._LogCache;
  8748. },
  8749. enumerable: true,
  8750. configurable: true
  8751. });
  8752. Tools.ClearLogCache = function () {
  8753. Tools._LogCache = "";
  8754. Tools.errorsCount = 0;
  8755. };
  8756. Object.defineProperty(Tools, "LogLevels", {
  8757. set: function (level) {
  8758. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  8759. Tools.Log = Tools._LogEnabled;
  8760. }
  8761. else {
  8762. Tools.Log = Tools._LogDisabled;
  8763. }
  8764. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  8765. Tools.Warn = Tools._WarnEnabled;
  8766. }
  8767. else {
  8768. Tools.Warn = Tools._WarnDisabled;
  8769. }
  8770. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  8771. Tools.Error = Tools._ErrorEnabled;
  8772. }
  8773. else {
  8774. Tools.Error = Tools._ErrorDisabled;
  8775. }
  8776. },
  8777. enumerable: true,
  8778. configurable: true
  8779. });
  8780. Tools.IsWindowObjectExist = function () {
  8781. return (typeof window) !== "undefined";
  8782. };
  8783. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  8784. get: function () {
  8785. return Tools._PerformanceNoneLogLevel;
  8786. },
  8787. enumerable: true,
  8788. configurable: true
  8789. });
  8790. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  8791. get: function () {
  8792. return Tools._PerformanceUserMarkLogLevel;
  8793. },
  8794. enumerable: true,
  8795. configurable: true
  8796. });
  8797. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  8798. get: function () {
  8799. return Tools._PerformanceConsoleLogLevel;
  8800. },
  8801. enumerable: true,
  8802. configurable: true
  8803. });
  8804. Object.defineProperty(Tools, "PerformanceLogLevel", {
  8805. set: function (level) {
  8806. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  8807. Tools.StartPerformanceCounter = Tools._StartUserMark;
  8808. Tools.EndPerformanceCounter = Tools._EndUserMark;
  8809. return;
  8810. }
  8811. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  8812. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  8813. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  8814. return;
  8815. }
  8816. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  8817. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  8818. },
  8819. enumerable: true,
  8820. configurable: true
  8821. });
  8822. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  8823. };
  8824. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  8825. };
  8826. Tools._StartUserMark = function (counterName, condition) {
  8827. if (condition === void 0) { condition = true; }
  8828. if (!Tools._performance) {
  8829. if (!Tools.IsWindowObjectExist()) {
  8830. return;
  8831. }
  8832. Tools._performance = window.performance;
  8833. }
  8834. if (!condition || !Tools._performance.mark) {
  8835. return;
  8836. }
  8837. Tools._performance.mark(counterName + "-Begin");
  8838. };
  8839. Tools._EndUserMark = function (counterName, condition) {
  8840. if (condition === void 0) { condition = true; }
  8841. if (!condition || !Tools._performance.mark) {
  8842. return;
  8843. }
  8844. Tools._performance.mark(counterName + "-End");
  8845. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  8846. };
  8847. Tools._StartPerformanceConsole = function (counterName, condition) {
  8848. if (condition === void 0) { condition = true; }
  8849. if (!condition) {
  8850. return;
  8851. }
  8852. Tools._StartUserMark(counterName, condition);
  8853. if (console.time) {
  8854. console.time(counterName);
  8855. }
  8856. };
  8857. Tools._EndPerformanceConsole = function (counterName, condition) {
  8858. if (condition === void 0) { condition = true; }
  8859. if (!condition) {
  8860. return;
  8861. }
  8862. Tools._EndUserMark(counterName, condition);
  8863. if (console.time) {
  8864. console.timeEnd(counterName);
  8865. }
  8866. };
  8867. Object.defineProperty(Tools, "Now", {
  8868. get: function () {
  8869. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  8870. return window.performance.now();
  8871. }
  8872. return new Date().getTime();
  8873. },
  8874. enumerable: true,
  8875. configurable: true
  8876. });
  8877. /**
  8878. * This method will return the name of the class used to create the instance of the given object.
  8879. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  8880. * @param object the object to get the class name from
  8881. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  8882. */
  8883. Tools.GetClassName = function (object, isType) {
  8884. if (isType === void 0) { isType = false; }
  8885. var name = null;
  8886. if (!isType && object.getClassName) {
  8887. name = object.getClassName();
  8888. }
  8889. else {
  8890. if (object instanceof Object) {
  8891. var classObj = isType ? object : Object.getPrototypeOf(object);
  8892. name = classObj.constructor["__bjsclassName__"];
  8893. }
  8894. if (!name) {
  8895. name = typeof object;
  8896. }
  8897. }
  8898. return name;
  8899. };
  8900. Tools.First = function (array, predicate) {
  8901. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  8902. var el = array_1[_i];
  8903. if (predicate(el)) {
  8904. return el;
  8905. }
  8906. }
  8907. return null;
  8908. };
  8909. /**
  8910. * This method will return the name of the full name of the class, including its owning module (if any).
  8911. * 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).
  8912. * @param object the object to get the class name from
  8913. * @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.
  8914. */
  8915. Tools.getFullClassName = function (object, isType) {
  8916. if (isType === void 0) { isType = false; }
  8917. var className = null;
  8918. var moduleName = null;
  8919. if (!isType && object.getClassName) {
  8920. className = object.getClassName();
  8921. }
  8922. else {
  8923. if (object instanceof Object) {
  8924. var classObj = isType ? object : Object.getPrototypeOf(object);
  8925. className = classObj.constructor["__bjsclassName__"];
  8926. moduleName = classObj.constructor["__bjsmoduleName__"];
  8927. }
  8928. if (!className) {
  8929. className = typeof object;
  8930. }
  8931. }
  8932. if (!className) {
  8933. return null;
  8934. }
  8935. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  8936. };
  8937. /**
  8938. * 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.
  8939. * @param array
  8940. */
  8941. Tools.arrayOrStringFeeder = function (array) {
  8942. return function (index) {
  8943. if (index >= array.length) {
  8944. return null;
  8945. }
  8946. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  8947. if (val && val.getHashCode) {
  8948. val = val.getHashCode();
  8949. }
  8950. if (typeof val === "string") {
  8951. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  8952. }
  8953. return val;
  8954. };
  8955. };
  8956. /**
  8957. * Compute the hashCode of a stream of number
  8958. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  8959. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  8960. * @return the hash code computed
  8961. */
  8962. Tools.hashCodeFromStream = function (feeder) {
  8963. // Based from here: http://stackoverflow.com/a/7616484/802124
  8964. var hash = 0;
  8965. var index = 0;
  8966. var chr = feeder(index++);
  8967. while (chr != null) {
  8968. hash = ((hash << 5) - hash) + chr;
  8969. hash |= 0; // Convert to 32bit integer
  8970. chr = feeder(index++);
  8971. }
  8972. return hash;
  8973. };
  8974. /**
  8975. * Returns a promise that resolves after the given amount of time.
  8976. * @param delay Number of milliseconds to delay
  8977. * @returns Promise that resolves after the given amount of time
  8978. */
  8979. Tools.DelayAsync = function (delay) {
  8980. return new Promise(function (resolve) {
  8981. setTimeout(function () {
  8982. resolve();
  8983. }, delay);
  8984. });
  8985. };
  8986. Tools.BaseUrl = "";
  8987. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  8988. /**
  8989. * Default behaviour for cors in the application.
  8990. * It can be a string if the expected behavior is identical in the entire app.
  8991. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  8992. */
  8993. Tools.CorsBehavior = "anonymous";
  8994. Tools.UseFallbackTexture = true;
  8995. /**
  8996. * Use this object to register external classes like custom textures or material
  8997. * to allow the laoders to instantiate them
  8998. */
  8999. Tools.RegisteredExternalClasses = {};
  9000. // Used in case of a texture loading problem
  9001. 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";
  9002. Tools.PreprocessUrl = function (url) {
  9003. return url;
  9004. };
  9005. // Logs
  9006. Tools._NoneLogLevel = 0;
  9007. Tools._MessageLogLevel = 1;
  9008. Tools._WarningLogLevel = 2;
  9009. Tools._ErrorLogLevel = 4;
  9010. Tools._LogCache = "";
  9011. Tools.errorsCount = 0;
  9012. Tools.Log = Tools._LogEnabled;
  9013. Tools.Warn = Tools._WarnEnabled;
  9014. Tools.Error = Tools._ErrorEnabled;
  9015. // Performances
  9016. Tools._PerformanceNoneLogLevel = 0;
  9017. Tools._PerformanceUserMarkLogLevel = 1;
  9018. Tools._PerformanceConsoleLogLevel = 2;
  9019. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9020. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9021. return Tools;
  9022. }());
  9023. BABYLON.Tools = Tools;
  9024. /**
  9025. * This class is used to track a performance counter which is number based.
  9026. * The user has access to many properties which give statistics of different nature
  9027. *
  9028. * The implementer can track two kinds of Performance Counter: time and count
  9029. * 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.
  9030. * 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.
  9031. */
  9032. var PerfCounter = /** @class */ (function () {
  9033. function PerfCounter() {
  9034. this._startMonitoringTime = 0;
  9035. this._min = 0;
  9036. this._max = 0;
  9037. this._average = 0;
  9038. this._lastSecAverage = 0;
  9039. this._current = 0;
  9040. this._totalValueCount = 0;
  9041. this._totalAccumulated = 0;
  9042. this._lastSecAccumulated = 0;
  9043. this._lastSecTime = 0;
  9044. this._lastSecValueCount = 0;
  9045. }
  9046. Object.defineProperty(PerfCounter.prototype, "min", {
  9047. /**
  9048. * Returns the smallest value ever
  9049. */
  9050. get: function () {
  9051. return this._min;
  9052. },
  9053. enumerable: true,
  9054. configurable: true
  9055. });
  9056. Object.defineProperty(PerfCounter.prototype, "max", {
  9057. /**
  9058. * Returns the biggest value ever
  9059. */
  9060. get: function () {
  9061. return this._max;
  9062. },
  9063. enumerable: true,
  9064. configurable: true
  9065. });
  9066. Object.defineProperty(PerfCounter.prototype, "average", {
  9067. /**
  9068. * Returns the average value since the performance counter is running
  9069. */
  9070. get: function () {
  9071. return this._average;
  9072. },
  9073. enumerable: true,
  9074. configurable: true
  9075. });
  9076. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9077. /**
  9078. * Returns the average value of the last second the counter was monitored
  9079. */
  9080. get: function () {
  9081. return this._lastSecAverage;
  9082. },
  9083. enumerable: true,
  9084. configurable: true
  9085. });
  9086. Object.defineProperty(PerfCounter.prototype, "current", {
  9087. /**
  9088. * Returns the current value
  9089. */
  9090. get: function () {
  9091. return this._current;
  9092. },
  9093. enumerable: true,
  9094. configurable: true
  9095. });
  9096. Object.defineProperty(PerfCounter.prototype, "total", {
  9097. get: function () {
  9098. return this._totalAccumulated;
  9099. },
  9100. enumerable: true,
  9101. configurable: true
  9102. });
  9103. Object.defineProperty(PerfCounter.prototype, "count", {
  9104. get: function () {
  9105. return this._totalValueCount;
  9106. },
  9107. enumerable: true,
  9108. configurable: true
  9109. });
  9110. /**
  9111. * Call this method to start monitoring a new frame.
  9112. * 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.
  9113. */
  9114. PerfCounter.prototype.fetchNewFrame = function () {
  9115. this._totalValueCount++;
  9116. this._current = 0;
  9117. this._lastSecValueCount++;
  9118. };
  9119. /**
  9120. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9121. * @param newCount the count value to add to the monitored count
  9122. * @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.
  9123. */
  9124. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9125. if (!PerfCounter.Enabled) {
  9126. return;
  9127. }
  9128. this._current += newCount;
  9129. if (fetchResult) {
  9130. this._fetchResult();
  9131. }
  9132. };
  9133. /**
  9134. * Start monitoring this performance counter
  9135. */
  9136. PerfCounter.prototype.beginMonitoring = function () {
  9137. if (!PerfCounter.Enabled) {
  9138. return;
  9139. }
  9140. this._startMonitoringTime = Tools.Now;
  9141. };
  9142. /**
  9143. * Compute the time lapsed since the previous beginMonitoring() call.
  9144. * @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
  9145. */
  9146. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9147. if (newFrame === void 0) { newFrame = true; }
  9148. if (!PerfCounter.Enabled) {
  9149. return;
  9150. }
  9151. if (newFrame) {
  9152. this.fetchNewFrame();
  9153. }
  9154. var currentTime = Tools.Now;
  9155. this._current = currentTime - this._startMonitoringTime;
  9156. if (newFrame) {
  9157. this._fetchResult();
  9158. }
  9159. };
  9160. PerfCounter.prototype._fetchResult = function () {
  9161. this._totalAccumulated += this._current;
  9162. this._lastSecAccumulated += this._current;
  9163. // Min/Max update
  9164. this._min = Math.min(this._min, this._current);
  9165. this._max = Math.max(this._max, this._current);
  9166. this._average = this._totalAccumulated / this._totalValueCount;
  9167. // Reset last sec?
  9168. var now = Tools.Now;
  9169. if ((now - this._lastSecTime) > 1000) {
  9170. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9171. this._lastSecTime = now;
  9172. this._lastSecAccumulated = 0;
  9173. this._lastSecValueCount = 0;
  9174. }
  9175. };
  9176. PerfCounter.Enabled = true;
  9177. return PerfCounter;
  9178. }());
  9179. BABYLON.PerfCounter = PerfCounter;
  9180. /**
  9181. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9182. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9183. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9184. * @param name The name of the class, case should be preserved
  9185. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9186. */
  9187. function className(name, module) {
  9188. return function (target) {
  9189. target["__bjsclassName__"] = name;
  9190. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9191. };
  9192. }
  9193. BABYLON.className = className;
  9194. /**
  9195. * An implementation of a loop for asynchronous functions.
  9196. */
  9197. var AsyncLoop = /** @class */ (function () {
  9198. /**
  9199. * Constroctor.
  9200. * @param iterations the number of iterations.
  9201. * @param _fn the function to run each iteration
  9202. * @param _successCallback the callback that will be called upon succesful execution
  9203. * @param offset starting offset.
  9204. */
  9205. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9206. if (offset === void 0) { offset = 0; }
  9207. this.iterations = iterations;
  9208. this._fn = _fn;
  9209. this._successCallback = _successCallback;
  9210. this.index = offset - 1;
  9211. this._done = false;
  9212. }
  9213. /**
  9214. * Execute the next iteration. Must be called after the last iteration was finished.
  9215. */
  9216. AsyncLoop.prototype.executeNext = function () {
  9217. if (!this._done) {
  9218. if (this.index + 1 < this.iterations) {
  9219. ++this.index;
  9220. this._fn(this);
  9221. }
  9222. else {
  9223. this.breakLoop();
  9224. }
  9225. }
  9226. };
  9227. /**
  9228. * Break the loop and run the success callback.
  9229. */
  9230. AsyncLoop.prototype.breakLoop = function () {
  9231. this._done = true;
  9232. this._successCallback();
  9233. };
  9234. /**
  9235. * Helper function
  9236. */
  9237. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9238. if (offset === void 0) { offset = 0; }
  9239. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9240. loop.executeNext();
  9241. return loop;
  9242. };
  9243. /**
  9244. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9245. * @param iterations total number of iterations
  9246. * @param syncedIterations number of synchronous iterations in each async iteration.
  9247. * @param fn the function to call each iteration.
  9248. * @param callback a success call back that will be called when iterating stops.
  9249. * @param breakFunction a break condition (optional)
  9250. * @param timeout timeout settings for the setTimeout function. default - 0.
  9251. * @constructor
  9252. */
  9253. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9254. if (timeout === void 0) { timeout = 0; }
  9255. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9256. if (breakFunction && breakFunction())
  9257. loop.breakLoop();
  9258. else {
  9259. setTimeout(function () {
  9260. for (var i = 0; i < syncedIterations; ++i) {
  9261. var iteration = (loop.index * syncedIterations) + i;
  9262. if (iteration >= iterations)
  9263. break;
  9264. fn(iteration);
  9265. if (breakFunction && breakFunction()) {
  9266. loop.breakLoop();
  9267. break;
  9268. }
  9269. }
  9270. loop.executeNext();
  9271. }, timeout);
  9272. }
  9273. }, callback);
  9274. };
  9275. return AsyncLoop;
  9276. }());
  9277. BABYLON.AsyncLoop = AsyncLoop;
  9278. })(BABYLON || (BABYLON = {}));
  9279. //# sourceMappingURL=babylon.tools.js.map
  9280. var BABYLON;
  9281. (function (BABYLON) {
  9282. var PromiseStates;
  9283. (function (PromiseStates) {
  9284. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9285. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9286. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9287. })(PromiseStates || (PromiseStates = {}));
  9288. var FulFillmentAgregator = /** @class */ (function () {
  9289. function FulFillmentAgregator() {
  9290. this.count = 0;
  9291. this.target = 0;
  9292. this.results = [];
  9293. }
  9294. return FulFillmentAgregator;
  9295. }());
  9296. var InternalPromise = /** @class */ (function () {
  9297. function InternalPromise(resolver) {
  9298. var _this = this;
  9299. this._state = PromiseStates.Pending;
  9300. this._children = new Array();
  9301. this._rejectWasConsumed = false;
  9302. if (!resolver) {
  9303. return;
  9304. }
  9305. try {
  9306. resolver(function (value) {
  9307. _this._resolve(value);
  9308. }, function (reason) {
  9309. _this._reject(reason);
  9310. });
  9311. }
  9312. catch (e) {
  9313. this._reject(e);
  9314. }
  9315. }
  9316. InternalPromise.prototype.catch = function (onRejected) {
  9317. return this.then(undefined, onRejected);
  9318. };
  9319. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9320. var _this = this;
  9321. var newPromise = new InternalPromise();
  9322. newPromise._onFulfilled = onFulfilled;
  9323. newPromise._onRejected = onRejected;
  9324. // Composition
  9325. this._children.push(newPromise);
  9326. if (this._state !== PromiseStates.Pending) {
  9327. BABYLON.Tools.SetImmediate(function () {
  9328. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9329. var returnedValue = newPromise._resolve(_this._result);
  9330. if (returnedValue !== undefined && returnedValue !== null) {
  9331. if (returnedValue._state !== undefined) {
  9332. var returnedPromise = returnedValue;
  9333. newPromise._children.push(returnedPromise);
  9334. newPromise = returnedPromise;
  9335. }
  9336. else {
  9337. newPromise._result = returnedValue;
  9338. }
  9339. }
  9340. }
  9341. else {
  9342. newPromise._reject(_this._reason);
  9343. }
  9344. });
  9345. }
  9346. return newPromise;
  9347. };
  9348. InternalPromise.prototype._moveChildren = function (children) {
  9349. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9350. if (this._state === PromiseStates.Fulfilled) {
  9351. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9352. var child = _b[_i];
  9353. child._resolve(this._result);
  9354. }
  9355. }
  9356. else if (this._state === PromiseStates.Rejected) {
  9357. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9358. var child = _d[_c];
  9359. child._reject(this._reason);
  9360. }
  9361. }
  9362. var _a;
  9363. };
  9364. InternalPromise.prototype._resolve = function (value) {
  9365. try {
  9366. this._state = PromiseStates.Fulfilled;
  9367. this._result = value;
  9368. var returnedValue = null;
  9369. if (this._onFulfilled) {
  9370. returnedValue = this._onFulfilled(value);
  9371. }
  9372. if (returnedValue !== undefined && returnedValue !== null) {
  9373. if (returnedValue._state !== undefined) {
  9374. // Transmit children
  9375. var returnedPromise = returnedValue;
  9376. returnedPromise._moveChildren(this._children);
  9377. }
  9378. else {
  9379. value = returnedValue;
  9380. }
  9381. }
  9382. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9383. var child = _a[_i];
  9384. child._resolve(value);
  9385. }
  9386. this._children.length = 0;
  9387. delete this._onFulfilled;
  9388. delete this._onRejected;
  9389. return returnedValue;
  9390. }
  9391. catch (e) {
  9392. this._reject(e, true);
  9393. }
  9394. return null;
  9395. };
  9396. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9397. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9398. this._state = PromiseStates.Rejected;
  9399. this._reason = reason;
  9400. if (this._onRejected && !onLocalThrow) {
  9401. try {
  9402. this._onRejected(reason);
  9403. this._rejectWasConsumed = true;
  9404. }
  9405. catch (e) {
  9406. reason = e;
  9407. }
  9408. }
  9409. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9410. var child = _a[_i];
  9411. if (this._rejectWasConsumed) {
  9412. child._resolve(null);
  9413. }
  9414. else {
  9415. child._reject(reason);
  9416. }
  9417. }
  9418. this._children.length = 0;
  9419. delete this._onFulfilled;
  9420. delete this._onRejected;
  9421. };
  9422. InternalPromise.resolve = function (value) {
  9423. var newPromise = new InternalPromise();
  9424. newPromise._resolve(value);
  9425. return newPromise;
  9426. };
  9427. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9428. promise.then(function (value) {
  9429. agregator.results[index] = value;
  9430. agregator.count++;
  9431. if (agregator.count === agregator.target) {
  9432. agregator.rootPromise._resolve(agregator.results);
  9433. }
  9434. return null;
  9435. }, function (reason) {
  9436. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9437. agregator.rootPromise._reject(reason);
  9438. }
  9439. });
  9440. };
  9441. InternalPromise.all = function (promises) {
  9442. var newPromise = new InternalPromise();
  9443. var agregator = new FulFillmentAgregator();
  9444. agregator.target = promises.length;
  9445. agregator.rootPromise = newPromise;
  9446. if (promises.length) {
  9447. for (var index = 0; index < promises.length; index++) {
  9448. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9449. }
  9450. }
  9451. else {
  9452. newPromise._resolve([]);
  9453. }
  9454. return newPromise;
  9455. };
  9456. return InternalPromise;
  9457. }());
  9458. /**
  9459. * Helper class that provides a small promise polyfill
  9460. */
  9461. var PromisePolyfill = /** @class */ (function () {
  9462. function PromisePolyfill() {
  9463. }
  9464. /**
  9465. * Static function used to check if the polyfill is required
  9466. * If this is the case then the function will inject the polyfill to window.Promise
  9467. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9468. */
  9469. PromisePolyfill.Apply = function (force) {
  9470. if (force === void 0) { force = false; }
  9471. if (force || typeof Promise === 'undefined') {
  9472. var root = window;
  9473. root.Promise = InternalPromise;
  9474. }
  9475. };
  9476. return PromisePolyfill;
  9477. }());
  9478. BABYLON.PromisePolyfill = PromisePolyfill;
  9479. })(BABYLON || (BABYLON = {}));
  9480. //# sourceMappingURL=babylon.promise.js.map
  9481. var BABYLON;
  9482. (function (BABYLON) {
  9483. var _AlphaState = /** @class */ (function () {
  9484. /**
  9485. * Initializes the state.
  9486. */
  9487. function _AlphaState() {
  9488. this._isAlphaBlendDirty = false;
  9489. this._isBlendFunctionParametersDirty = false;
  9490. this._isBlendEquationParametersDirty = false;
  9491. this._isBlendConstantsDirty = false;
  9492. this._alphaBlend = false;
  9493. this._blendFunctionParameters = new Array(4);
  9494. this._blendEquationParameters = new Array(2);
  9495. this._blendConstants = new Array(4);
  9496. this.reset();
  9497. }
  9498. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9499. get: function () {
  9500. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9501. },
  9502. enumerable: true,
  9503. configurable: true
  9504. });
  9505. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9506. get: function () {
  9507. return this._alphaBlend;
  9508. },
  9509. set: function (value) {
  9510. if (this._alphaBlend === value) {
  9511. return;
  9512. }
  9513. this._alphaBlend = value;
  9514. this._isAlphaBlendDirty = true;
  9515. },
  9516. enumerable: true,
  9517. configurable: true
  9518. });
  9519. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9520. if (this._blendConstants[0] === r &&
  9521. this._blendConstants[1] === g &&
  9522. this._blendConstants[2] === b &&
  9523. this._blendConstants[3] === a) {
  9524. return;
  9525. }
  9526. this._blendConstants[0] = r;
  9527. this._blendConstants[1] = g;
  9528. this._blendConstants[2] = b;
  9529. this._blendConstants[3] = a;
  9530. this._isBlendConstantsDirty = true;
  9531. };
  9532. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9533. if (this._blendFunctionParameters[0] === value0 &&
  9534. this._blendFunctionParameters[1] === value1 &&
  9535. this._blendFunctionParameters[2] === value2 &&
  9536. this._blendFunctionParameters[3] === value3) {
  9537. return;
  9538. }
  9539. this._blendFunctionParameters[0] = value0;
  9540. this._blendFunctionParameters[1] = value1;
  9541. this._blendFunctionParameters[2] = value2;
  9542. this._blendFunctionParameters[3] = value3;
  9543. this._isBlendFunctionParametersDirty = true;
  9544. };
  9545. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9546. if (this._blendEquationParameters[0] === rgb &&
  9547. this._blendEquationParameters[1] === alpha) {
  9548. return;
  9549. }
  9550. this._blendEquationParameters[0] = rgb;
  9551. this._blendEquationParameters[1] = alpha;
  9552. this._isBlendEquationParametersDirty = true;
  9553. };
  9554. _AlphaState.prototype.reset = function () {
  9555. this._alphaBlend = false;
  9556. this._blendFunctionParameters[0] = null;
  9557. this._blendFunctionParameters[1] = null;
  9558. this._blendFunctionParameters[2] = null;
  9559. this._blendFunctionParameters[3] = null;
  9560. this._blendEquationParameters[0] = null;
  9561. this._blendEquationParameters[1] = null;
  9562. this._blendConstants[0] = null;
  9563. this._blendConstants[1] = null;
  9564. this._blendConstants[2] = null;
  9565. this._blendConstants[3] = null;
  9566. this._isAlphaBlendDirty = true;
  9567. this._isBlendFunctionParametersDirty = false;
  9568. this._isBlendEquationParametersDirty = false;
  9569. this._isBlendConstantsDirty = false;
  9570. };
  9571. _AlphaState.prototype.apply = function (gl) {
  9572. if (!this.isDirty) {
  9573. return;
  9574. }
  9575. // Alpha blend
  9576. if (this._isAlphaBlendDirty) {
  9577. if (this._alphaBlend) {
  9578. gl.enable(gl.BLEND);
  9579. }
  9580. else {
  9581. gl.disable(gl.BLEND);
  9582. }
  9583. this._isAlphaBlendDirty = false;
  9584. }
  9585. // Alpha function
  9586. if (this._isBlendFunctionParametersDirty) {
  9587. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9588. this._isBlendFunctionParametersDirty = false;
  9589. }
  9590. // Alpha equation
  9591. if (this._isBlendEquationParametersDirty) {
  9592. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9593. this._isBlendEquationParametersDirty = false;
  9594. }
  9595. // Constants
  9596. if (this._isBlendConstantsDirty) {
  9597. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9598. this._isBlendConstantsDirty = false;
  9599. }
  9600. };
  9601. return _AlphaState;
  9602. }());
  9603. BABYLON._AlphaState = _AlphaState;
  9604. })(BABYLON || (BABYLON = {}));
  9605. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9606. var BABYLON;
  9607. (function (BABYLON) {
  9608. var _DepthCullingState = /** @class */ (function () {
  9609. /**
  9610. * Initializes the state.
  9611. */
  9612. function _DepthCullingState() {
  9613. this._isDepthTestDirty = false;
  9614. this._isDepthMaskDirty = false;
  9615. this._isDepthFuncDirty = false;
  9616. this._isCullFaceDirty = false;
  9617. this._isCullDirty = false;
  9618. this._isZOffsetDirty = false;
  9619. this._isFrontFaceDirty = false;
  9620. this.reset();
  9621. }
  9622. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9623. get: function () {
  9624. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9625. },
  9626. enumerable: true,
  9627. configurable: true
  9628. });
  9629. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9630. get: function () {
  9631. return this._zOffset;
  9632. },
  9633. set: function (value) {
  9634. if (this._zOffset === value) {
  9635. return;
  9636. }
  9637. this._zOffset = value;
  9638. this._isZOffsetDirty = true;
  9639. },
  9640. enumerable: true,
  9641. configurable: true
  9642. });
  9643. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9644. get: function () {
  9645. return this._cullFace;
  9646. },
  9647. set: function (value) {
  9648. if (this._cullFace === value) {
  9649. return;
  9650. }
  9651. this._cullFace = value;
  9652. this._isCullFaceDirty = true;
  9653. },
  9654. enumerable: true,
  9655. configurable: true
  9656. });
  9657. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  9658. get: function () {
  9659. return this._cull;
  9660. },
  9661. set: function (value) {
  9662. if (this._cull === value) {
  9663. return;
  9664. }
  9665. this._cull = value;
  9666. this._isCullDirty = true;
  9667. },
  9668. enumerable: true,
  9669. configurable: true
  9670. });
  9671. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  9672. get: function () {
  9673. return this._depthFunc;
  9674. },
  9675. set: function (value) {
  9676. if (this._depthFunc === value) {
  9677. return;
  9678. }
  9679. this._depthFunc = value;
  9680. this._isDepthFuncDirty = true;
  9681. },
  9682. enumerable: true,
  9683. configurable: true
  9684. });
  9685. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  9686. get: function () {
  9687. return this._depthMask;
  9688. },
  9689. set: function (value) {
  9690. if (this._depthMask === value) {
  9691. return;
  9692. }
  9693. this._depthMask = value;
  9694. this._isDepthMaskDirty = true;
  9695. },
  9696. enumerable: true,
  9697. configurable: true
  9698. });
  9699. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  9700. get: function () {
  9701. return this._depthTest;
  9702. },
  9703. set: function (value) {
  9704. if (this._depthTest === value) {
  9705. return;
  9706. }
  9707. this._depthTest = value;
  9708. this._isDepthTestDirty = true;
  9709. },
  9710. enumerable: true,
  9711. configurable: true
  9712. });
  9713. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  9714. get: function () {
  9715. return this._frontFace;
  9716. },
  9717. set: function (value) {
  9718. if (this._frontFace === value) {
  9719. return;
  9720. }
  9721. this._frontFace = value;
  9722. this._isFrontFaceDirty = true;
  9723. },
  9724. enumerable: true,
  9725. configurable: true
  9726. });
  9727. _DepthCullingState.prototype.reset = function () {
  9728. this._depthMask = true;
  9729. this._depthTest = true;
  9730. this._depthFunc = null;
  9731. this._cullFace = null;
  9732. this._cull = null;
  9733. this._zOffset = 0;
  9734. this._frontFace = null;
  9735. this._isDepthTestDirty = true;
  9736. this._isDepthMaskDirty = true;
  9737. this._isDepthFuncDirty = false;
  9738. this._isCullFaceDirty = false;
  9739. this._isCullDirty = false;
  9740. this._isZOffsetDirty = false;
  9741. this._isFrontFaceDirty = false;
  9742. };
  9743. _DepthCullingState.prototype.apply = function (gl) {
  9744. if (!this.isDirty) {
  9745. return;
  9746. }
  9747. // Cull
  9748. if (this._isCullDirty) {
  9749. if (this.cull) {
  9750. gl.enable(gl.CULL_FACE);
  9751. }
  9752. else {
  9753. gl.disable(gl.CULL_FACE);
  9754. }
  9755. this._isCullDirty = false;
  9756. }
  9757. // Cull face
  9758. if (this._isCullFaceDirty) {
  9759. gl.cullFace(this.cullFace);
  9760. this._isCullFaceDirty = false;
  9761. }
  9762. // Depth mask
  9763. if (this._isDepthMaskDirty) {
  9764. gl.depthMask(this.depthMask);
  9765. this._isDepthMaskDirty = false;
  9766. }
  9767. // Depth test
  9768. if (this._isDepthTestDirty) {
  9769. if (this.depthTest) {
  9770. gl.enable(gl.DEPTH_TEST);
  9771. }
  9772. else {
  9773. gl.disable(gl.DEPTH_TEST);
  9774. }
  9775. this._isDepthTestDirty = false;
  9776. }
  9777. // Depth func
  9778. if (this._isDepthFuncDirty) {
  9779. gl.depthFunc(this.depthFunc);
  9780. this._isDepthFuncDirty = false;
  9781. }
  9782. // zOffset
  9783. if (this._isZOffsetDirty) {
  9784. if (this.zOffset) {
  9785. gl.enable(gl.POLYGON_OFFSET_FILL);
  9786. gl.polygonOffset(this.zOffset, 0);
  9787. }
  9788. else {
  9789. gl.disable(gl.POLYGON_OFFSET_FILL);
  9790. }
  9791. this._isZOffsetDirty = false;
  9792. }
  9793. // Front face
  9794. if (this._isFrontFaceDirty) {
  9795. gl.frontFace(this.frontFace);
  9796. this._isFrontFaceDirty = false;
  9797. }
  9798. };
  9799. return _DepthCullingState;
  9800. }());
  9801. BABYLON._DepthCullingState = _DepthCullingState;
  9802. })(BABYLON || (BABYLON = {}));
  9803. //# sourceMappingURL=babylon.depthCullingState.js.map
  9804. var BABYLON;
  9805. (function (BABYLON) {
  9806. var _StencilState = /** @class */ (function () {
  9807. function _StencilState() {
  9808. this._isStencilTestDirty = false;
  9809. this._isStencilMaskDirty = false;
  9810. this._isStencilFuncDirty = false;
  9811. this._isStencilOpDirty = false;
  9812. this.reset();
  9813. }
  9814. Object.defineProperty(_StencilState.prototype, "isDirty", {
  9815. get: function () {
  9816. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  9817. },
  9818. enumerable: true,
  9819. configurable: true
  9820. });
  9821. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  9822. get: function () {
  9823. return this._stencilFunc;
  9824. },
  9825. set: function (value) {
  9826. if (this._stencilFunc === value) {
  9827. return;
  9828. }
  9829. this._stencilFunc = value;
  9830. this._isStencilFuncDirty = true;
  9831. },
  9832. enumerable: true,
  9833. configurable: true
  9834. });
  9835. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  9836. get: function () {
  9837. return this._stencilFuncRef;
  9838. },
  9839. set: function (value) {
  9840. if (this._stencilFuncRef === value) {
  9841. return;
  9842. }
  9843. this._stencilFuncRef = value;
  9844. this._isStencilFuncDirty = true;
  9845. },
  9846. enumerable: true,
  9847. configurable: true
  9848. });
  9849. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  9850. get: function () {
  9851. return this._stencilFuncMask;
  9852. },
  9853. set: function (value) {
  9854. if (this._stencilFuncMask === value) {
  9855. return;
  9856. }
  9857. this._stencilFuncMask = value;
  9858. this._isStencilFuncDirty = true;
  9859. },
  9860. enumerable: true,
  9861. configurable: true
  9862. });
  9863. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  9864. get: function () {
  9865. return this._stencilOpStencilFail;
  9866. },
  9867. set: function (value) {
  9868. if (this._stencilOpStencilFail === value) {
  9869. return;
  9870. }
  9871. this._stencilOpStencilFail = value;
  9872. this._isStencilOpDirty = true;
  9873. },
  9874. enumerable: true,
  9875. configurable: true
  9876. });
  9877. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  9878. get: function () {
  9879. return this._stencilOpDepthFail;
  9880. },
  9881. set: function (value) {
  9882. if (this._stencilOpDepthFail === value) {
  9883. return;
  9884. }
  9885. this._stencilOpDepthFail = value;
  9886. this._isStencilOpDirty = true;
  9887. },
  9888. enumerable: true,
  9889. configurable: true
  9890. });
  9891. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  9892. get: function () {
  9893. return this._stencilOpStencilDepthPass;
  9894. },
  9895. set: function (value) {
  9896. if (this._stencilOpStencilDepthPass === value) {
  9897. return;
  9898. }
  9899. this._stencilOpStencilDepthPass = value;
  9900. this._isStencilOpDirty = true;
  9901. },
  9902. enumerable: true,
  9903. configurable: true
  9904. });
  9905. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  9906. get: function () {
  9907. return this._stencilMask;
  9908. },
  9909. set: function (value) {
  9910. if (this._stencilMask === value) {
  9911. return;
  9912. }
  9913. this._stencilMask = value;
  9914. this._isStencilMaskDirty = true;
  9915. },
  9916. enumerable: true,
  9917. configurable: true
  9918. });
  9919. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  9920. get: function () {
  9921. return this._stencilTest;
  9922. },
  9923. set: function (value) {
  9924. if (this._stencilTest === value) {
  9925. return;
  9926. }
  9927. this._stencilTest = value;
  9928. this._isStencilTestDirty = true;
  9929. },
  9930. enumerable: true,
  9931. configurable: true
  9932. });
  9933. _StencilState.prototype.reset = function () {
  9934. this._stencilTest = false;
  9935. this._stencilMask = 0xFF;
  9936. this._stencilFunc = BABYLON.Engine.ALWAYS;
  9937. this._stencilFuncRef = 1;
  9938. this._stencilFuncMask = 0xFF;
  9939. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  9940. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  9941. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  9942. this._isStencilTestDirty = true;
  9943. this._isStencilMaskDirty = true;
  9944. this._isStencilFuncDirty = true;
  9945. this._isStencilOpDirty = true;
  9946. };
  9947. _StencilState.prototype.apply = function (gl) {
  9948. if (!this.isDirty) {
  9949. return;
  9950. }
  9951. // Stencil test
  9952. if (this._isStencilTestDirty) {
  9953. if (this.stencilTest) {
  9954. gl.enable(gl.STENCIL_TEST);
  9955. }
  9956. else {
  9957. gl.disable(gl.STENCIL_TEST);
  9958. }
  9959. this._isStencilTestDirty = false;
  9960. }
  9961. // Stencil mask
  9962. if (this._isStencilMaskDirty) {
  9963. gl.stencilMask(this.stencilMask);
  9964. this._isStencilMaskDirty = false;
  9965. }
  9966. // Stencil func
  9967. if (this._isStencilFuncDirty) {
  9968. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  9969. this._isStencilFuncDirty = false;
  9970. }
  9971. // Stencil op
  9972. if (this._isStencilOpDirty) {
  9973. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  9974. this._isStencilOpDirty = false;
  9975. }
  9976. };
  9977. return _StencilState;
  9978. }());
  9979. BABYLON._StencilState = _StencilState;
  9980. })(BABYLON || (BABYLON = {}));
  9981. //# sourceMappingURL=babylon.stencilState.js.map
  9982. var __assign = (this && this.__assign) || Object.assign || function(t) {
  9983. for (var s, i = 1, n = arguments.length; i < n; i++) {
  9984. s = arguments[i];
  9985. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  9986. t[p] = s[p];
  9987. }
  9988. return t;
  9989. };
  9990. var BABYLON;
  9991. (function (BABYLON) {
  9992. var compileShader = function (gl, source, type, defines, shaderVersion) {
  9993. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  9994. };
  9995. var compileRawShader = function (gl, source, type) {
  9996. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  9997. gl.shaderSource(shader, source);
  9998. gl.compileShader(shader);
  9999. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10000. var log = gl.getShaderInfoLog(shader);
  10001. if (log) {
  10002. throw new Error(log);
  10003. }
  10004. }
  10005. if (!shader) {
  10006. throw new Error("Something went wrong while compile the shader.");
  10007. }
  10008. return shader;
  10009. };
  10010. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10011. var magFilter = gl.NEAREST;
  10012. var minFilter = gl.NEAREST;
  10013. switch (samplingMode) {
  10014. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10015. magFilter = gl.LINEAR;
  10016. if (generateMipMaps) {
  10017. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10018. }
  10019. else {
  10020. minFilter = gl.LINEAR;
  10021. }
  10022. break;
  10023. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10024. magFilter = gl.LINEAR;
  10025. if (generateMipMaps) {
  10026. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10027. }
  10028. else {
  10029. minFilter = gl.LINEAR;
  10030. }
  10031. break;
  10032. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10033. magFilter = gl.NEAREST;
  10034. if (generateMipMaps) {
  10035. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10036. }
  10037. else {
  10038. minFilter = gl.NEAREST;
  10039. }
  10040. break;
  10041. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10042. magFilter = gl.NEAREST;
  10043. if (generateMipMaps) {
  10044. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10045. }
  10046. else {
  10047. minFilter = gl.NEAREST;
  10048. }
  10049. break;
  10050. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10051. magFilter = gl.NEAREST;
  10052. if (generateMipMaps) {
  10053. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10054. }
  10055. else {
  10056. minFilter = gl.LINEAR;
  10057. }
  10058. break;
  10059. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10060. magFilter = gl.NEAREST;
  10061. if (generateMipMaps) {
  10062. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10063. }
  10064. else {
  10065. minFilter = gl.LINEAR;
  10066. }
  10067. break;
  10068. case BABYLON.Texture.NEAREST_LINEAR:
  10069. magFilter = gl.NEAREST;
  10070. minFilter = gl.LINEAR;
  10071. break;
  10072. case BABYLON.Texture.NEAREST_NEAREST:
  10073. magFilter = gl.NEAREST;
  10074. minFilter = gl.NEAREST;
  10075. break;
  10076. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10077. magFilter = gl.LINEAR;
  10078. if (generateMipMaps) {
  10079. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10080. }
  10081. else {
  10082. minFilter = gl.NEAREST;
  10083. }
  10084. break;
  10085. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10086. magFilter = gl.LINEAR;
  10087. if (generateMipMaps) {
  10088. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10089. }
  10090. else {
  10091. minFilter = gl.NEAREST;
  10092. }
  10093. break;
  10094. case BABYLON.Texture.LINEAR_LINEAR:
  10095. magFilter = gl.LINEAR;
  10096. minFilter = gl.LINEAR;
  10097. break;
  10098. case BABYLON.Texture.LINEAR_NEAREST:
  10099. magFilter = gl.LINEAR;
  10100. minFilter = gl.NEAREST;
  10101. break;
  10102. }
  10103. return {
  10104. min: minFilter,
  10105. mag: magFilter
  10106. };
  10107. };
  10108. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10109. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10110. var img;
  10111. var onload = function () {
  10112. loadedImages[index] = img;
  10113. loadedImages._internalCount++;
  10114. if (scene) {
  10115. scene._removePendingData(img);
  10116. }
  10117. if (loadedImages._internalCount === 6) {
  10118. onfinish(loadedImages);
  10119. }
  10120. };
  10121. var onerror = function (message, exception) {
  10122. if (scene) {
  10123. scene._removePendingData(img);
  10124. }
  10125. if (onErrorCallBack) {
  10126. onErrorCallBack(message, exception);
  10127. }
  10128. };
  10129. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10130. if (scene) {
  10131. scene._addPendingData(img);
  10132. }
  10133. };
  10134. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10135. if (onError === void 0) { onError = null; }
  10136. var loadedImages = [];
  10137. loadedImages._internalCount = 0;
  10138. for (var index = 0; index < 6; index++) {
  10139. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10140. }
  10141. };
  10142. var BufferPointer = /** @class */ (function () {
  10143. function BufferPointer() {
  10144. }
  10145. return BufferPointer;
  10146. }());
  10147. var InstancingAttributeInfo = /** @class */ (function () {
  10148. function InstancingAttributeInfo() {
  10149. }
  10150. return InstancingAttributeInfo;
  10151. }());
  10152. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10153. /**
  10154. * Define options used to create a render target texture
  10155. */
  10156. var RenderTargetCreationOptions = /** @class */ (function () {
  10157. function RenderTargetCreationOptions() {
  10158. }
  10159. return RenderTargetCreationOptions;
  10160. }());
  10161. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10162. /**
  10163. * Regroup several parameters relative to the browser in use
  10164. */
  10165. var EngineCapabilities = /** @class */ (function () {
  10166. function EngineCapabilities() {
  10167. }
  10168. return EngineCapabilities;
  10169. }());
  10170. BABYLON.EngineCapabilities = EngineCapabilities;
  10171. /**
  10172. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10173. */
  10174. var Engine = /** @class */ (function () {
  10175. /**
  10176. * @constructor
  10177. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10178. * @param antialias defines enable antialiasing (default: false)
  10179. * @param options defines further options to be sent to the getContext() function
  10180. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10181. */
  10182. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10183. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10184. var _this = this;
  10185. // Public members
  10186. this.forcePOTTextures = false;
  10187. this.isFullscreen = false;
  10188. this.isPointerLock = false;
  10189. this.cullBackFaces = true;
  10190. this.renderEvenInBackground = true;
  10191. this.preventCacheWipeBetweenFrames = false;
  10192. // To enable/disable IDB support and avoid XHR on .manifest
  10193. this.enableOfflineSupport = false;
  10194. this.scenes = new Array();
  10195. this.postProcesses = new Array();
  10196. // Observables
  10197. /**
  10198. * Observable event triggered each time the rendering canvas is resized
  10199. */
  10200. this.onResizeObservable = new BABYLON.Observable();
  10201. /**
  10202. * Observable event triggered each time the canvas loses focus
  10203. */
  10204. this.onCanvasBlurObservable = new BABYLON.Observable();
  10205. /**
  10206. * Observable event triggered each time the canvas gains focus
  10207. */
  10208. this.onCanvasFocusObservable = new BABYLON.Observable();
  10209. /**
  10210. * Observable event triggered each time the canvas receives pointerout event
  10211. */
  10212. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10213. /**
  10214. * Observable event triggered before each texture is initialized
  10215. */
  10216. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10217. //WebVR
  10218. this._vrDisplay = undefined;
  10219. this._vrSupported = false;
  10220. this._vrExclusivePointerMode = false;
  10221. // Uniform buffers list
  10222. this.disableUniformBuffers = false;
  10223. this._uniformBuffers = new Array();
  10224. // Observables
  10225. /**
  10226. * Observable raised when the engine begins a new frame
  10227. */
  10228. this.onBeginFrameObservable = new BABYLON.Observable();
  10229. /**
  10230. * Observable raised when the engine ends the current frame
  10231. */
  10232. this.onEndFrameObservable = new BABYLON.Observable();
  10233. /**
  10234. * Observable raised when the engine is about to compile a shader
  10235. */
  10236. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10237. /**
  10238. * Observable raised when the engine has jsut compiled a shader
  10239. */
  10240. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10241. this._windowIsBackground = false;
  10242. this._webGLVersion = 1.0;
  10243. this._badOS = false;
  10244. this._badDesktopOS = false;
  10245. /**
  10246. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10247. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10248. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10249. */
  10250. this.disableTextureBindingOptimization = false;
  10251. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10252. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10253. this.onVRRequestPresentStart = new BABYLON.Observable();
  10254. this._colorWrite = true;
  10255. this._drawCalls = new BABYLON.PerfCounter();
  10256. this._textureCollisions = new BABYLON.PerfCounter();
  10257. this._renderingQueueLaunched = false;
  10258. this._activeRenderLoops = new Array();
  10259. // Deterministic lockstepMaxSteps
  10260. this._deterministicLockstep = false;
  10261. this._lockstepMaxSteps = 4;
  10262. // Lost context
  10263. this.onContextLostObservable = new BABYLON.Observable();
  10264. this.onContextRestoredObservable = new BABYLON.Observable();
  10265. this._contextWasLost = false;
  10266. this._doNotHandleContextLost = false;
  10267. // FPS
  10268. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10269. this._fps = 60;
  10270. this._deltaTime = 0;
  10271. /**
  10272. * Turn this value on if you want to pause FPS computation when in background
  10273. */
  10274. this.disablePerformanceMonitorInBackground = false;
  10275. // States
  10276. this._depthCullingState = new BABYLON._DepthCullingState();
  10277. this._stencilState = new BABYLON._StencilState();
  10278. this._alphaState = new BABYLON._AlphaState();
  10279. this._alphaMode = Engine.ALPHA_DISABLE;
  10280. // Cache
  10281. this._internalTexturesCache = new Array();
  10282. this._activeChannel = 0;
  10283. this._currentTextureChannel = -1;
  10284. this._boundTexturesCache = {};
  10285. this._compiledEffects = {};
  10286. this._vertexAttribArraysEnabled = [];
  10287. this._uintIndicesCurrentlySet = false;
  10288. this._currentBoundBuffer = new Array();
  10289. this._currentBufferPointers = new Array();
  10290. this._currentInstanceLocations = new Array();
  10291. this._currentInstanceBuffers = new Array();
  10292. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10293. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10294. this._vaoRecordInProgress = false;
  10295. this._mustWipeVertexAttributes = false;
  10296. this._nextFreeTextureSlots = new Array();
  10297. this._maxSimultaneousTextures = 0;
  10298. this._activeRequests = new Array();
  10299. // Hardware supported Compressed Textures
  10300. this._texturesSupported = new Array();
  10301. this._onVRFullScreenTriggered = function () {
  10302. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10303. //get the old size before we change
  10304. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10305. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10306. //get the width and height, change the render size
  10307. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10308. _this.setHardwareScalingLevel(1);
  10309. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10310. }
  10311. else {
  10312. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10313. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10314. }
  10315. };
  10316. this._boundUniforms = {};
  10317. // Register promises
  10318. BABYLON.PromisePolyfill.Apply();
  10319. var canvas = null;
  10320. Engine.Instances.push(this);
  10321. if (!canvasOrContext) {
  10322. return;
  10323. }
  10324. options = options || {};
  10325. if (canvasOrContext.getContext) {
  10326. canvas = canvasOrContext;
  10327. this._renderingCanvas = canvas;
  10328. if (antialias != null) {
  10329. options.antialias = antialias;
  10330. }
  10331. if (options.deterministicLockstep === undefined) {
  10332. options.deterministicLockstep = false;
  10333. }
  10334. if (options.lockstepMaxSteps === undefined) {
  10335. options.lockstepMaxSteps = 4;
  10336. }
  10337. if (options.preserveDrawingBuffer === undefined) {
  10338. options.preserveDrawingBuffer = false;
  10339. }
  10340. if (options.audioEngine === undefined) {
  10341. options.audioEngine = true;
  10342. }
  10343. if (options.stencil === undefined) {
  10344. options.stencil = true;
  10345. }
  10346. this._deterministicLockstep = options.deterministicLockstep;
  10347. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10348. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10349. // Exceptions
  10350. if (navigator && navigator.userAgent) {
  10351. var ua = navigator.userAgent;
  10352. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10353. var exception = _a[_i];
  10354. var key = exception.key;
  10355. var targets = exception.targets;
  10356. if (ua.indexOf(key) > -1) {
  10357. if (exception.capture && exception.captureConstraint) {
  10358. var capture = exception.capture;
  10359. var constraint = exception.captureConstraint;
  10360. var regex = new RegExp(capture);
  10361. var matches = regex.exec(ua);
  10362. if (matches && matches.length > 0) {
  10363. var capturedValue = parseInt(matches[matches.length - 1]);
  10364. if (capturedValue >= constraint) {
  10365. continue;
  10366. }
  10367. }
  10368. }
  10369. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10370. var target = targets_1[_b];
  10371. switch (target) {
  10372. case "uniformBuffer":
  10373. this.disableUniformBuffers = true;
  10374. break;
  10375. case "textureBindingOptimization":
  10376. this.disableTextureBindingOptimization = true;
  10377. break;
  10378. }
  10379. }
  10380. break;
  10381. }
  10382. }
  10383. }
  10384. // GL
  10385. if (!options.disableWebGL2Support) {
  10386. try {
  10387. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10388. if (this._gl) {
  10389. this._webGLVersion = 2.0;
  10390. }
  10391. }
  10392. catch (e) {
  10393. // Do nothing
  10394. }
  10395. }
  10396. if (!this._gl) {
  10397. if (!canvas) {
  10398. throw new Error("The provided canvas is null or undefined.");
  10399. }
  10400. try {
  10401. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10402. }
  10403. catch (e) {
  10404. throw new Error("WebGL not supported");
  10405. }
  10406. }
  10407. if (!this._gl) {
  10408. throw new Error("WebGL not supported");
  10409. }
  10410. this._onCanvasFocus = function () {
  10411. _this.onCanvasFocusObservable.notifyObservers(_this);
  10412. };
  10413. this._onCanvasBlur = function () {
  10414. _this.onCanvasBlurObservable.notifyObservers(_this);
  10415. };
  10416. canvas.addEventListener("focus", this._onCanvasFocus);
  10417. canvas.addEventListener("blur", this._onCanvasBlur);
  10418. this._onBlur = function () {
  10419. if (_this.disablePerformanceMonitorInBackground) {
  10420. _this._performanceMonitor.disable();
  10421. }
  10422. _this._windowIsBackground = true;
  10423. };
  10424. this._onFocus = function () {
  10425. if (_this.disablePerformanceMonitorInBackground) {
  10426. _this._performanceMonitor.enable();
  10427. }
  10428. _this._windowIsBackground = false;
  10429. };
  10430. this._onCanvasPointerOut = function () {
  10431. _this.onCanvasPointerOutObservable.notifyObservers(_this);
  10432. };
  10433. window.addEventListener("blur", this._onBlur);
  10434. window.addEventListener("focus", this._onFocus);
  10435. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10436. // Context lost
  10437. if (!this._doNotHandleContextLost) {
  10438. this._onContextLost = function (evt) {
  10439. evt.preventDefault();
  10440. _this._contextWasLost = true;
  10441. BABYLON.Tools.Warn("WebGL context lost.");
  10442. _this.onContextLostObservable.notifyObservers(_this);
  10443. };
  10444. this._onContextRestored = function (evt) {
  10445. // Adding a timeout to avoid race condition at browser level
  10446. setTimeout(function () {
  10447. // Rebuild gl context
  10448. _this._initGLContext();
  10449. // Rebuild effects
  10450. _this._rebuildEffects();
  10451. // Rebuild textures
  10452. _this._rebuildInternalTextures();
  10453. // Rebuild buffers
  10454. _this._rebuildBuffers();
  10455. // Cache
  10456. _this.wipeCaches(true);
  10457. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10458. _this.onContextRestoredObservable.notifyObservers(_this);
  10459. _this._contextWasLost = false;
  10460. }, 0);
  10461. };
  10462. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10463. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10464. }
  10465. }
  10466. else {
  10467. this._gl = canvasOrContext;
  10468. this._renderingCanvas = this._gl.canvas;
  10469. if (this._gl.renderbufferStorageMultisample) {
  10470. this._webGLVersion = 2.0;
  10471. }
  10472. options.stencil = this._gl.getContextAttributes().stencil;
  10473. }
  10474. // Viewport
  10475. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10476. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10477. this.resize();
  10478. this._isStencilEnable = options.stencil ? true : false;
  10479. this._initGLContext();
  10480. if (canvas) {
  10481. // Fullscreen
  10482. this._onFullscreenChange = function () {
  10483. if (document.fullscreen !== undefined) {
  10484. _this.isFullscreen = document.fullscreen;
  10485. }
  10486. else if (document.mozFullScreen !== undefined) {
  10487. _this.isFullscreen = document.mozFullScreen;
  10488. }
  10489. else if (document.webkitIsFullScreen !== undefined) {
  10490. _this.isFullscreen = document.webkitIsFullScreen;
  10491. }
  10492. else if (document.msIsFullScreen !== undefined) {
  10493. _this.isFullscreen = document.msIsFullScreen;
  10494. }
  10495. // Pointer lock
  10496. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10497. canvas.requestPointerLock = canvas.requestPointerLock ||
  10498. canvas.msRequestPointerLock ||
  10499. canvas.mozRequestPointerLock ||
  10500. canvas.webkitRequestPointerLock;
  10501. if (canvas.requestPointerLock) {
  10502. canvas.requestPointerLock();
  10503. }
  10504. }
  10505. };
  10506. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10507. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10508. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10509. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10510. // Pointer lock
  10511. this._onPointerLockChange = function () {
  10512. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10513. document.webkitPointerLockElement === canvas ||
  10514. document.msPointerLockElement === canvas ||
  10515. document.pointerLockElement === canvas);
  10516. };
  10517. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10518. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10519. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10520. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10521. this._onVRDisplayPointerRestricted = function () {
  10522. if (canvas) {
  10523. canvas.requestPointerLock();
  10524. }
  10525. };
  10526. this._onVRDisplayPointerUnrestricted = function () {
  10527. document.exitPointerLock();
  10528. };
  10529. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10530. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10531. }
  10532. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10533. Engine.audioEngine = new BABYLON.AudioEngine();
  10534. }
  10535. // Prepare buffer pointers
  10536. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10537. this._currentBufferPointers[i] = new BufferPointer();
  10538. }
  10539. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10540. // Load WebVR Devices
  10541. if (options.autoEnableWebVR) {
  10542. this.initWebVR();
  10543. }
  10544. // Detect if we are running on a faulty buggy OS.
  10545. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10546. // Detect if we are running on a faulty buggy desktop OS.
  10547. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10548. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  10549. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10550. }
  10551. Object.defineProperty(Engine, "LastCreatedEngine", {
  10552. get: function () {
  10553. if (Engine.Instances.length === 0) {
  10554. return null;
  10555. }
  10556. return Engine.Instances[Engine.Instances.length - 1];
  10557. },
  10558. enumerable: true,
  10559. configurable: true
  10560. });
  10561. Object.defineProperty(Engine, "LastCreatedScene", {
  10562. get: function () {
  10563. var lastCreatedEngine = Engine.LastCreatedEngine;
  10564. if (!lastCreatedEngine) {
  10565. return null;
  10566. }
  10567. if (lastCreatedEngine.scenes.length === 0) {
  10568. return null;
  10569. }
  10570. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10571. },
  10572. enumerable: true,
  10573. configurable: true
  10574. });
  10575. /**
  10576. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10577. */
  10578. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10579. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10580. var engine = Engine.Instances[engineIndex];
  10581. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10582. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10583. }
  10584. }
  10585. };
  10586. Object.defineProperty(Engine, "NEVER", {
  10587. get: function () {
  10588. return Engine._NEVER;
  10589. },
  10590. enumerable: true,
  10591. configurable: true
  10592. });
  10593. Object.defineProperty(Engine, "ALWAYS", {
  10594. get: function () {
  10595. return Engine._ALWAYS;
  10596. },
  10597. enumerable: true,
  10598. configurable: true
  10599. });
  10600. Object.defineProperty(Engine, "LESS", {
  10601. get: function () {
  10602. return Engine._LESS;
  10603. },
  10604. enumerable: true,
  10605. configurable: true
  10606. });
  10607. Object.defineProperty(Engine, "EQUAL", {
  10608. get: function () {
  10609. return Engine._EQUAL;
  10610. },
  10611. enumerable: true,
  10612. configurable: true
  10613. });
  10614. Object.defineProperty(Engine, "LEQUAL", {
  10615. get: function () {
  10616. return Engine._LEQUAL;
  10617. },
  10618. enumerable: true,
  10619. configurable: true
  10620. });
  10621. Object.defineProperty(Engine, "GREATER", {
  10622. get: function () {
  10623. return Engine._GREATER;
  10624. },
  10625. enumerable: true,
  10626. configurable: true
  10627. });
  10628. Object.defineProperty(Engine, "GEQUAL", {
  10629. get: function () {
  10630. return Engine._GEQUAL;
  10631. },
  10632. enumerable: true,
  10633. configurable: true
  10634. });
  10635. Object.defineProperty(Engine, "NOTEQUAL", {
  10636. get: function () {
  10637. return Engine._NOTEQUAL;
  10638. },
  10639. enumerable: true,
  10640. configurable: true
  10641. });
  10642. Object.defineProperty(Engine, "KEEP", {
  10643. get: function () {
  10644. return Engine._KEEP;
  10645. },
  10646. enumerable: true,
  10647. configurable: true
  10648. });
  10649. Object.defineProperty(Engine, "REPLACE", {
  10650. get: function () {
  10651. return Engine._REPLACE;
  10652. },
  10653. enumerable: true,
  10654. configurable: true
  10655. });
  10656. Object.defineProperty(Engine, "INCR", {
  10657. get: function () {
  10658. return Engine._INCR;
  10659. },
  10660. enumerable: true,
  10661. configurable: true
  10662. });
  10663. Object.defineProperty(Engine, "DECR", {
  10664. get: function () {
  10665. return Engine._DECR;
  10666. },
  10667. enumerable: true,
  10668. configurable: true
  10669. });
  10670. Object.defineProperty(Engine, "INVERT", {
  10671. get: function () {
  10672. return Engine._INVERT;
  10673. },
  10674. enumerable: true,
  10675. configurable: true
  10676. });
  10677. Object.defineProperty(Engine, "INCR_WRAP", {
  10678. get: function () {
  10679. return Engine._INCR_WRAP;
  10680. },
  10681. enumerable: true,
  10682. configurable: true
  10683. });
  10684. Object.defineProperty(Engine, "DECR_WRAP", {
  10685. get: function () {
  10686. return Engine._DECR_WRAP;
  10687. },
  10688. enumerable: true,
  10689. configurable: true
  10690. });
  10691. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  10692. get: function () {
  10693. return Engine._ALPHA_DISABLE;
  10694. },
  10695. enumerable: true,
  10696. configurable: true
  10697. });
  10698. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  10699. get: function () {
  10700. return Engine._ALPHA_ONEONE;
  10701. },
  10702. enumerable: true,
  10703. configurable: true
  10704. });
  10705. Object.defineProperty(Engine, "ALPHA_ADD", {
  10706. get: function () {
  10707. return Engine._ALPHA_ADD;
  10708. },
  10709. enumerable: true,
  10710. configurable: true
  10711. });
  10712. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  10713. get: function () {
  10714. return Engine._ALPHA_COMBINE;
  10715. },
  10716. enumerable: true,
  10717. configurable: true
  10718. });
  10719. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  10720. get: function () {
  10721. return Engine._ALPHA_SUBTRACT;
  10722. },
  10723. enumerable: true,
  10724. configurable: true
  10725. });
  10726. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  10727. get: function () {
  10728. return Engine._ALPHA_MULTIPLY;
  10729. },
  10730. enumerable: true,
  10731. configurable: true
  10732. });
  10733. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  10734. get: function () {
  10735. return Engine._ALPHA_MAXIMIZED;
  10736. },
  10737. enumerable: true,
  10738. configurable: true
  10739. });
  10740. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  10741. get: function () {
  10742. return Engine._ALPHA_PREMULTIPLIED;
  10743. },
  10744. enumerable: true,
  10745. configurable: true
  10746. });
  10747. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  10748. get: function () {
  10749. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  10750. },
  10751. enumerable: true,
  10752. configurable: true
  10753. });
  10754. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  10755. get: function () {
  10756. return Engine._ALPHA_INTERPOLATE;
  10757. },
  10758. enumerable: true,
  10759. configurable: true
  10760. });
  10761. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  10762. get: function () {
  10763. return Engine._ALPHA_SCREENMODE;
  10764. },
  10765. enumerable: true,
  10766. configurable: true
  10767. });
  10768. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  10769. get: function () {
  10770. return Engine._DELAYLOADSTATE_NONE;
  10771. },
  10772. enumerable: true,
  10773. configurable: true
  10774. });
  10775. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  10776. get: function () {
  10777. return Engine._DELAYLOADSTATE_LOADED;
  10778. },
  10779. enumerable: true,
  10780. configurable: true
  10781. });
  10782. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  10783. get: function () {
  10784. return Engine._DELAYLOADSTATE_LOADING;
  10785. },
  10786. enumerable: true,
  10787. configurable: true
  10788. });
  10789. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  10790. get: function () {
  10791. return Engine._DELAYLOADSTATE_NOTLOADED;
  10792. },
  10793. enumerable: true,
  10794. configurable: true
  10795. });
  10796. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  10797. get: function () {
  10798. return Engine._TEXTUREFORMAT_ALPHA;
  10799. },
  10800. enumerable: true,
  10801. configurable: true
  10802. });
  10803. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  10804. get: function () {
  10805. return Engine._TEXTUREFORMAT_LUMINANCE;
  10806. },
  10807. enumerable: true,
  10808. configurable: true
  10809. });
  10810. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  10811. /**
  10812. * R32F
  10813. */
  10814. get: function () {
  10815. return Engine._TEXTUREFORMAT_R32F;
  10816. },
  10817. enumerable: true,
  10818. configurable: true
  10819. });
  10820. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  10821. /**
  10822. * RG32F
  10823. */
  10824. get: function () {
  10825. return Engine._TEXTUREFORMAT_RG32F;
  10826. },
  10827. enumerable: true,
  10828. configurable: true
  10829. });
  10830. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  10831. /**
  10832. * RGB32F
  10833. */
  10834. get: function () {
  10835. return Engine._TEXTUREFORMAT_RGB32F;
  10836. },
  10837. enumerable: true,
  10838. configurable: true
  10839. });
  10840. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  10841. /**
  10842. * RGBA32F
  10843. */
  10844. get: function () {
  10845. return Engine._TEXTUREFORMAT_RGBA32F;
  10846. },
  10847. enumerable: true,
  10848. configurable: true
  10849. });
  10850. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  10851. get: function () {
  10852. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  10853. },
  10854. enumerable: true,
  10855. configurable: true
  10856. });
  10857. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  10858. get: function () {
  10859. return Engine._TEXTUREFORMAT_RGB;
  10860. },
  10861. enumerable: true,
  10862. configurable: true
  10863. });
  10864. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  10865. get: function () {
  10866. return Engine._TEXTUREFORMAT_RGBA;
  10867. },
  10868. enumerable: true,
  10869. configurable: true
  10870. });
  10871. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  10872. get: function () {
  10873. return Engine._TEXTURETYPE_UNSIGNED_INT;
  10874. },
  10875. enumerable: true,
  10876. configurable: true
  10877. });
  10878. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  10879. get: function () {
  10880. return Engine._TEXTURETYPE_FLOAT;
  10881. },
  10882. enumerable: true,
  10883. configurable: true
  10884. });
  10885. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  10886. get: function () {
  10887. return Engine._TEXTURETYPE_HALF_FLOAT;
  10888. },
  10889. enumerable: true,
  10890. configurable: true
  10891. });
  10892. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  10893. get: function () {
  10894. return Engine._SCALEMODE_FLOOR;
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  10900. get: function () {
  10901. return Engine._SCALEMODE_NEAREST;
  10902. },
  10903. enumerable: true,
  10904. configurable: true
  10905. });
  10906. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  10907. get: function () {
  10908. return Engine._SCALEMODE_CEILING;
  10909. },
  10910. enumerable: true,
  10911. configurable: true
  10912. });
  10913. Object.defineProperty(Engine, "Version", {
  10914. get: function () {
  10915. return "3.2.0-alpha8";
  10916. },
  10917. enumerable: true,
  10918. configurable: true
  10919. });
  10920. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  10921. get: function () {
  10922. return this._vrExclusivePointerMode;
  10923. },
  10924. enumerable: true,
  10925. configurable: true
  10926. });
  10927. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  10928. get: function () {
  10929. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  10930. },
  10931. enumerable: true,
  10932. configurable: true
  10933. });
  10934. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  10935. get: function () {
  10936. return this._webGLVersion < 2 || this.forcePOTTextures;
  10937. },
  10938. enumerable: true,
  10939. configurable: true
  10940. });
  10941. Object.defineProperty(Engine.prototype, "badOS", {
  10942. get: function () {
  10943. return this._badOS;
  10944. },
  10945. enumerable: true,
  10946. configurable: true
  10947. });
  10948. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  10949. get: function () {
  10950. return this._badDesktopOS;
  10951. },
  10952. enumerable: true,
  10953. configurable: true
  10954. });
  10955. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  10956. get: function () {
  10957. return this._performanceMonitor;
  10958. },
  10959. enumerable: true,
  10960. configurable: true
  10961. });
  10962. Object.defineProperty(Engine.prototype, "texturesSupported", {
  10963. get: function () {
  10964. return this._texturesSupported;
  10965. },
  10966. enumerable: true,
  10967. configurable: true
  10968. });
  10969. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  10970. get: function () {
  10971. return this._textureFormatInUse;
  10972. },
  10973. enumerable: true,
  10974. configurable: true
  10975. });
  10976. Object.defineProperty(Engine.prototype, "currentViewport", {
  10977. get: function () {
  10978. return this._cachedViewport;
  10979. },
  10980. enumerable: true,
  10981. configurable: true
  10982. });
  10983. Object.defineProperty(Engine.prototype, "emptyTexture", {
  10984. // Empty texture
  10985. get: function () {
  10986. if (!this._emptyTexture) {
  10987. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10988. }
  10989. return this._emptyTexture;
  10990. },
  10991. enumerable: true,
  10992. configurable: true
  10993. });
  10994. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  10995. get: function () {
  10996. if (!this._emptyTexture3D) {
  10997. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10998. }
  10999. return this._emptyTexture3D;
  11000. },
  11001. enumerable: true,
  11002. configurable: true
  11003. });
  11004. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11005. get: function () {
  11006. if (!this._emptyCubeTexture) {
  11007. var faceData = new Uint8Array(4);
  11008. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11009. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11010. }
  11011. return this._emptyCubeTexture;
  11012. },
  11013. enumerable: true,
  11014. configurable: true
  11015. });
  11016. Engine.prototype._rebuildInternalTextures = function () {
  11017. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11018. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11019. var internalTexture = currentState_1[_i];
  11020. internalTexture._rebuild();
  11021. }
  11022. };
  11023. Engine.prototype._rebuildEffects = function () {
  11024. for (var key in this._compiledEffects) {
  11025. var effect = this._compiledEffects[key];
  11026. effect._prepareEffect();
  11027. }
  11028. BABYLON.Effect.ResetCache();
  11029. };
  11030. Engine.prototype._rebuildBuffers = function () {
  11031. // Index / Vertex
  11032. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11033. var scene = _a[_i];
  11034. scene.resetCachedMaterial();
  11035. scene._rebuildGeometries();
  11036. scene._rebuildTextures();
  11037. }
  11038. // Uniforms
  11039. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11040. var uniformBuffer = _c[_b];
  11041. uniformBuffer._rebuild();
  11042. }
  11043. };
  11044. Engine.prototype._initGLContext = function () {
  11045. // Caps
  11046. this._caps = new EngineCapabilities();
  11047. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11048. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11049. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11050. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11051. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11052. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11053. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11054. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11055. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11056. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11057. // Infos
  11058. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11059. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11060. if (rendererInfo != null) {
  11061. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11062. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11063. }
  11064. if (!this._glVendor) {
  11065. this._glVendor = "Unknown vendor";
  11066. }
  11067. if (!this._glRenderer) {
  11068. this._glRenderer = "Unknown renderer";
  11069. }
  11070. // Constants
  11071. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11072. if (this._gl.RGBA16F !== 0x881A) {
  11073. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11074. }
  11075. if (this._gl.RGBA32F !== 0x8814) {
  11076. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11077. }
  11078. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11079. this._gl.DEPTH24_STENCIL8 = 35056;
  11080. }
  11081. // Extensions
  11082. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11083. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11084. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11085. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11086. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11087. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11088. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11089. 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');
  11090. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11091. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11092. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11093. this._caps.highPrecisionShaderSupported = true;
  11094. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11095. if (this._caps.timerQuery) {
  11096. if (this._webGLVersion === 1) {
  11097. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11098. }
  11099. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11100. }
  11101. // Checks if some of the format renders first to allow the use of webgl inspector.
  11102. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11103. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  11104. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  11105. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  11106. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  11107. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  11108. if (this._webGLVersion > 1) {
  11109. this._gl.HALF_FLOAT_OES = 0x140B;
  11110. }
  11111. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11112. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  11113. // Draw buffers
  11114. if (this._webGLVersion > 1) {
  11115. this._caps.drawBuffersExtension = true;
  11116. }
  11117. else {
  11118. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11119. if (drawBuffersExtension !== null) {
  11120. this._caps.drawBuffersExtension = true;
  11121. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11122. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11123. for (var i = 0; i < 16; i++) {
  11124. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11125. }
  11126. }
  11127. else {
  11128. this._caps.drawBuffersExtension = false;
  11129. }
  11130. }
  11131. // Depth Texture
  11132. if (this._webGLVersion > 1) {
  11133. this._caps.depthTextureExtension = true;
  11134. }
  11135. else {
  11136. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11137. if (depthTextureExtension != null) {
  11138. this._caps.depthTextureExtension = true;
  11139. }
  11140. }
  11141. // Vertex array object
  11142. if (this._webGLVersion > 1) {
  11143. this._caps.vertexArrayObject = true;
  11144. }
  11145. else {
  11146. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11147. if (vertexArrayObjectExtension != null) {
  11148. this._caps.vertexArrayObject = true;
  11149. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11150. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11151. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11152. }
  11153. else {
  11154. this._caps.vertexArrayObject = false;
  11155. }
  11156. }
  11157. // Instances count
  11158. if (this._webGLVersion > 1) {
  11159. this._caps.instancedArrays = true;
  11160. }
  11161. else {
  11162. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11163. if (instanceExtension != null) {
  11164. this._caps.instancedArrays = true;
  11165. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11166. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11167. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11168. }
  11169. else {
  11170. this._caps.instancedArrays = false;
  11171. }
  11172. }
  11173. // Intelligently add supported compressed formats in order to check for.
  11174. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11175. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11176. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11177. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11178. if (this._caps.astc)
  11179. this.texturesSupported.push('-astc.ktx');
  11180. if (this._caps.s3tc)
  11181. this.texturesSupported.push('-dxt.ktx');
  11182. if (this._caps.pvrtc)
  11183. this.texturesSupported.push('-pvrtc.ktx');
  11184. if (this._caps.etc2)
  11185. this.texturesSupported.push('-etc2.ktx');
  11186. if (this._caps.etc1)
  11187. this.texturesSupported.push('-etc1.ktx');
  11188. if (this._gl.getShaderPrecisionFormat) {
  11189. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11190. if (highp) {
  11191. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11192. }
  11193. }
  11194. // Depth buffer
  11195. this.setDepthBuffer(true);
  11196. this.setDepthFunctionToLessOrEqual();
  11197. this.setDepthWrite(true);
  11198. // Texture maps
  11199. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11200. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11201. this._nextFreeTextureSlots.push(slot);
  11202. }
  11203. };
  11204. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11205. get: function () {
  11206. return this._webGLVersion;
  11207. },
  11208. enumerable: true,
  11209. configurable: true
  11210. });
  11211. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11212. /**
  11213. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11214. */
  11215. get: function () {
  11216. return this._isStencilEnable;
  11217. },
  11218. enumerable: true,
  11219. configurable: true
  11220. });
  11221. Engine.prototype._prepareWorkingCanvas = function () {
  11222. if (this._workingCanvas) {
  11223. return;
  11224. }
  11225. this._workingCanvas = document.createElement("canvas");
  11226. var context = this._workingCanvas.getContext("2d");
  11227. if (context) {
  11228. this._workingContext = context;
  11229. }
  11230. };
  11231. Engine.prototype.resetTextureCache = function () {
  11232. for (var key in this._boundTexturesCache) {
  11233. var boundTexture = this._boundTexturesCache[key];
  11234. if (boundTexture) {
  11235. this._removeDesignatedSlot(boundTexture);
  11236. }
  11237. this._boundTexturesCache[key] = null;
  11238. }
  11239. if (!this.disableTextureBindingOptimization) {
  11240. this._nextFreeTextureSlots = [];
  11241. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11242. this._nextFreeTextureSlots.push(slot);
  11243. }
  11244. }
  11245. this._currentTextureChannel = -1;
  11246. };
  11247. Engine.prototype.isDeterministicLockStep = function () {
  11248. return this._deterministicLockstep;
  11249. };
  11250. Engine.prototype.getLockstepMaxSteps = function () {
  11251. return this._lockstepMaxSteps;
  11252. };
  11253. Engine.prototype.getGlInfo = function () {
  11254. return {
  11255. vendor: this._glVendor,
  11256. renderer: this._glRenderer,
  11257. version: this._glVersion
  11258. };
  11259. };
  11260. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11261. if (useScreen === void 0) { useScreen = false; }
  11262. var viewport = camera.viewport;
  11263. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11264. };
  11265. Engine.prototype.getRenderWidth = function (useScreen) {
  11266. if (useScreen === void 0) { useScreen = false; }
  11267. if (!useScreen && this._currentRenderTarget) {
  11268. return this._currentRenderTarget.width;
  11269. }
  11270. return this._gl.drawingBufferWidth;
  11271. };
  11272. Engine.prototype.getRenderHeight = function (useScreen) {
  11273. if (useScreen === void 0) { useScreen = false; }
  11274. if (!useScreen && this._currentRenderTarget) {
  11275. return this._currentRenderTarget.height;
  11276. }
  11277. return this._gl.drawingBufferHeight;
  11278. };
  11279. Engine.prototype.getRenderingCanvas = function () {
  11280. return this._renderingCanvas;
  11281. };
  11282. Engine.prototype.getRenderingCanvasClientRect = function () {
  11283. if (!this._renderingCanvas) {
  11284. return null;
  11285. }
  11286. return this._renderingCanvas.getBoundingClientRect();
  11287. };
  11288. Engine.prototype.setHardwareScalingLevel = function (level) {
  11289. this._hardwareScalingLevel = level;
  11290. this.resize();
  11291. };
  11292. Engine.prototype.getHardwareScalingLevel = function () {
  11293. return this._hardwareScalingLevel;
  11294. };
  11295. Engine.prototype.getLoadedTexturesCache = function () {
  11296. return this._internalTexturesCache;
  11297. };
  11298. Engine.prototype.getCaps = function () {
  11299. return this._caps;
  11300. };
  11301. Object.defineProperty(Engine.prototype, "drawCalls", {
  11302. /** The number of draw calls submitted last frame */
  11303. get: function () {
  11304. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11305. return 0;
  11306. },
  11307. enumerable: true,
  11308. configurable: true
  11309. });
  11310. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11311. get: function () {
  11312. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11313. return null;
  11314. },
  11315. enumerable: true,
  11316. configurable: true
  11317. });
  11318. Engine.prototype.getDepthFunction = function () {
  11319. return this._depthCullingState.depthFunc;
  11320. };
  11321. Engine.prototype.setDepthFunction = function (depthFunc) {
  11322. this._depthCullingState.depthFunc = depthFunc;
  11323. };
  11324. Engine.prototype.setDepthFunctionToGreater = function () {
  11325. this._depthCullingState.depthFunc = this._gl.GREATER;
  11326. };
  11327. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11328. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11329. };
  11330. Engine.prototype.setDepthFunctionToLess = function () {
  11331. this._depthCullingState.depthFunc = this._gl.LESS;
  11332. };
  11333. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11334. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11335. };
  11336. Engine.prototype.getStencilBuffer = function () {
  11337. return this._stencilState.stencilTest;
  11338. };
  11339. Engine.prototype.setStencilBuffer = function (enable) {
  11340. this._stencilState.stencilTest = enable;
  11341. };
  11342. Engine.prototype.getStencilMask = function () {
  11343. return this._stencilState.stencilMask;
  11344. };
  11345. Engine.prototype.setStencilMask = function (mask) {
  11346. this._stencilState.stencilMask = mask;
  11347. };
  11348. Engine.prototype.getStencilFunction = function () {
  11349. return this._stencilState.stencilFunc;
  11350. };
  11351. Engine.prototype.getStencilFunctionReference = function () {
  11352. return this._stencilState.stencilFuncRef;
  11353. };
  11354. Engine.prototype.getStencilFunctionMask = function () {
  11355. return this._stencilState.stencilFuncMask;
  11356. };
  11357. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11358. this._stencilState.stencilFunc = stencilFunc;
  11359. };
  11360. Engine.prototype.setStencilFunctionReference = function (reference) {
  11361. this._stencilState.stencilFuncRef = reference;
  11362. };
  11363. Engine.prototype.setStencilFunctionMask = function (mask) {
  11364. this._stencilState.stencilFuncMask = mask;
  11365. };
  11366. Engine.prototype.getStencilOperationFail = function () {
  11367. return this._stencilState.stencilOpStencilFail;
  11368. };
  11369. Engine.prototype.getStencilOperationDepthFail = function () {
  11370. return this._stencilState.stencilOpDepthFail;
  11371. };
  11372. Engine.prototype.getStencilOperationPass = function () {
  11373. return this._stencilState.stencilOpStencilDepthPass;
  11374. };
  11375. Engine.prototype.setStencilOperationFail = function (operation) {
  11376. this._stencilState.stencilOpStencilFail = operation;
  11377. };
  11378. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11379. this._stencilState.stencilOpDepthFail = operation;
  11380. };
  11381. Engine.prototype.setStencilOperationPass = function (operation) {
  11382. this._stencilState.stencilOpStencilDepthPass = operation;
  11383. };
  11384. Engine.prototype.setDitheringState = function (value) {
  11385. if (value) {
  11386. this._gl.enable(this._gl.DITHER);
  11387. }
  11388. else {
  11389. this._gl.disable(this._gl.DITHER);
  11390. }
  11391. };
  11392. Engine.prototype.setRasterizerState = function (value) {
  11393. if (value) {
  11394. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11395. }
  11396. else {
  11397. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11398. }
  11399. };
  11400. /**
  11401. * stop executing a render loop function and remove it from the execution array
  11402. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11403. */
  11404. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11405. if (!renderFunction) {
  11406. this._activeRenderLoops = [];
  11407. return;
  11408. }
  11409. var index = this._activeRenderLoops.indexOf(renderFunction);
  11410. if (index >= 0) {
  11411. this._activeRenderLoops.splice(index, 1);
  11412. }
  11413. };
  11414. Engine.prototype._renderLoop = function () {
  11415. if (!this._contextWasLost) {
  11416. var shouldRender = true;
  11417. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11418. shouldRender = false;
  11419. }
  11420. if (shouldRender) {
  11421. // Start new frame
  11422. this.beginFrame();
  11423. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11424. var renderFunction = this._activeRenderLoops[index];
  11425. renderFunction();
  11426. }
  11427. // Present
  11428. this.endFrame();
  11429. }
  11430. }
  11431. if (this._activeRenderLoops.length > 0) {
  11432. // Register new frame
  11433. var requester = null;
  11434. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11435. requester = this._vrDisplay;
  11436. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11437. }
  11438. else {
  11439. this._renderingQueueLaunched = false;
  11440. }
  11441. };
  11442. /**
  11443. * Register and execute a render loop. The engine can have more than one render function.
  11444. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11445. * @example
  11446. * engine.runRenderLoop(function () {
  11447. * scene.render()
  11448. * })
  11449. */
  11450. Engine.prototype.runRenderLoop = function (renderFunction) {
  11451. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11452. return;
  11453. }
  11454. this._activeRenderLoops.push(renderFunction);
  11455. if (!this._renderingQueueLaunched) {
  11456. this._renderingQueueLaunched = true;
  11457. this._bindedRenderFunction = this._renderLoop.bind(this);
  11458. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11459. }
  11460. };
  11461. /**
  11462. * Toggle full screen mode.
  11463. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11464. * @param {any} options - an options object to be sent to the requestFullscreen function
  11465. */
  11466. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11467. if (this.isFullscreen) {
  11468. BABYLON.Tools.ExitFullscreen();
  11469. }
  11470. else {
  11471. this._pointerLockRequested = requestPointerLock;
  11472. if (this._renderingCanvas) {
  11473. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11474. }
  11475. }
  11476. };
  11477. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11478. if (stencil === void 0) { stencil = false; }
  11479. this.applyStates();
  11480. var mode = 0;
  11481. if (backBuffer && color) {
  11482. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11483. mode |= this._gl.COLOR_BUFFER_BIT;
  11484. }
  11485. if (depth) {
  11486. this._gl.clearDepth(1.0);
  11487. mode |= this._gl.DEPTH_BUFFER_BIT;
  11488. }
  11489. if (stencil) {
  11490. this._gl.clearStencil(0);
  11491. mode |= this._gl.STENCIL_BUFFER_BIT;
  11492. }
  11493. this._gl.clear(mode);
  11494. };
  11495. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11496. var gl = this._gl;
  11497. // Save state
  11498. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11499. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11500. // Change state
  11501. gl.enable(gl.SCISSOR_TEST);
  11502. gl.scissor(x, y, width, height);
  11503. // Clear
  11504. this.clear(clearColor, true, true, true);
  11505. // Restore state
  11506. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11507. if (curScissor === true) {
  11508. gl.enable(gl.SCISSOR_TEST);
  11509. }
  11510. else {
  11511. gl.disable(gl.SCISSOR_TEST);
  11512. }
  11513. };
  11514. /**
  11515. * Set the WebGL's viewport
  11516. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11517. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11518. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11519. */
  11520. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11521. var width = requiredWidth || this.getRenderWidth();
  11522. var height = requiredHeight || this.getRenderHeight();
  11523. var x = viewport.x || 0;
  11524. var y = viewport.y || 0;
  11525. this._cachedViewport = viewport;
  11526. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11527. };
  11528. /**
  11529. * Directly set the WebGL Viewport
  11530. * The x, y, width & height are directly passed to the WebGL call
  11531. * @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.
  11532. */
  11533. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11534. var currentViewport = this._cachedViewport;
  11535. this._cachedViewport = null;
  11536. this._gl.viewport(x, y, width, height);
  11537. return currentViewport;
  11538. };
  11539. Engine.prototype.beginFrame = function () {
  11540. this.onBeginFrameObservable.notifyObservers(this);
  11541. this._measureFps();
  11542. };
  11543. Engine.prototype.endFrame = function () {
  11544. //force a flush in case we are using a bad OS.
  11545. if (this._badOS) {
  11546. this.flushFramebuffer();
  11547. }
  11548. //submit frame to the vr device, if enabled
  11549. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11550. // TODO: We should only submit the frame if we read frameData successfully.
  11551. this._vrDisplay.submitFrame();
  11552. }
  11553. this.onEndFrameObservable.notifyObservers(this);
  11554. };
  11555. /**
  11556. * resize the view according to the canvas' size.
  11557. * @example
  11558. * window.addEventListener("resize", function () {
  11559. * engine.resize();
  11560. * });
  11561. */
  11562. Engine.prototype.resize = function () {
  11563. // We're not resizing the size of the canvas while in VR mode & presenting
  11564. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11565. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11566. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11567. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11568. }
  11569. };
  11570. /**
  11571. * force a specific size of the canvas
  11572. * @param {number} width - the new canvas' width
  11573. * @param {number} height - the new canvas' height
  11574. */
  11575. Engine.prototype.setSize = function (width, height) {
  11576. if (!this._renderingCanvas) {
  11577. return;
  11578. }
  11579. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11580. return;
  11581. }
  11582. this._renderingCanvas.width = width;
  11583. this._renderingCanvas.height = height;
  11584. for (var index = 0; index < this.scenes.length; index++) {
  11585. var scene = this.scenes[index];
  11586. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11587. var cam = scene.cameras[camIndex];
  11588. cam._currentRenderId = 0;
  11589. }
  11590. }
  11591. if (this.onResizeObservable.hasObservers) {
  11592. this.onResizeObservable.notifyObservers(this);
  11593. }
  11594. };
  11595. // WebVR functions
  11596. Engine.prototype.isVRDevicePresent = function () {
  11597. return !!this._vrDisplay;
  11598. };
  11599. Engine.prototype.getVRDevice = function () {
  11600. return this._vrDisplay;
  11601. };
  11602. /**
  11603. * Initializes a webVR display and starts listening to display change events.
  11604. * The onVRDisplayChangedObservable will be notified upon these changes.
  11605. * @returns The onVRDisplayChangedObservable.
  11606. */
  11607. Engine.prototype.initWebVR = function () {
  11608. this.initWebVRAsync();
  11609. return this.onVRDisplayChangedObservable;
  11610. };
  11611. /**
  11612. * Initializes a webVR display and starts listening to display change events.
  11613. * The onVRDisplayChangedObservable will be notified upon these changes.
  11614. * @returns A promise containing a VRDisplay and if vr is supported.
  11615. */
  11616. Engine.prototype.initWebVRAsync = function () {
  11617. var _this = this;
  11618. var notifyObservers = function () {
  11619. var eventArgs = {
  11620. vrDisplay: _this._vrDisplay,
  11621. vrSupported: _this._vrSupported
  11622. };
  11623. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11624. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11625. };
  11626. if (!this._onVrDisplayConnect) {
  11627. this._onVrDisplayConnect = function (event) {
  11628. _this._vrDisplay = event.display;
  11629. notifyObservers();
  11630. };
  11631. this._onVrDisplayDisconnect = function () {
  11632. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11633. _this._vrDisplay = undefined;
  11634. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11635. notifyObservers();
  11636. };
  11637. this._onVrDisplayPresentChange = function () {
  11638. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11639. };
  11640. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11641. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11642. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11643. }
  11644. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11645. this._webVRInitPromise.then(notifyObservers);
  11646. return this._webVRInitPromise;
  11647. };
  11648. Engine.prototype.enableVR = function () {
  11649. var _this = this;
  11650. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  11651. var onResolved = function () {
  11652. _this.onVRRequestPresentComplete.notifyObservers(true);
  11653. _this._onVRFullScreenTriggered();
  11654. };
  11655. var onRejected = function () {
  11656. _this.onVRRequestPresentComplete.notifyObservers(false);
  11657. };
  11658. this.onVRRequestPresentStart.notifyObservers(this);
  11659. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  11660. }
  11661. };
  11662. Engine.prototype.disableVR = function () {
  11663. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11664. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  11665. }
  11666. };
  11667. Engine.prototype._getVRDisplaysAsync = function () {
  11668. var _this = this;
  11669. return new Promise(function (res, rej) {
  11670. if (navigator.getVRDisplays) {
  11671. navigator.getVRDisplays().then(function (devices) {
  11672. _this._vrSupported = true;
  11673. // note that devices may actually be an empty array. This is fine;
  11674. // we expect this._vrDisplay to be undefined in this case.
  11675. _this._vrDisplay = devices[0];
  11676. res({
  11677. vrDisplay: _this._vrDisplay,
  11678. vrSupported: _this._vrSupported
  11679. });
  11680. });
  11681. }
  11682. else {
  11683. _this._vrDisplay = undefined;
  11684. _this._vrSupported = false;
  11685. res({
  11686. vrDisplay: _this._vrDisplay,
  11687. vrSupported: _this._vrSupported
  11688. });
  11689. }
  11690. });
  11691. };
  11692. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  11693. if (this._currentRenderTarget) {
  11694. this.unBindFramebuffer(this._currentRenderTarget);
  11695. }
  11696. this._currentRenderTarget = texture;
  11697. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  11698. var gl = this._gl;
  11699. if (texture.isCube) {
  11700. if (faceIndex === undefined) {
  11701. faceIndex = 0;
  11702. }
  11703. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  11704. }
  11705. if (this._cachedViewport && !forceFullscreenViewport) {
  11706. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  11707. }
  11708. else {
  11709. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  11710. }
  11711. this.wipeCaches();
  11712. };
  11713. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  11714. if (this._currentFramebuffer !== framebuffer) {
  11715. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  11716. this._currentFramebuffer = framebuffer;
  11717. }
  11718. };
  11719. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  11720. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11721. this._currentRenderTarget = null;
  11722. // If MSAA, we need to bitblt back to main texture
  11723. var gl = this._gl;
  11724. if (texture._MSAAFramebuffer) {
  11725. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  11726. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  11727. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11728. }
  11729. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11730. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  11731. gl.generateMipmap(gl.TEXTURE_2D);
  11732. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11733. }
  11734. if (onBeforeUnbind) {
  11735. if (texture._MSAAFramebuffer) {
  11736. // Bind the correct framebuffer
  11737. this.bindUnboundFramebuffer(texture._framebuffer);
  11738. }
  11739. onBeforeUnbind();
  11740. }
  11741. this.bindUnboundFramebuffer(null);
  11742. };
  11743. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  11744. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  11745. this._currentRenderTarget = null;
  11746. // If MSAA, we need to bitblt back to main texture
  11747. var gl = this._gl;
  11748. if (textures[0]._MSAAFramebuffer) {
  11749. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  11750. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  11751. var attachments = textures[0]._attachments;
  11752. if (!attachments) {
  11753. attachments = new Array(textures.length);
  11754. textures[0]._attachments = attachments;
  11755. }
  11756. for (var i = 0; i < textures.length; i++) {
  11757. var texture = textures[i];
  11758. for (var j = 0; j < attachments.length; j++) {
  11759. attachments[j] = gl.NONE;
  11760. }
  11761. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11762. gl.readBuffer(attachments[i]);
  11763. gl.drawBuffers(attachments);
  11764. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  11765. }
  11766. for (var i = 0; i < attachments.length; i++) {
  11767. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  11768. }
  11769. gl.drawBuffers(attachments);
  11770. }
  11771. for (var i = 0; i < textures.length; i++) {
  11772. var texture = textures[i];
  11773. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  11774. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  11775. gl.generateMipmap(gl.TEXTURE_2D);
  11776. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  11777. }
  11778. }
  11779. if (onBeforeUnbind) {
  11780. if (textures[0]._MSAAFramebuffer) {
  11781. // Bind the correct framebuffer
  11782. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  11783. }
  11784. onBeforeUnbind();
  11785. }
  11786. this.bindUnboundFramebuffer(null);
  11787. };
  11788. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  11789. if (texture.generateMipMaps) {
  11790. var gl = this._gl;
  11791. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  11792. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  11793. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  11794. }
  11795. };
  11796. Engine.prototype.flushFramebuffer = function () {
  11797. this._gl.flush();
  11798. };
  11799. Engine.prototype.restoreDefaultFramebuffer = function () {
  11800. if (this._currentRenderTarget) {
  11801. this.unBindFramebuffer(this._currentRenderTarget);
  11802. }
  11803. else {
  11804. this.bindUnboundFramebuffer(null);
  11805. }
  11806. if (this._cachedViewport) {
  11807. this.setViewport(this._cachedViewport);
  11808. }
  11809. this.wipeCaches();
  11810. };
  11811. // UBOs
  11812. Engine.prototype.createUniformBuffer = function (elements) {
  11813. var ubo = this._gl.createBuffer();
  11814. if (!ubo) {
  11815. throw new Error("Unable to create uniform buffer");
  11816. }
  11817. this.bindUniformBuffer(ubo);
  11818. if (elements instanceof Float32Array) {
  11819. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  11820. }
  11821. else {
  11822. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  11823. }
  11824. this.bindUniformBuffer(null);
  11825. ubo.references = 1;
  11826. return ubo;
  11827. };
  11828. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  11829. var ubo = this._gl.createBuffer();
  11830. if (!ubo) {
  11831. throw new Error("Unable to create dynamic uniform buffer");
  11832. }
  11833. this.bindUniformBuffer(ubo);
  11834. if (elements instanceof Float32Array) {
  11835. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  11836. }
  11837. else {
  11838. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  11839. }
  11840. this.bindUniformBuffer(null);
  11841. ubo.references = 1;
  11842. return ubo;
  11843. };
  11844. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  11845. this.bindUniformBuffer(uniformBuffer);
  11846. if (offset === undefined) {
  11847. offset = 0;
  11848. }
  11849. if (count === undefined) {
  11850. if (elements instanceof Float32Array) {
  11851. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  11852. }
  11853. else {
  11854. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  11855. }
  11856. }
  11857. else {
  11858. if (elements instanceof Float32Array) {
  11859. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  11860. }
  11861. else {
  11862. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  11863. }
  11864. }
  11865. this.bindUniformBuffer(null);
  11866. };
  11867. // VBOs
  11868. Engine.prototype._resetVertexBufferBinding = function () {
  11869. this.bindArrayBuffer(null);
  11870. this._cachedVertexBuffers = null;
  11871. };
  11872. Engine.prototype.createVertexBuffer = function (vertices) {
  11873. var vbo = this._gl.createBuffer();
  11874. if (!vbo) {
  11875. throw new Error("Unable to create vertex buffer");
  11876. }
  11877. this.bindArrayBuffer(vbo);
  11878. if (vertices instanceof Float32Array) {
  11879. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  11880. }
  11881. else {
  11882. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  11883. }
  11884. this._resetVertexBufferBinding();
  11885. vbo.references = 1;
  11886. return vbo;
  11887. };
  11888. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  11889. var vbo = this._gl.createBuffer();
  11890. if (!vbo) {
  11891. throw new Error("Unable to create dynamic vertex buffer");
  11892. }
  11893. this.bindArrayBuffer(vbo);
  11894. if (vertices instanceof Float32Array) {
  11895. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  11896. }
  11897. else {
  11898. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  11899. }
  11900. this._resetVertexBufferBinding();
  11901. vbo.references = 1;
  11902. return vbo;
  11903. };
  11904. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  11905. if (offset === void 0) { offset = 0; }
  11906. // Force cache update
  11907. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  11908. this.bindIndexBuffer(indexBuffer);
  11909. var arrayBuffer;
  11910. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  11911. arrayBuffer = indices;
  11912. }
  11913. else {
  11914. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11915. }
  11916. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  11917. this._resetIndexBufferBinding();
  11918. };
  11919. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  11920. this.bindArrayBuffer(vertexBuffer);
  11921. if (offset === undefined) {
  11922. offset = 0;
  11923. }
  11924. if (count === undefined) {
  11925. if (vertices instanceof Float32Array) {
  11926. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  11927. }
  11928. else {
  11929. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  11930. }
  11931. }
  11932. else {
  11933. if (vertices instanceof Float32Array) {
  11934. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  11935. }
  11936. else {
  11937. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  11938. }
  11939. }
  11940. this._resetVertexBufferBinding();
  11941. };
  11942. Engine.prototype._resetIndexBufferBinding = function () {
  11943. this.bindIndexBuffer(null);
  11944. this._cachedIndexBuffer = null;
  11945. };
  11946. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  11947. var vbo = this._gl.createBuffer();
  11948. if (!vbo) {
  11949. throw new Error("Unable to create index buffer");
  11950. }
  11951. this.bindIndexBuffer(vbo);
  11952. // Check for 32 bits indices
  11953. var arrayBuffer;
  11954. var need32Bits = false;
  11955. if (indices instanceof Uint16Array) {
  11956. arrayBuffer = indices;
  11957. }
  11958. else {
  11959. //check 32 bit support
  11960. if (this._caps.uintIndices) {
  11961. if (indices instanceof Uint32Array) {
  11962. arrayBuffer = indices;
  11963. need32Bits = true;
  11964. }
  11965. else {
  11966. //number[] or Int32Array, check if 32 bit is necessary
  11967. for (var index = 0; index < indices.length; index++) {
  11968. if (indices[index] > 65535) {
  11969. need32Bits = true;
  11970. break;
  11971. }
  11972. }
  11973. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  11974. }
  11975. }
  11976. else {
  11977. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  11978. arrayBuffer = new Uint16Array(indices);
  11979. }
  11980. }
  11981. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  11982. this._resetIndexBufferBinding();
  11983. vbo.references = 1;
  11984. vbo.is32Bits = need32Bits;
  11985. return vbo;
  11986. };
  11987. Engine.prototype.bindArrayBuffer = function (buffer) {
  11988. if (!this._vaoRecordInProgress) {
  11989. this._unbindVertexArrayObject();
  11990. }
  11991. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  11992. };
  11993. Engine.prototype.bindUniformBuffer = function (buffer) {
  11994. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  11995. };
  11996. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  11997. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  11998. };
  11999. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12000. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12001. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12002. };
  12003. ;
  12004. Engine.prototype.bindIndexBuffer = function (buffer) {
  12005. if (!this._vaoRecordInProgress) {
  12006. this._unbindVertexArrayObject();
  12007. }
  12008. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12009. };
  12010. Engine.prototype.bindBuffer = function (buffer, target) {
  12011. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12012. this._gl.bindBuffer(target, buffer);
  12013. this._currentBoundBuffer[target] = buffer;
  12014. }
  12015. };
  12016. Engine.prototype.updateArrayBuffer = function (data) {
  12017. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12018. };
  12019. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12020. var pointer = this._currentBufferPointers[indx];
  12021. var changed = false;
  12022. if (!pointer.active) {
  12023. changed = true;
  12024. pointer.active = true;
  12025. pointer.index = indx;
  12026. pointer.size = size;
  12027. pointer.type = type;
  12028. pointer.normalized = normalized;
  12029. pointer.stride = stride;
  12030. pointer.offset = offset;
  12031. pointer.buffer = buffer;
  12032. }
  12033. else {
  12034. if (pointer.buffer !== buffer) {
  12035. pointer.buffer = buffer;
  12036. changed = true;
  12037. }
  12038. if (pointer.size !== size) {
  12039. pointer.size = size;
  12040. changed = true;
  12041. }
  12042. if (pointer.type !== type) {
  12043. pointer.type = type;
  12044. changed = true;
  12045. }
  12046. if (pointer.normalized !== normalized) {
  12047. pointer.normalized = normalized;
  12048. changed = true;
  12049. }
  12050. if (pointer.stride !== stride) {
  12051. pointer.stride = stride;
  12052. changed = true;
  12053. }
  12054. if (pointer.offset !== offset) {
  12055. pointer.offset = offset;
  12056. changed = true;
  12057. }
  12058. }
  12059. if (changed || this._vaoRecordInProgress) {
  12060. this.bindArrayBuffer(buffer);
  12061. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12062. }
  12063. };
  12064. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12065. if (indexBuffer == null) {
  12066. return;
  12067. }
  12068. if (this._cachedIndexBuffer !== indexBuffer) {
  12069. this._cachedIndexBuffer = indexBuffer;
  12070. this.bindIndexBuffer(indexBuffer);
  12071. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12072. }
  12073. };
  12074. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12075. var attributes = effect.getAttributesNames();
  12076. if (!this._vaoRecordInProgress) {
  12077. this._unbindVertexArrayObject();
  12078. }
  12079. this.unbindAllAttributes();
  12080. for (var index = 0; index < attributes.length; index++) {
  12081. var order = effect.getAttributeLocation(index);
  12082. if (order >= 0) {
  12083. var vertexBuffer = vertexBuffers[attributes[index]];
  12084. if (!vertexBuffer) {
  12085. continue;
  12086. }
  12087. this._gl.enableVertexAttribArray(order);
  12088. if (!this._vaoRecordInProgress) {
  12089. this._vertexAttribArraysEnabled[order] = true;
  12090. }
  12091. var buffer = vertexBuffer.getBuffer();
  12092. if (buffer) {
  12093. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12094. if (vertexBuffer.getIsInstanced()) {
  12095. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12096. if (!this._vaoRecordInProgress) {
  12097. this._currentInstanceLocations.push(order);
  12098. this._currentInstanceBuffers.push(buffer);
  12099. }
  12100. }
  12101. }
  12102. }
  12103. }
  12104. };
  12105. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12106. var vao = this._gl.createVertexArray();
  12107. this._vaoRecordInProgress = true;
  12108. this._gl.bindVertexArray(vao);
  12109. this._mustWipeVertexAttributes = true;
  12110. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12111. this.bindIndexBuffer(indexBuffer);
  12112. this._vaoRecordInProgress = false;
  12113. this._gl.bindVertexArray(null);
  12114. return vao;
  12115. };
  12116. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12117. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12118. this._cachedVertexArrayObject = vertexArrayObject;
  12119. this._gl.bindVertexArray(vertexArrayObject);
  12120. this._cachedVertexBuffers = null;
  12121. this._cachedIndexBuffer = null;
  12122. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12123. this._mustWipeVertexAttributes = true;
  12124. }
  12125. };
  12126. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12127. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12128. this._cachedVertexBuffers = vertexBuffer;
  12129. this._cachedEffectForVertexBuffers = effect;
  12130. var attributesCount = effect.getAttributesCount();
  12131. this._unbindVertexArrayObject();
  12132. this.unbindAllAttributes();
  12133. var offset = 0;
  12134. for (var index = 0; index < attributesCount; index++) {
  12135. if (index < vertexDeclaration.length) {
  12136. var order = effect.getAttributeLocation(index);
  12137. if (order >= 0) {
  12138. this._gl.enableVertexAttribArray(order);
  12139. this._vertexAttribArraysEnabled[order] = true;
  12140. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12141. }
  12142. offset += vertexDeclaration[index] * 4;
  12143. }
  12144. }
  12145. }
  12146. this._bindIndexBufferWithCache(indexBuffer);
  12147. };
  12148. Engine.prototype._unbindVertexArrayObject = function () {
  12149. if (!this._cachedVertexArrayObject) {
  12150. return;
  12151. }
  12152. this._cachedVertexArrayObject = null;
  12153. this._gl.bindVertexArray(null);
  12154. };
  12155. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12156. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12157. this._cachedVertexBuffers = vertexBuffers;
  12158. this._cachedEffectForVertexBuffers = effect;
  12159. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12160. }
  12161. this._bindIndexBufferWithCache(indexBuffer);
  12162. };
  12163. Engine.prototype.unbindInstanceAttributes = function () {
  12164. var boundBuffer;
  12165. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12166. var instancesBuffer = this._currentInstanceBuffers[i];
  12167. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12168. boundBuffer = instancesBuffer;
  12169. this.bindArrayBuffer(instancesBuffer);
  12170. }
  12171. var offsetLocation = this._currentInstanceLocations[i];
  12172. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12173. }
  12174. this._currentInstanceBuffers.length = 0;
  12175. this._currentInstanceLocations.length = 0;
  12176. };
  12177. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12178. this._gl.deleteVertexArray(vao);
  12179. };
  12180. Engine.prototype._releaseBuffer = function (buffer) {
  12181. buffer.references--;
  12182. if (buffer.references === 0) {
  12183. this._gl.deleteBuffer(buffer);
  12184. return true;
  12185. }
  12186. return false;
  12187. };
  12188. Engine.prototype.createInstancesBuffer = function (capacity) {
  12189. var buffer = this._gl.createBuffer();
  12190. if (!buffer) {
  12191. throw new Error("Unable to create instance buffer");
  12192. }
  12193. buffer.capacity = capacity;
  12194. this.bindArrayBuffer(buffer);
  12195. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12196. return buffer;
  12197. };
  12198. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12199. this._gl.deleteBuffer(buffer);
  12200. };
  12201. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12202. this.bindArrayBuffer(instancesBuffer);
  12203. if (data) {
  12204. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12205. }
  12206. if (offsetLocations[0].index !== undefined) {
  12207. var stride = 0;
  12208. for (var i = 0; i < offsetLocations.length; i++) {
  12209. var ai = offsetLocations[i];
  12210. stride += ai.attributeSize * 4;
  12211. }
  12212. for (var i = 0; i < offsetLocations.length; i++) {
  12213. var ai = offsetLocations[i];
  12214. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12215. this._gl.enableVertexAttribArray(ai.index);
  12216. this._vertexAttribArraysEnabled[ai.index] = true;
  12217. }
  12218. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12219. this._gl.vertexAttribDivisor(ai.index, 1);
  12220. this._currentInstanceLocations.push(ai.index);
  12221. this._currentInstanceBuffers.push(instancesBuffer);
  12222. }
  12223. }
  12224. else {
  12225. for (var index = 0; index < 4; index++) {
  12226. var offsetLocation = offsetLocations[index];
  12227. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12228. this._gl.enableVertexAttribArray(offsetLocation);
  12229. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12230. }
  12231. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12232. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12233. this._currentInstanceLocations.push(offsetLocation);
  12234. this._currentInstanceBuffers.push(instancesBuffer);
  12235. }
  12236. }
  12237. };
  12238. Engine.prototype.applyStates = function () {
  12239. this._depthCullingState.apply(this._gl);
  12240. this._stencilState.apply(this._gl);
  12241. this._alphaState.apply(this._gl);
  12242. };
  12243. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12244. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12245. };
  12246. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12247. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12248. };
  12249. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12250. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12251. };
  12252. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12253. // Apply states
  12254. this.applyStates();
  12255. this._drawCalls.addCount(1, false);
  12256. // Render
  12257. var drawMode = this.DrawMode(fillMode);
  12258. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12259. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12260. if (instancesCount) {
  12261. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12262. }
  12263. else {
  12264. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12265. }
  12266. };
  12267. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12268. // Apply states
  12269. this.applyStates();
  12270. this._drawCalls.addCount(1, false);
  12271. var drawMode = this.DrawMode(fillMode);
  12272. if (instancesCount) {
  12273. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12274. }
  12275. else {
  12276. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12277. }
  12278. };
  12279. Engine.prototype.DrawMode = function (fillMode) {
  12280. switch (fillMode) {
  12281. // Triangle views
  12282. case BABYLON.Material.TriangleFillMode:
  12283. return this._gl.TRIANGLES;
  12284. case BABYLON.Material.PointFillMode:
  12285. return this._gl.POINTS;
  12286. case BABYLON.Material.WireFrameFillMode:
  12287. return this._gl.LINES;
  12288. // Draw modes
  12289. case BABYLON.Material.PointListDrawMode:
  12290. return this._gl.POINTS;
  12291. case BABYLON.Material.LineListDrawMode:
  12292. return this._gl.LINES;
  12293. case BABYLON.Material.LineLoopDrawMode:
  12294. return this._gl.LINE_LOOP;
  12295. case BABYLON.Material.LineStripDrawMode:
  12296. return this._gl.LINE_STRIP;
  12297. case BABYLON.Material.TriangleStripDrawMode:
  12298. return this._gl.TRIANGLE_STRIP;
  12299. case BABYLON.Material.TriangleFanDrawMode:
  12300. return this._gl.TRIANGLE_FAN;
  12301. default:
  12302. return this._gl.TRIANGLES;
  12303. }
  12304. };
  12305. // Shaders
  12306. Engine.prototype._releaseEffect = function (effect) {
  12307. if (this._compiledEffects[effect._key]) {
  12308. delete this._compiledEffects[effect._key];
  12309. this._deleteProgram(effect.getProgram());
  12310. }
  12311. };
  12312. Engine.prototype._deleteProgram = function (program) {
  12313. if (program) {
  12314. program.__SPECTOR_rebuildProgram = null;
  12315. if (program.transformFeedback) {
  12316. this.deleteTransformFeedback(program.transformFeedback);
  12317. program.transformFeedback = null;
  12318. }
  12319. this._gl.deleteProgram(program);
  12320. }
  12321. };
  12322. /**
  12323. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12324. * @param samplers An array of string used to represent textures
  12325. */
  12326. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12327. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12328. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12329. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12330. if (this._compiledEffects[name]) {
  12331. var compiledEffect = this._compiledEffects[name];
  12332. if (onCompiled && compiledEffect.isReady()) {
  12333. onCompiled(compiledEffect);
  12334. }
  12335. return compiledEffect;
  12336. }
  12337. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12338. effect._key = name;
  12339. this._compiledEffects[name] = effect;
  12340. return effect;
  12341. };
  12342. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12343. if (uniformsNames === void 0) { uniformsNames = []; }
  12344. if (samplers === void 0) { samplers = []; }
  12345. if (defines === void 0) { defines = ""; }
  12346. return this.createEffect({
  12347. vertex: "particles",
  12348. fragmentElement: fragmentName
  12349. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12350. };
  12351. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12352. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12353. context = context || this._gl;
  12354. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12355. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12356. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12357. };
  12358. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12359. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12360. context = context || this._gl;
  12361. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12362. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  12363. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12364. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12365. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12366. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12367. return program;
  12368. };
  12369. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12370. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12371. var shaderProgram = context.createProgram();
  12372. if (!shaderProgram) {
  12373. throw new Error("Unable to create program");
  12374. }
  12375. context.attachShader(shaderProgram, vertexShader);
  12376. context.attachShader(shaderProgram, fragmentShader);
  12377. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12378. var transformFeedback = this.createTransformFeedback();
  12379. this.bindTransformFeedback(transformFeedback);
  12380. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12381. shaderProgram.transformFeedback = transformFeedback;
  12382. }
  12383. context.linkProgram(shaderProgram);
  12384. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12385. this.bindTransformFeedback(null);
  12386. }
  12387. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12388. if (!linked) {
  12389. context.validateProgram(shaderProgram);
  12390. var error = context.getProgramInfoLog(shaderProgram);
  12391. if (error) {
  12392. throw new Error(error);
  12393. }
  12394. }
  12395. context.deleteShader(vertexShader);
  12396. context.deleteShader(fragmentShader);
  12397. return shaderProgram;
  12398. };
  12399. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12400. var results = new Array();
  12401. for (var index = 0; index < uniformsNames.length; index++) {
  12402. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12403. }
  12404. return results;
  12405. };
  12406. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12407. var results = [];
  12408. for (var index = 0; index < attributesNames.length; index++) {
  12409. try {
  12410. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12411. }
  12412. catch (e) {
  12413. results.push(-1);
  12414. }
  12415. }
  12416. return results;
  12417. };
  12418. Engine.prototype.enableEffect = function (effect) {
  12419. if (!effect) {
  12420. return;
  12421. }
  12422. // Use program
  12423. this.bindSamplers(effect);
  12424. this._currentEffect = effect;
  12425. if (effect.onBind) {
  12426. effect.onBind(effect);
  12427. }
  12428. effect.onBindObservable.notifyObservers(effect);
  12429. };
  12430. Engine.prototype.setIntArray = function (uniform, array) {
  12431. if (!uniform)
  12432. return;
  12433. this._gl.uniform1iv(uniform, array);
  12434. };
  12435. Engine.prototype.setIntArray2 = function (uniform, array) {
  12436. if (!uniform || array.length % 2 !== 0)
  12437. return;
  12438. this._gl.uniform2iv(uniform, array);
  12439. };
  12440. Engine.prototype.setIntArray3 = function (uniform, array) {
  12441. if (!uniform || array.length % 3 !== 0)
  12442. return;
  12443. this._gl.uniform3iv(uniform, array);
  12444. };
  12445. Engine.prototype.setIntArray4 = function (uniform, array) {
  12446. if (!uniform || array.length % 4 !== 0)
  12447. return;
  12448. this._gl.uniform4iv(uniform, array);
  12449. };
  12450. Engine.prototype.setFloatArray = function (uniform, array) {
  12451. if (!uniform)
  12452. return;
  12453. this._gl.uniform1fv(uniform, array);
  12454. };
  12455. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12456. if (!uniform || array.length % 2 !== 0)
  12457. return;
  12458. this._gl.uniform2fv(uniform, array);
  12459. };
  12460. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12461. if (!uniform || array.length % 3 !== 0)
  12462. return;
  12463. this._gl.uniform3fv(uniform, array);
  12464. };
  12465. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12466. if (!uniform || array.length % 4 !== 0)
  12467. return;
  12468. this._gl.uniform4fv(uniform, array);
  12469. };
  12470. Engine.prototype.setArray = function (uniform, array) {
  12471. if (!uniform)
  12472. return;
  12473. this._gl.uniform1fv(uniform, array);
  12474. };
  12475. Engine.prototype.setArray2 = function (uniform, array) {
  12476. if (!uniform || array.length % 2 !== 0)
  12477. return;
  12478. this._gl.uniform2fv(uniform, array);
  12479. };
  12480. Engine.prototype.setArray3 = function (uniform, array) {
  12481. if (!uniform || array.length % 3 !== 0)
  12482. return;
  12483. this._gl.uniform3fv(uniform, array);
  12484. };
  12485. Engine.prototype.setArray4 = function (uniform, array) {
  12486. if (!uniform || array.length % 4 !== 0)
  12487. return;
  12488. this._gl.uniform4fv(uniform, array);
  12489. };
  12490. Engine.prototype.setMatrices = function (uniform, matrices) {
  12491. if (!uniform)
  12492. return;
  12493. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12494. };
  12495. Engine.prototype.setMatrix = function (uniform, matrix) {
  12496. if (!uniform)
  12497. return;
  12498. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12499. };
  12500. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12501. if (!uniform)
  12502. return;
  12503. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12504. };
  12505. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12506. if (!uniform)
  12507. return;
  12508. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12509. };
  12510. Engine.prototype.setInt = function (uniform, value) {
  12511. if (!uniform)
  12512. return;
  12513. this._gl.uniform1i(uniform, value);
  12514. };
  12515. Engine.prototype.setFloat = function (uniform, value) {
  12516. if (!uniform)
  12517. return;
  12518. this._gl.uniform1f(uniform, value);
  12519. };
  12520. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12521. if (!uniform)
  12522. return;
  12523. this._gl.uniform2f(uniform, x, y);
  12524. };
  12525. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12526. if (!uniform)
  12527. return;
  12528. this._gl.uniform3f(uniform, x, y, z);
  12529. };
  12530. Engine.prototype.setBool = function (uniform, bool) {
  12531. if (!uniform)
  12532. return;
  12533. this._gl.uniform1i(uniform, bool);
  12534. };
  12535. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12536. if (!uniform)
  12537. return;
  12538. this._gl.uniform4f(uniform, x, y, z, w);
  12539. };
  12540. Engine.prototype.setColor3 = function (uniform, color3) {
  12541. if (!uniform)
  12542. return;
  12543. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12544. };
  12545. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12546. if (!uniform)
  12547. return;
  12548. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12549. };
  12550. /**
  12551. * Sets a Color4 on a uniform variable
  12552. * @param uniform defines the uniform location
  12553. * @param color4 defines the value to be set
  12554. */
  12555. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12556. if (!uniform)
  12557. return;
  12558. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12559. };
  12560. // States
  12561. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12562. if (zOffset === void 0) { zOffset = 0; }
  12563. if (reverseSide === void 0) { reverseSide = false; }
  12564. // Culling
  12565. if (this._depthCullingState.cull !== culling || force) {
  12566. this._depthCullingState.cull = culling;
  12567. }
  12568. // Cull face
  12569. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12570. if (this._depthCullingState.cullFace !== cullFace || force) {
  12571. this._depthCullingState.cullFace = cullFace;
  12572. }
  12573. // Z offset
  12574. this.setZOffset(zOffset);
  12575. // Front face
  12576. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12577. if (this._depthCullingState.frontFace !== frontFace || force) {
  12578. this._depthCullingState.frontFace = frontFace;
  12579. }
  12580. };
  12581. Engine.prototype.setZOffset = function (value) {
  12582. this._depthCullingState.zOffset = value;
  12583. };
  12584. Engine.prototype.getZOffset = function () {
  12585. return this._depthCullingState.zOffset;
  12586. };
  12587. Engine.prototype.setDepthBuffer = function (enable) {
  12588. this._depthCullingState.depthTest = enable;
  12589. };
  12590. Engine.prototype.getDepthWrite = function () {
  12591. return this._depthCullingState.depthMask;
  12592. };
  12593. Engine.prototype.setDepthWrite = function (enable) {
  12594. this._depthCullingState.depthMask = enable;
  12595. };
  12596. Engine.prototype.setColorWrite = function (enable) {
  12597. this._gl.colorMask(enable, enable, enable, enable);
  12598. this._colorWrite = enable;
  12599. };
  12600. Engine.prototype.getColorWrite = function () {
  12601. return this._colorWrite;
  12602. };
  12603. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12604. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12605. };
  12606. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12607. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12608. if (this._alphaMode === mode) {
  12609. return;
  12610. }
  12611. switch (mode) {
  12612. case Engine.ALPHA_DISABLE:
  12613. this._alphaState.alphaBlend = false;
  12614. break;
  12615. case Engine.ALPHA_PREMULTIPLIED:
  12616. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12617. this._alphaState.alphaBlend = true;
  12618. break;
  12619. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12620. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12621. this._alphaState.alphaBlend = true;
  12622. break;
  12623. case Engine.ALPHA_COMBINE:
  12624. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12625. this._alphaState.alphaBlend = true;
  12626. break;
  12627. case Engine.ALPHA_ONEONE:
  12628. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12629. this._alphaState.alphaBlend = true;
  12630. break;
  12631. case Engine.ALPHA_ADD:
  12632. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12633. this._alphaState.alphaBlend = true;
  12634. break;
  12635. case Engine.ALPHA_SUBTRACT:
  12636. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12637. this._alphaState.alphaBlend = true;
  12638. break;
  12639. case Engine.ALPHA_MULTIPLY:
  12640. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  12641. this._alphaState.alphaBlend = true;
  12642. break;
  12643. case Engine.ALPHA_MAXIMIZED:
  12644. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  12645. this._alphaState.alphaBlend = true;
  12646. break;
  12647. case Engine.ALPHA_INTERPOLATE:
  12648. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  12649. this._alphaState.alphaBlend = true;
  12650. break;
  12651. case Engine.ALPHA_SCREENMODE:
  12652. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12653. this._alphaState.alphaBlend = true;
  12654. break;
  12655. }
  12656. if (!noDepthWriteChange) {
  12657. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  12658. }
  12659. this._alphaMode = mode;
  12660. };
  12661. Engine.prototype.getAlphaMode = function () {
  12662. return this._alphaMode;
  12663. };
  12664. // Textures
  12665. Engine.prototype.wipeCaches = function (bruteForce) {
  12666. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  12667. return;
  12668. }
  12669. this._currentEffect = null;
  12670. // 6/8/2017: deltakosh: Should not be required anymore.
  12671. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  12672. if (bruteForce) {
  12673. this.resetTextureCache();
  12674. this._currentProgram = null;
  12675. this._stencilState.reset();
  12676. this._depthCullingState.reset();
  12677. this.setDepthFunctionToLessOrEqual();
  12678. this._alphaState.reset();
  12679. }
  12680. this._resetVertexBufferBinding();
  12681. this._cachedIndexBuffer = null;
  12682. this._cachedEffectForVertexBuffers = null;
  12683. this._unbindVertexArrayObject();
  12684. this.bindIndexBuffer(null);
  12685. };
  12686. /**
  12687. * Set the compressed texture format to use, based on the formats you have, and the formats
  12688. * supported by the hardware / browser.
  12689. *
  12690. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  12691. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  12692. * to API arguments needed to compressed textures. This puts the burden on the container
  12693. * generator to house the arcane code for determining these for current & future formats.
  12694. *
  12695. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  12696. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  12697. *
  12698. * Note: The result of this call is not taken into account when a texture is base64.
  12699. *
  12700. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  12701. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  12702. *
  12703. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  12704. * @returns The extension selected.
  12705. */
  12706. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  12707. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  12708. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  12709. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  12710. return this._textureFormatInUse = this._texturesSupported[i];
  12711. }
  12712. }
  12713. }
  12714. // actively set format to nothing, to allow this to be called more than once
  12715. // and possibly fail the 2nd time
  12716. this._textureFormatInUse = null;
  12717. return null;
  12718. };
  12719. Engine.prototype._createTexture = function () {
  12720. var texture = this._gl.createTexture();
  12721. if (!texture) {
  12722. throw new Error("Unable to create texture");
  12723. }
  12724. return texture;
  12725. };
  12726. /**
  12727. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  12728. * @param {string} urlArg- This contains one of the following:
  12729. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  12730. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  12731. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  12732. *
  12733. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  12734. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  12735. * @param {Scene} scene- Needed for loading to the correct scene.
  12736. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  12737. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  12738. * @param {callback} onError- Optional callback to be called upon failure.
  12739. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  12740. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  12741. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  12742. *
  12743. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  12744. */
  12745. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  12746. var _this = this;
  12747. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12748. if (onLoad === void 0) { onLoad = null; }
  12749. if (onError === void 0) { onError = null; }
  12750. if (buffer === void 0) { buffer = null; }
  12751. if (fallBack === void 0) { fallBack = null; }
  12752. if (format === void 0) { format = null; }
  12753. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  12754. var fromData = url.substr(0, 5) === "data:";
  12755. var fromBlob = url.substr(0, 5) === "blob:";
  12756. var isBase64 = fromData && url.indexOf("base64") !== -1;
  12757. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  12758. // establish the file extension, if possible
  12759. var lastDot = url.lastIndexOf('.');
  12760. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  12761. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  12762. var isTGA = (extension.indexOf(".tga") === 0);
  12763. // determine if a ktx file should be substituted
  12764. var isKTX = false;
  12765. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  12766. url = url.substring(0, lastDot) + this._textureFormatInUse;
  12767. isKTX = true;
  12768. }
  12769. if (scene) {
  12770. scene._addPendingData(texture);
  12771. }
  12772. texture.url = url;
  12773. texture.generateMipMaps = !noMipmap;
  12774. texture.samplingMode = samplingMode;
  12775. texture.invertY = invertY;
  12776. if (!this._doNotHandleContextLost) {
  12777. // Keep a link to the buffer only if we plan to handle context lost
  12778. texture._buffer = buffer;
  12779. }
  12780. var onLoadObserver = null;
  12781. if (onLoad && !fallBack) {
  12782. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  12783. }
  12784. if (!fallBack)
  12785. this._internalTexturesCache.push(texture);
  12786. var onerror = function (message, exception) {
  12787. if (scene) {
  12788. scene._removePendingData(texture);
  12789. }
  12790. if (onLoadObserver) {
  12791. texture.onLoadedObservable.remove(onLoadObserver);
  12792. }
  12793. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  12794. if (isKTX) {
  12795. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12796. }
  12797. else if (BABYLON.Tools.UseFallbackTexture) {
  12798. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  12799. }
  12800. if (onError) {
  12801. onError(message || "Unknown error", exception);
  12802. }
  12803. };
  12804. var callback = null;
  12805. // processing for non-image formats
  12806. if (isKTX || isTGA || isDDS) {
  12807. if (isKTX) {
  12808. callback = function (data) {
  12809. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  12810. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  12811. ktx.uploadLevels(_this._gl, !noMipmap);
  12812. return false;
  12813. }, samplingMode);
  12814. };
  12815. }
  12816. else if (isTGA) {
  12817. callback = function (arrayBuffer) {
  12818. var data = new Uint8Array(arrayBuffer);
  12819. var header = BABYLON.TGATools.GetTGAHeader(data);
  12820. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  12821. BABYLON.TGATools.UploadContent(_this._gl, data);
  12822. return false;
  12823. }, samplingMode);
  12824. };
  12825. }
  12826. else if (isDDS) {
  12827. callback = function (data) {
  12828. var info = BABYLON.DDSTools.GetDDSInfo(data);
  12829. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  12830. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  12831. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  12832. return false;
  12833. }, samplingMode);
  12834. };
  12835. }
  12836. if (!buffer) {
  12837. this._loadFile(url, function (data) {
  12838. if (callback) {
  12839. callback(data);
  12840. }
  12841. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  12842. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  12843. });
  12844. }
  12845. else {
  12846. if (callback) {
  12847. callback(buffer);
  12848. }
  12849. }
  12850. // image format processing
  12851. }
  12852. else {
  12853. var onload = function (img) {
  12854. if (fromBlob && !_this._doNotHandleContextLost) {
  12855. // We need to store the image if we need to rebuild the texture
  12856. // in case of a webgl context lost
  12857. texture._buffer = img;
  12858. }
  12859. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  12860. var gl = _this._gl;
  12861. var isPot = (img.width === potWidth && img.height === potHeight);
  12862. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  12863. if (isPot) {
  12864. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12865. return false;
  12866. }
  12867. // Using shaders to rescale because canvas.drawImage is lossy
  12868. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  12869. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  12870. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  12871. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  12872. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  12873. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  12874. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  12875. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  12876. _this._releaseTexture(source);
  12877. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12878. continuationCallback();
  12879. });
  12880. return true;
  12881. }, samplingMode);
  12882. };
  12883. if (!fromData || isBase64)
  12884. if (buffer instanceof HTMLImageElement) {
  12885. onload(buffer);
  12886. }
  12887. else {
  12888. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  12889. }
  12890. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  12891. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  12892. else
  12893. onload(buffer);
  12894. }
  12895. return texture;
  12896. };
  12897. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  12898. var _this = this;
  12899. var rtt = this.createRenderTargetTexture({
  12900. width: destination.width,
  12901. height: destination.height,
  12902. }, {
  12903. generateMipMaps: false,
  12904. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  12905. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  12906. generateDepthBuffer: false,
  12907. generateStencilBuffer: false
  12908. });
  12909. if (!this._rescalePostProcess) {
  12910. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  12911. }
  12912. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  12913. _this._rescalePostProcess.onApply = function (effect) {
  12914. effect._bindTexture("textureSampler", source);
  12915. };
  12916. var hostingScene = scene;
  12917. if (!hostingScene) {
  12918. hostingScene = _this.scenes[_this.scenes.length - 1];
  12919. }
  12920. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  12921. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  12922. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  12923. _this.unBindFramebuffer(rtt);
  12924. _this._releaseTexture(rtt);
  12925. if (onComplete) {
  12926. onComplete();
  12927. }
  12928. });
  12929. };
  12930. Engine.prototype._getInternalFormat = function (format) {
  12931. var internalFormat = this._gl.RGBA;
  12932. switch (format) {
  12933. case Engine.TEXTUREFORMAT_ALPHA:
  12934. internalFormat = this._gl.ALPHA;
  12935. break;
  12936. case Engine.TEXTUREFORMAT_LUMINANCE:
  12937. internalFormat = this._gl.LUMINANCE;
  12938. break;
  12939. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  12940. internalFormat = this._gl.LUMINANCE_ALPHA;
  12941. break;
  12942. case Engine.TEXTUREFORMAT_RGB:
  12943. case Engine.TEXTUREFORMAT_RGB32F:
  12944. internalFormat = this._gl.RGB;
  12945. break;
  12946. case Engine.TEXTUREFORMAT_RGBA:
  12947. case Engine.TEXTUREFORMAT_RGBA32F:
  12948. internalFormat = this._gl.RGBA;
  12949. break;
  12950. case Engine.TEXTUREFORMAT_R32F:
  12951. internalFormat = this._gl.RED;
  12952. break;
  12953. case Engine.TEXTUREFORMAT_RG32F:
  12954. internalFormat = this._gl.RG;
  12955. break;
  12956. }
  12957. return internalFormat;
  12958. };
  12959. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  12960. if (compression === void 0) { compression = null; }
  12961. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12962. if (!texture) {
  12963. return;
  12964. }
  12965. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  12966. var internalFormat = this._getInternalFormat(format);
  12967. var textureType = this._getWebGLTextureType(type);
  12968. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  12969. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  12970. if (!this._doNotHandleContextLost) {
  12971. texture._bufferView = data;
  12972. texture.format = format;
  12973. texture.type = type;
  12974. texture.invertY = invertY;
  12975. texture._compression = compression;
  12976. }
  12977. if (texture.width % 4 !== 0) {
  12978. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  12979. }
  12980. if (compression && data) {
  12981. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  12982. }
  12983. else {
  12984. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  12985. }
  12986. if (texture.generateMipMaps) {
  12987. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  12988. }
  12989. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  12990. // this.resetTextureCache();
  12991. texture.isReady = true;
  12992. };
  12993. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  12994. if (compression === void 0) { compression = null; }
  12995. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  12996. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  12997. texture.baseWidth = width;
  12998. texture.baseHeight = height;
  12999. texture.width = width;
  13000. texture.height = height;
  13001. texture.format = format;
  13002. texture.generateMipMaps = generateMipMaps;
  13003. texture.samplingMode = samplingMode;
  13004. texture.invertY = invertY;
  13005. texture._compression = compression;
  13006. texture.type = type;
  13007. if (!this._doNotHandleContextLost) {
  13008. texture._bufferView = data;
  13009. }
  13010. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13011. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13012. // Filters
  13013. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13014. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13015. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13016. if (generateMipMaps) {
  13017. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13018. }
  13019. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13020. this._internalTexturesCache.push(texture);
  13021. return texture;
  13022. };
  13023. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13024. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13025. texture.baseWidth = width;
  13026. texture.baseHeight = height;
  13027. if (generateMipMaps) {
  13028. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13029. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13030. }
  13031. // this.resetTextureCache();
  13032. texture.width = width;
  13033. texture.height = height;
  13034. texture.isReady = false;
  13035. texture.generateMipMaps = generateMipMaps;
  13036. texture.samplingMode = samplingMode;
  13037. this.updateTextureSamplingMode(samplingMode, texture);
  13038. this._internalTexturesCache.push(texture);
  13039. return texture;
  13040. };
  13041. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13042. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13043. if (texture.isCube) {
  13044. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13045. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13046. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13047. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13048. }
  13049. else if (texture.is3D) {
  13050. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13051. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13052. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13053. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13054. }
  13055. else {
  13056. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13057. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13058. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13059. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13060. }
  13061. texture.samplingMode = samplingMode;
  13062. };
  13063. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13064. if (premulAlpha === void 0) { premulAlpha = false; }
  13065. if (!texture) {
  13066. return;
  13067. }
  13068. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13069. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13070. if (premulAlpha) {
  13071. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13072. }
  13073. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13074. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13075. if (texture.generateMipMaps) {
  13076. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13077. }
  13078. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13079. if (premulAlpha) {
  13080. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13081. }
  13082. texture.isReady = true;
  13083. };
  13084. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13085. if (!texture || texture._isDisabled) {
  13086. return;
  13087. }
  13088. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13089. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13090. try {
  13091. // Testing video texture support
  13092. if (this._videoTextureSupported === undefined) {
  13093. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13094. if (this._gl.getError() !== 0) {
  13095. this._videoTextureSupported = false;
  13096. }
  13097. else {
  13098. this._videoTextureSupported = true;
  13099. }
  13100. }
  13101. // Copy video through the current working canvas if video texture is not supported
  13102. if (!this._videoTextureSupported) {
  13103. if (!texture._workingCanvas) {
  13104. texture._workingCanvas = document.createElement("canvas");
  13105. var context = texture._workingCanvas.getContext("2d");
  13106. if (!context) {
  13107. throw new Error("Unable to get 2d context");
  13108. }
  13109. texture._workingContext = context;
  13110. texture._workingCanvas.width = texture.width;
  13111. texture._workingCanvas.height = texture.height;
  13112. }
  13113. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13114. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13115. }
  13116. else {
  13117. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13118. }
  13119. if (texture.generateMipMaps) {
  13120. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13121. }
  13122. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13123. // this.resetTextureCache();
  13124. texture.isReady = true;
  13125. }
  13126. catch (ex) {
  13127. // Something unexpected
  13128. // Let's disable the texture
  13129. texture._isDisabled = true;
  13130. }
  13131. };
  13132. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13133. var fullOptions = new RenderTargetCreationOptions();
  13134. if (options !== undefined && typeof options === "object") {
  13135. fullOptions.generateMipMaps = options.generateMipMaps;
  13136. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13137. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13138. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13139. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13140. }
  13141. else {
  13142. fullOptions.generateMipMaps = options;
  13143. fullOptions.generateDepthBuffer = true;
  13144. fullOptions.generateStencilBuffer = false;
  13145. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13146. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13147. }
  13148. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13149. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13150. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13151. }
  13152. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13153. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13154. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13155. }
  13156. var gl = this._gl;
  13157. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13158. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13159. var width = size.width || size;
  13160. var height = size.height || size;
  13161. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13162. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13163. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13164. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13165. }
  13166. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13167. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13168. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13169. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13170. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13171. // Create the framebuffer
  13172. var framebuffer = gl.createFramebuffer();
  13173. this.bindUnboundFramebuffer(framebuffer);
  13174. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13175. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13176. if (fullOptions.generateMipMaps) {
  13177. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13178. }
  13179. // Unbind
  13180. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13181. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13182. this.bindUnboundFramebuffer(null);
  13183. texture._framebuffer = framebuffer;
  13184. texture.baseWidth = width;
  13185. texture.baseHeight = height;
  13186. texture.width = width;
  13187. texture.height = height;
  13188. texture.isReady = true;
  13189. texture.samples = 1;
  13190. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13191. texture.samplingMode = fullOptions.samplingMode;
  13192. texture.type = fullOptions.type;
  13193. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13194. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13195. // this.resetTextureCache();
  13196. this._internalTexturesCache.push(texture);
  13197. return texture;
  13198. };
  13199. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13200. var generateMipMaps = false;
  13201. var generateDepthBuffer = true;
  13202. var generateStencilBuffer = false;
  13203. var generateDepthTexture = false;
  13204. var textureCount = 1;
  13205. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13206. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13207. var types = [], samplingModes = [];
  13208. if (options !== undefined) {
  13209. generateMipMaps = options.generateMipMaps;
  13210. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13211. generateStencilBuffer = options.generateStencilBuffer;
  13212. generateDepthTexture = options.generateDepthTexture;
  13213. textureCount = options.textureCount || 1;
  13214. if (options.types) {
  13215. types = options.types;
  13216. }
  13217. if (options.samplingModes) {
  13218. samplingModes = options.samplingModes;
  13219. }
  13220. }
  13221. var gl = this._gl;
  13222. // Create the framebuffer
  13223. var framebuffer = gl.createFramebuffer();
  13224. this.bindUnboundFramebuffer(framebuffer);
  13225. var width = size.width || size;
  13226. var height = size.height || size;
  13227. var textures = [];
  13228. var attachments = [];
  13229. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13230. for (var i = 0; i < textureCount; i++) {
  13231. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13232. var type = types[i] || defaultType;
  13233. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13234. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13235. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13236. }
  13237. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13238. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13239. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13240. }
  13241. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13242. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13243. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13244. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13245. }
  13246. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13247. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13248. textures.push(texture);
  13249. attachments.push(attachment);
  13250. gl.activeTexture(gl["TEXTURE" + i]);
  13251. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13252. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13253. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13254. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13255. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13256. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13257. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13258. if (generateMipMaps) {
  13259. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13260. }
  13261. // Unbind
  13262. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13263. texture._framebuffer = framebuffer;
  13264. texture._depthStencilBuffer = depthStencilBuffer;
  13265. texture.baseWidth = width;
  13266. texture.baseHeight = height;
  13267. texture.width = width;
  13268. texture.height = height;
  13269. texture.isReady = true;
  13270. texture.samples = 1;
  13271. texture.generateMipMaps = generateMipMaps;
  13272. texture.samplingMode = samplingMode;
  13273. texture.type = type;
  13274. texture._generateDepthBuffer = generateDepthBuffer;
  13275. texture._generateStencilBuffer = generateStencilBuffer;
  13276. texture._attachments = attachments;
  13277. this._internalTexturesCache.push(texture);
  13278. }
  13279. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13280. // Depth texture
  13281. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13282. gl.activeTexture(gl.TEXTURE0);
  13283. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13284. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13285. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13286. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13287. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13288. 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);
  13289. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13290. depthTexture._framebuffer = framebuffer;
  13291. depthTexture.baseWidth = width;
  13292. depthTexture.baseHeight = height;
  13293. depthTexture.width = width;
  13294. depthTexture.height = height;
  13295. depthTexture.isReady = true;
  13296. depthTexture.samples = 1;
  13297. depthTexture.generateMipMaps = generateMipMaps;
  13298. depthTexture.samplingMode = gl.NEAREST;
  13299. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13300. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13301. textures.push(depthTexture);
  13302. this._internalTexturesCache.push(depthTexture);
  13303. }
  13304. gl.drawBuffers(attachments);
  13305. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13306. this.bindUnboundFramebuffer(null);
  13307. this.resetTextureCache();
  13308. return textures;
  13309. };
  13310. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13311. if (samples === void 0) { samples = 1; }
  13312. var depthStencilBuffer = null;
  13313. var gl = this._gl;
  13314. // Create the depth/stencil buffer
  13315. if (generateStencilBuffer) {
  13316. depthStencilBuffer = gl.createRenderbuffer();
  13317. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13318. if (samples > 1) {
  13319. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13320. }
  13321. else {
  13322. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13323. }
  13324. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13325. }
  13326. else if (generateDepthBuffer) {
  13327. depthStencilBuffer = gl.createRenderbuffer();
  13328. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13329. if (samples > 1) {
  13330. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13331. }
  13332. else {
  13333. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13334. }
  13335. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13336. }
  13337. return depthStencilBuffer;
  13338. };
  13339. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13340. if (this.webGLVersion < 2 || !texture) {
  13341. return 1;
  13342. }
  13343. if (texture.samples === samples) {
  13344. return samples;
  13345. }
  13346. var gl = this._gl;
  13347. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13348. // Dispose previous render buffers
  13349. if (texture._depthStencilBuffer) {
  13350. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13351. texture._depthStencilBuffer = null;
  13352. }
  13353. if (texture._MSAAFramebuffer) {
  13354. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13355. texture._MSAAFramebuffer = null;
  13356. }
  13357. if (texture._MSAARenderBuffer) {
  13358. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13359. texture._MSAARenderBuffer = null;
  13360. }
  13361. if (samples > 1) {
  13362. var framebuffer = gl.createFramebuffer();
  13363. if (!framebuffer) {
  13364. throw new Error("Unable to create multi sampled framebuffer");
  13365. }
  13366. texture._MSAAFramebuffer = framebuffer;
  13367. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13368. var colorRenderbuffer = gl.createRenderbuffer();
  13369. if (!colorRenderbuffer) {
  13370. throw new Error("Unable to create multi sampled framebuffer");
  13371. }
  13372. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13373. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13374. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13375. texture._MSAARenderBuffer = colorRenderbuffer;
  13376. }
  13377. else {
  13378. this.bindUnboundFramebuffer(texture._framebuffer);
  13379. }
  13380. texture.samples = samples;
  13381. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13382. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13383. this.bindUnboundFramebuffer(null);
  13384. return samples;
  13385. };
  13386. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13387. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13388. return 1;
  13389. }
  13390. if (textures[0].samples === samples) {
  13391. return samples;
  13392. }
  13393. var gl = this._gl;
  13394. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13395. // Dispose previous render buffers
  13396. if (textures[0]._depthStencilBuffer) {
  13397. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13398. textures[0]._depthStencilBuffer = null;
  13399. }
  13400. if (textures[0]._MSAAFramebuffer) {
  13401. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13402. textures[0]._MSAAFramebuffer = null;
  13403. }
  13404. for (var i = 0; i < textures.length; i++) {
  13405. if (textures[i]._MSAARenderBuffer) {
  13406. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13407. textures[i]._MSAARenderBuffer = null;
  13408. }
  13409. }
  13410. if (samples > 1) {
  13411. var framebuffer = gl.createFramebuffer();
  13412. if (!framebuffer) {
  13413. throw new Error("Unable to create multi sampled framebuffer");
  13414. }
  13415. this.bindUnboundFramebuffer(framebuffer);
  13416. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13417. var attachments = [];
  13418. for (var i = 0; i < textures.length; i++) {
  13419. var texture = textures[i];
  13420. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13421. var colorRenderbuffer = gl.createRenderbuffer();
  13422. if (!colorRenderbuffer) {
  13423. throw new Error("Unable to create multi sampled framebuffer");
  13424. }
  13425. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13426. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13427. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13428. texture._MSAAFramebuffer = framebuffer;
  13429. texture._MSAARenderBuffer = colorRenderbuffer;
  13430. texture.samples = samples;
  13431. texture._depthStencilBuffer = depthStencilBuffer;
  13432. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13433. attachments.push(attachment);
  13434. }
  13435. gl.drawBuffers(attachments);
  13436. }
  13437. else {
  13438. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13439. }
  13440. this.bindUnboundFramebuffer(null);
  13441. return samples;
  13442. };
  13443. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13444. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13445. };
  13446. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13447. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13448. };
  13449. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13450. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE }, options);
  13451. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13452. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13453. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13454. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13455. }
  13456. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13457. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13458. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13459. }
  13460. var gl = this._gl;
  13461. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13462. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13463. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13464. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13465. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13466. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13467. }
  13468. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13469. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13470. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13471. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13472. for (var face = 0; face < 6; face++) {
  13473. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), size, size, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  13474. }
  13475. // Create the framebuffer
  13476. var framebuffer = gl.createFramebuffer();
  13477. this.bindUnboundFramebuffer(framebuffer);
  13478. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  13479. // MipMaps
  13480. if (fullOptions.generateMipMaps) {
  13481. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13482. }
  13483. // Unbind
  13484. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13485. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13486. this.bindUnboundFramebuffer(null);
  13487. texture._framebuffer = framebuffer;
  13488. texture.width = size;
  13489. texture.height = size;
  13490. texture.isReady = true;
  13491. texture.isCube = true;
  13492. texture.samples = 1;
  13493. texture.generateMipMaps = fullOptions.generateMipMaps;
  13494. texture.samplingMode = fullOptions.samplingMode;
  13495. texture.type = fullOptions.type;
  13496. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13497. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  13498. this._internalTexturesCache.push(texture);
  13499. return texture;
  13500. };
  13501. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  13502. var _this = this;
  13503. if (onLoad === void 0) { onLoad = null; }
  13504. if (onError === void 0) { onError = null; }
  13505. if (forcedExtension === void 0) { forcedExtension = null; }
  13506. var callback = function (loadData) {
  13507. if (!loadData) {
  13508. if (onLoad) {
  13509. onLoad(null);
  13510. }
  13511. return;
  13512. }
  13513. var texture = loadData.texture;
  13514. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  13515. texture._lodGenerationScale = scale;
  13516. texture._lodGenerationOffset = offset;
  13517. if (_this._caps.textureLOD) {
  13518. // Do not add extra process if texture lod is supported.
  13519. if (onLoad) {
  13520. onLoad(texture);
  13521. }
  13522. return;
  13523. }
  13524. var mipSlices = 3;
  13525. var gl = _this._gl;
  13526. var width = loadData.width;
  13527. if (!width) {
  13528. return;
  13529. }
  13530. var textures = [];
  13531. for (var i = 0; i < mipSlices; i++) {
  13532. //compute LOD from even spacing in smoothness (matching shader calculation)
  13533. var smoothness = i / (mipSlices - 1);
  13534. var roughness = 1 - smoothness;
  13535. var minLODIndex = offset; // roughness = 0
  13536. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  13537. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  13538. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  13539. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13540. glTextureFromLod.isCube = true;
  13541. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  13542. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13543. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13544. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13545. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13546. if (loadData.isDDS) {
  13547. var info = loadData.info;
  13548. var data = loadData.data;
  13549. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13550. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  13551. }
  13552. else {
  13553. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  13554. }
  13555. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13556. // Wrap in a base texture for easy binding.
  13557. var lodTexture = new BABYLON.BaseTexture(scene);
  13558. lodTexture.isCube = true;
  13559. lodTexture._texture = glTextureFromLod;
  13560. glTextureFromLod.isReady = true;
  13561. textures.push(lodTexture);
  13562. }
  13563. texture._lodTextureHigh = textures[2];
  13564. texture._lodTextureMid = textures[1];
  13565. texture._lodTextureLow = textures[0];
  13566. if (onLoad) {
  13567. onLoad(texture);
  13568. }
  13569. };
  13570. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  13571. };
  13572. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  13573. var _this = this;
  13574. if (onLoad === void 0) { onLoad = null; }
  13575. if (onError === void 0) { onError = null; }
  13576. if (forcedExtension === void 0) { forcedExtension = null; }
  13577. var gl = this._gl;
  13578. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  13579. texture.isCube = true;
  13580. texture.url = rootUrl;
  13581. texture.generateMipMaps = !noMipmap;
  13582. if (!this._doNotHandleContextLost) {
  13583. texture._extension = forcedExtension;
  13584. texture._files = files;
  13585. }
  13586. var isKTX = false;
  13587. var isDDS = false;
  13588. var lastDot = rootUrl.lastIndexOf('.');
  13589. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  13590. if (this._textureFormatInUse) {
  13591. extension = this._textureFormatInUse;
  13592. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  13593. isKTX = true;
  13594. }
  13595. else {
  13596. isDDS = (extension === ".dds");
  13597. }
  13598. var onerror = function (request, exception) {
  13599. if (onError && request) {
  13600. onError(request.status + " " + request.statusText, exception);
  13601. }
  13602. };
  13603. if (isKTX) {
  13604. this._loadFile(rootUrl, function (data) {
  13605. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  13606. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  13607. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13608. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  13609. ktx.uploadLevels(_this._gl, !noMipmap);
  13610. _this.setCubeMapTextureParams(gl, loadMipmap);
  13611. texture.width = ktx.pixelWidth;
  13612. texture.height = ktx.pixelHeight;
  13613. texture.isReady = true;
  13614. }, undefined, undefined, true, onerror);
  13615. }
  13616. else if (isDDS) {
  13617. if (files && files.length === 6) {
  13618. this._cascadeLoadFiles(scene, function (imgs) {
  13619. var info;
  13620. var loadMipmap = false;
  13621. var width = 0;
  13622. for (var index = 0; index < imgs.length; index++) {
  13623. var data = imgs[index];
  13624. info = BABYLON.DDSTools.GetDDSInfo(data);
  13625. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13626. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13627. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13628. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  13629. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13630. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13631. }
  13632. texture.width = info.width;
  13633. texture.height = info.height;
  13634. texture.type = info.textureType;
  13635. width = info.width;
  13636. }
  13637. _this.setCubeMapTextureParams(gl, loadMipmap);
  13638. texture.isReady = true;
  13639. if (onLoad) {
  13640. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  13641. }
  13642. }, files, onError);
  13643. }
  13644. else {
  13645. this._loadFile(rootUrl, function (data) {
  13646. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13647. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  13648. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13649. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  13650. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  13651. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  13652. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13653. }
  13654. _this.setCubeMapTextureParams(gl, loadMipmap);
  13655. texture.width = info.width;
  13656. texture.height = info.height;
  13657. texture.isReady = true;
  13658. texture.type = info.textureType;
  13659. if (onLoad) {
  13660. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  13661. }
  13662. }, undefined, undefined, true, onerror);
  13663. }
  13664. }
  13665. else {
  13666. if (!files) {
  13667. throw new Error("Cannot load cubemap because files were not defined");
  13668. }
  13669. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  13670. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  13671. var height = width;
  13672. _this._prepareWorkingCanvas();
  13673. if (!_this._workingCanvas || !_this._workingContext) {
  13674. return;
  13675. }
  13676. _this._workingCanvas.width = width;
  13677. _this._workingCanvas.height = height;
  13678. var faces = [
  13679. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  13680. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  13681. ];
  13682. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13683. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13684. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  13685. for (var index = 0; index < faces.length; index++) {
  13686. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  13687. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  13688. }
  13689. if (!noMipmap) {
  13690. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13691. }
  13692. _this.setCubeMapTextureParams(gl, !noMipmap);
  13693. texture.width = width;
  13694. texture.height = height;
  13695. texture.isReady = true;
  13696. if (format) {
  13697. texture.format = format;
  13698. }
  13699. texture.onLoadedObservable.notifyObservers(texture);
  13700. texture.onLoadedObservable.clear();
  13701. if (onLoad) {
  13702. onLoad();
  13703. }
  13704. }, files, onError);
  13705. }
  13706. this._internalTexturesCache.push(texture);
  13707. return texture;
  13708. };
  13709. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  13710. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13711. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  13712. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13713. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13714. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13715. // this.resetTextureCache();
  13716. };
  13717. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  13718. if (compression === void 0) { compression = null; }
  13719. if (level === void 0) { level = 0; }
  13720. texture._bufferViewArray = data;
  13721. texture.format = format;
  13722. texture.type = type;
  13723. texture.invertY = invertY;
  13724. texture._compression = compression;
  13725. var gl = this._gl;
  13726. var textureType = this._getWebGLTextureType(type);
  13727. var internalFormat = this._getInternalFormat(format);
  13728. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  13729. var needConversion = false;
  13730. if (internalFormat === gl.RGB) {
  13731. internalFormat = gl.RGBA;
  13732. needConversion = true;
  13733. }
  13734. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13735. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13736. if (texture.width % 4 !== 0) {
  13737. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  13738. }
  13739. // Data are known to be in +X +Y +Z -X -Y -Z
  13740. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13741. var faceData = data[faceIndex];
  13742. if (compression) {
  13743. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  13744. }
  13745. else {
  13746. if (needConversion) {
  13747. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  13748. }
  13749. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  13750. }
  13751. }
  13752. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13753. if (isPot && texture.generateMipMaps && level === 0) {
  13754. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13755. }
  13756. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13757. // this.resetTextureCache();
  13758. texture.isReady = true;
  13759. };
  13760. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  13761. if (compression === void 0) { compression = null; }
  13762. var gl = this._gl;
  13763. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  13764. texture.isCube = true;
  13765. texture.generateMipMaps = generateMipMaps;
  13766. texture.format = format;
  13767. texture.type = type;
  13768. if (!this._doNotHandleContextLost) {
  13769. texture._bufferViewArray = data;
  13770. }
  13771. var textureType = this._getWebGLTextureType(type);
  13772. var internalFormat = this._getInternalFormat(format);
  13773. if (internalFormat === gl.RGB) {
  13774. internalFormat = gl.RGBA;
  13775. }
  13776. var width = size;
  13777. var height = width;
  13778. texture.width = width;
  13779. texture.height = height;
  13780. // Double check on POT to generate Mips.
  13781. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  13782. if (!isPot) {
  13783. generateMipMaps = false;
  13784. }
  13785. // Upload data if needed. The texture won't be ready until then.
  13786. if (data) {
  13787. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  13788. }
  13789. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13790. // Filters
  13791. if (data && generateMipMaps) {
  13792. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  13793. }
  13794. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  13795. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13796. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13797. }
  13798. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  13799. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13800. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13801. }
  13802. else {
  13803. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13804. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13805. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13806. }
  13807. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13808. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13809. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13810. return texture;
  13811. };
  13812. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  13813. var _this = this;
  13814. if (onLoad === void 0) { onLoad = null; }
  13815. if (onError === void 0) { onError = null; }
  13816. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13817. if (invertY === void 0) { invertY = false; }
  13818. var gl = this._gl;
  13819. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  13820. scene._addPendingData(texture);
  13821. texture.url = url;
  13822. this._internalTexturesCache.push(texture);
  13823. var onerror = function (request, exception) {
  13824. scene._removePendingData(texture);
  13825. if (onError && request) {
  13826. onError(request.status + " " + request.statusText, exception);
  13827. }
  13828. };
  13829. var internalCallback = function (data) {
  13830. var width = texture.width;
  13831. var faceDataArrays = callback(data);
  13832. if (!faceDataArrays) {
  13833. return;
  13834. }
  13835. if (mipmmapGenerator) {
  13836. var textureType = _this._getWebGLTextureType(type);
  13837. var internalFormat = _this._getInternalFormat(format);
  13838. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  13839. var needConversion = false;
  13840. if (internalFormat === gl.RGB) {
  13841. internalFormat = gl.RGBA;
  13842. needConversion = true;
  13843. }
  13844. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13845. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  13846. var mipData = mipmmapGenerator(faceDataArrays);
  13847. for (var level = 0; level < mipData.length; level++) {
  13848. var mipSize = width >> level;
  13849. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  13850. var mipFaceData = mipData[level][faceIndex];
  13851. if (needConversion) {
  13852. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  13853. }
  13854. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  13855. }
  13856. }
  13857. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13858. }
  13859. else {
  13860. texture.generateMipMaps = !noMipmap;
  13861. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  13862. }
  13863. texture.isReady = true;
  13864. // this.resetTextureCache();
  13865. scene._removePendingData(texture);
  13866. if (onLoad) {
  13867. onLoad();
  13868. }
  13869. };
  13870. this._loadFile(url, function (data) {
  13871. internalCallback(data);
  13872. }, undefined, scene.database, true, onerror);
  13873. return texture;
  13874. };
  13875. ;
  13876. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  13877. if (compression === void 0) { compression = null; }
  13878. var internalFormat = this._getInternalFormat(format);
  13879. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13880. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13881. if (!this._doNotHandleContextLost) {
  13882. texture._bufferView = data;
  13883. texture.format = format;
  13884. texture.invertY = invertY;
  13885. texture._compression = compression;
  13886. }
  13887. if (texture.width % 4 !== 0) {
  13888. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13889. }
  13890. if (compression && data) {
  13891. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  13892. }
  13893. else {
  13894. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  13895. }
  13896. if (texture.generateMipMaps) {
  13897. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13898. }
  13899. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13900. // this.resetTextureCache();
  13901. texture.isReady = true;
  13902. };
  13903. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  13904. if (compression === void 0) { compression = null; }
  13905. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  13906. texture.baseWidth = width;
  13907. texture.baseHeight = height;
  13908. texture.baseDepth = depth;
  13909. texture.width = width;
  13910. texture.height = height;
  13911. texture.depth = depth;
  13912. texture.format = format;
  13913. texture.generateMipMaps = generateMipMaps;
  13914. texture.samplingMode = samplingMode;
  13915. texture.is3D = true;
  13916. if (!this._doNotHandleContextLost) {
  13917. texture._bufferView = data;
  13918. }
  13919. this.updateRawTexture3D(texture, data, format, invertY, compression);
  13920. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13921. // Filters
  13922. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13923. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13924. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13925. if (generateMipMaps) {
  13926. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  13927. }
  13928. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13929. this._internalTexturesCache.push(texture);
  13930. return texture;
  13931. };
  13932. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  13933. var gl = this._gl;
  13934. if (!gl) {
  13935. return;
  13936. }
  13937. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  13938. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13939. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13940. if (!noMipmap && !isCompressed) {
  13941. gl.generateMipmap(gl.TEXTURE_2D);
  13942. }
  13943. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13944. // this.resetTextureCache();
  13945. if (scene) {
  13946. scene._removePendingData(texture);
  13947. }
  13948. texture.onLoadedObservable.notifyObservers(texture);
  13949. texture.onLoadedObservable.clear();
  13950. };
  13951. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  13952. var _this = this;
  13953. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13954. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  13955. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  13956. var gl = this._gl;
  13957. if (!gl) {
  13958. return;
  13959. }
  13960. if (!texture._webGLTexture) {
  13961. // this.resetTextureCache();
  13962. if (scene) {
  13963. scene._removePendingData(texture);
  13964. }
  13965. return;
  13966. }
  13967. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13968. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13969. texture.baseWidth = width;
  13970. texture.baseHeight = height;
  13971. texture.width = potWidth;
  13972. texture.height = potHeight;
  13973. texture.isReady = true;
  13974. if (processFunction(potWidth, potHeight, function () {
  13975. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13976. })) {
  13977. // Returning as texture needs extra async steps
  13978. return;
  13979. }
  13980. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  13981. };
  13982. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  13983. // Create new RGBA data container.
  13984. var rgbaData;
  13985. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  13986. rgbaData = new Float32Array(width * height * 4);
  13987. }
  13988. else {
  13989. rgbaData = new Uint32Array(width * height * 4);
  13990. }
  13991. // Convert each pixel.
  13992. for (var x = 0; x < width; x++) {
  13993. for (var y = 0; y < height; y++) {
  13994. var index = (y * width + x) * 3;
  13995. var newIndex = (y * width + x) * 4;
  13996. // Map Old Value to new value.
  13997. rgbaData[newIndex + 0] = rgbData[index + 0];
  13998. rgbaData[newIndex + 1] = rgbData[index + 1];
  13999. rgbaData[newIndex + 2] = rgbData[index + 2];
  14000. // Add fully opaque alpha channel.
  14001. rgbaData[newIndex + 3] = 1;
  14002. }
  14003. }
  14004. return rgbaData;
  14005. };
  14006. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14007. var gl = this._gl;
  14008. if (texture._framebuffer) {
  14009. gl.deleteFramebuffer(texture._framebuffer);
  14010. texture._framebuffer = null;
  14011. }
  14012. if (texture._depthStencilBuffer) {
  14013. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14014. texture._depthStencilBuffer = null;
  14015. }
  14016. if (texture._MSAAFramebuffer) {
  14017. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14018. texture._MSAAFramebuffer = null;
  14019. }
  14020. if (texture._MSAARenderBuffer) {
  14021. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14022. texture._MSAARenderBuffer = null;
  14023. }
  14024. };
  14025. Engine.prototype._releaseTexture = function (texture) {
  14026. var gl = this._gl;
  14027. this._releaseFramebufferObjects(texture);
  14028. gl.deleteTexture(texture._webGLTexture);
  14029. // Unbind channels
  14030. this.unbindAllTextures();
  14031. var index = this._internalTexturesCache.indexOf(texture);
  14032. if (index !== -1) {
  14033. this._internalTexturesCache.splice(index, 1);
  14034. }
  14035. // Integrated fixed lod samplers.
  14036. if (texture._lodTextureHigh) {
  14037. texture._lodTextureHigh.dispose();
  14038. }
  14039. if (texture._lodTextureMid) {
  14040. texture._lodTextureMid.dispose();
  14041. }
  14042. if (texture._lodTextureLow) {
  14043. texture._lodTextureLow.dispose();
  14044. }
  14045. };
  14046. Engine.prototype.setProgram = function (program) {
  14047. if (this._currentProgram !== program) {
  14048. this._gl.useProgram(program);
  14049. this._currentProgram = program;
  14050. }
  14051. };
  14052. Engine.prototype.bindSamplers = function (effect) {
  14053. this.setProgram(effect.getProgram());
  14054. var samplers = effect.getSamplers();
  14055. for (var index = 0; index < samplers.length; index++) {
  14056. var uniform = effect.getUniform(samplers[index]);
  14057. if (uniform) {
  14058. this._boundUniforms[index] = uniform;
  14059. }
  14060. }
  14061. this._currentEffect = null;
  14062. };
  14063. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14064. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14065. return;
  14066. }
  14067. // Remove
  14068. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14069. // Bind last to it
  14070. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14071. // Bind to dummy
  14072. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14073. };
  14074. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14075. if (!internalTexture) {
  14076. return -1;
  14077. }
  14078. internalTexture._initialSlot = channel;
  14079. if (this.disableTextureBindingOptimization) {
  14080. if (channel !== internalTexture._designatedSlot) {
  14081. this._textureCollisions.addCount(1, false);
  14082. }
  14083. }
  14084. else {
  14085. if (channel !== internalTexture._designatedSlot) {
  14086. if (internalTexture._designatedSlot > -1) {
  14087. return internalTexture._designatedSlot;
  14088. }
  14089. else {
  14090. // No slot for this texture, let's pick a new one (if we find a free slot)
  14091. if (this._nextFreeTextureSlots.length) {
  14092. return this._nextFreeTextureSlots[0];
  14093. }
  14094. // We need to recycle the oldest bound texture, sorry.
  14095. this._textureCollisions.addCount(1, false);
  14096. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14097. }
  14098. }
  14099. }
  14100. return channel;
  14101. };
  14102. Engine.prototype._linkTrackers = function (previous, next) {
  14103. previous.next = next;
  14104. next.previous = previous;
  14105. };
  14106. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14107. var currentSlot = internalTexture._designatedSlot;
  14108. if (currentSlot === -1) {
  14109. return -1;
  14110. }
  14111. internalTexture._designatedSlot = -1;
  14112. if (this.disableTextureBindingOptimization) {
  14113. return -1;
  14114. }
  14115. // Remove from bound list
  14116. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14117. // Free the slot
  14118. this._boundTexturesCache[currentSlot] = null;
  14119. this._nextFreeTextureSlots.push(currentSlot);
  14120. return currentSlot;
  14121. };
  14122. Engine.prototype._activateCurrentTexture = function () {
  14123. if (this._currentTextureChannel !== this._activeChannel) {
  14124. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14125. this._currentTextureChannel = this._activeChannel;
  14126. }
  14127. };
  14128. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14129. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14130. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14131. this._activeChannel = texture._designatedSlot;
  14132. }
  14133. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14134. var isTextureForRendering = texture && texture._initialSlot > -1;
  14135. if (currentTextureBound !== texture) {
  14136. if (currentTextureBound) {
  14137. this._removeDesignatedSlot(currentTextureBound);
  14138. }
  14139. this._activateCurrentTexture();
  14140. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14141. this._boundTexturesCache[this._activeChannel] = texture;
  14142. if (texture) {
  14143. if (!this.disableTextureBindingOptimization) {
  14144. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14145. if (slotIndex > -1) {
  14146. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14147. }
  14148. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14149. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14150. }
  14151. texture._designatedSlot = this._activeChannel;
  14152. }
  14153. }
  14154. else if (forTextureDataUpdate) {
  14155. this._activateCurrentTexture();
  14156. }
  14157. if (isTextureForRendering && !forTextureDataUpdate) {
  14158. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14159. }
  14160. };
  14161. Engine.prototype._bindTexture = function (channel, texture) {
  14162. if (channel < 0) {
  14163. return;
  14164. }
  14165. if (texture) {
  14166. channel = this._getCorrectTextureChannel(channel, texture);
  14167. }
  14168. this._activeChannel = channel;
  14169. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14170. };
  14171. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14172. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14173. };
  14174. Engine.prototype.unbindAllTextures = function () {
  14175. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14176. this._activeChannel = channel;
  14177. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14178. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14179. if (this.webGLVersion > 1) {
  14180. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14181. }
  14182. }
  14183. };
  14184. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14185. if (channel < 0) {
  14186. return;
  14187. }
  14188. if (uniform) {
  14189. this._boundUniforms[channel] = uniform;
  14190. }
  14191. this._setTexture(channel, texture);
  14192. };
  14193. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14194. var uniform = this._boundUniforms[sourceSlot];
  14195. if (uniform._currentState === destination) {
  14196. return;
  14197. }
  14198. this._gl.uniform1i(uniform, destination);
  14199. uniform._currentState = destination;
  14200. };
  14201. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray) {
  14202. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14203. // Not ready?
  14204. if (!texture) {
  14205. if (this._boundTexturesCache[channel] != null) {
  14206. this._activeChannel = channel;
  14207. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14208. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14209. if (this.webGLVersion > 1) {
  14210. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14211. }
  14212. }
  14213. return false;
  14214. }
  14215. // Video
  14216. if (texture.video) {
  14217. this._activeChannel = channel;
  14218. texture.update();
  14219. }
  14220. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14221. texture.delayLoad();
  14222. return false;
  14223. }
  14224. var internalTexture;
  14225. if (texture.isReady()) {
  14226. internalTexture = texture.getInternalTexture();
  14227. }
  14228. else if (texture.isCube) {
  14229. internalTexture = this.emptyCubeTexture;
  14230. }
  14231. else if (texture.is3D) {
  14232. internalTexture = this.emptyTexture3D;
  14233. }
  14234. else {
  14235. internalTexture = this.emptyTexture;
  14236. }
  14237. if (!isPartOfTextureArray) {
  14238. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14239. }
  14240. if (this._boundTexturesCache[channel] === internalTexture) {
  14241. this._moveBoundTextureOnTop(internalTexture);
  14242. if (!isPartOfTextureArray) {
  14243. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14244. }
  14245. return false;
  14246. }
  14247. this._activeChannel = channel;
  14248. if (internalTexture && internalTexture.is3D) {
  14249. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14250. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14251. internalTexture._cachedWrapU = texture.wrapU;
  14252. switch (texture.wrapU) {
  14253. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14254. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14255. break;
  14256. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14257. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14258. break;
  14259. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14260. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14261. break;
  14262. }
  14263. }
  14264. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14265. internalTexture._cachedWrapV = texture.wrapV;
  14266. switch (texture.wrapV) {
  14267. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14268. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14269. break;
  14270. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14271. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14272. break;
  14273. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14274. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14275. break;
  14276. }
  14277. }
  14278. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14279. internalTexture._cachedWrapR = texture.wrapR;
  14280. switch (texture.wrapR) {
  14281. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14282. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14283. break;
  14284. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14285. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14286. break;
  14287. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14288. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14289. break;
  14290. }
  14291. }
  14292. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14293. }
  14294. else if (internalTexture && internalTexture.isCube) {
  14295. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14296. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14297. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14298. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14299. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14300. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14301. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14302. }
  14303. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14304. }
  14305. else {
  14306. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14307. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14308. internalTexture._cachedWrapU = texture.wrapU;
  14309. switch (texture.wrapU) {
  14310. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14311. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14312. break;
  14313. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14314. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14315. break;
  14316. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14317. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14318. break;
  14319. }
  14320. }
  14321. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14322. internalTexture._cachedWrapV = texture.wrapV;
  14323. switch (texture.wrapV) {
  14324. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14325. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14326. break;
  14327. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14328. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14329. break;
  14330. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14331. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14332. break;
  14333. }
  14334. }
  14335. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14336. }
  14337. return true;
  14338. };
  14339. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14340. if (channel < 0 || !uniform) {
  14341. return;
  14342. }
  14343. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14344. this._textureUnits = new Int32Array(textures.length);
  14345. }
  14346. for (var i = 0; i < textures.length; i++) {
  14347. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14348. }
  14349. this._gl.uniform1iv(uniform, this._textureUnits);
  14350. for (var index = 0; index < textures.length; index++) {
  14351. this._setTexture(this._textureUnits[index], textures[index], true);
  14352. }
  14353. };
  14354. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14355. var internalTexture = texture.getInternalTexture();
  14356. if (!internalTexture) {
  14357. return;
  14358. }
  14359. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14360. var value = texture.anisotropicFilteringLevel;
  14361. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14362. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14363. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14364. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14365. }
  14366. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14367. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14368. internalTexture._cachedAnisotropicFilteringLevel = value;
  14369. }
  14370. };
  14371. Engine.prototype.readPixels = function (x, y, width, height) {
  14372. var data = new Uint8Array(height * width * 4);
  14373. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14374. return data;
  14375. };
  14376. /**
  14377. * Add an externaly attached data from its key.
  14378. * This method call will fail and return false, if such key already exists.
  14379. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14380. * @param key the unique key that identifies the data
  14381. * @param data the data object to associate to the key for this Engine instance
  14382. * @return true if no such key were already present and the data was added successfully, false otherwise
  14383. */
  14384. Engine.prototype.addExternalData = function (key, data) {
  14385. if (!this._externalData) {
  14386. this._externalData = new BABYLON.StringDictionary();
  14387. }
  14388. return this._externalData.add(key, data);
  14389. };
  14390. /**
  14391. * Get an externaly attached data from its key
  14392. * @param key the unique key that identifies the data
  14393. * @return the associated data, if present (can be null), or undefined if not present
  14394. */
  14395. Engine.prototype.getExternalData = function (key) {
  14396. if (!this._externalData) {
  14397. this._externalData = new BABYLON.StringDictionary();
  14398. }
  14399. return this._externalData.get(key);
  14400. };
  14401. /**
  14402. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14403. * @param key the unique key that identifies the data
  14404. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14405. * @return the associated data, can be null if the factory returned null.
  14406. */
  14407. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14408. if (!this._externalData) {
  14409. this._externalData = new BABYLON.StringDictionary();
  14410. }
  14411. return this._externalData.getOrAddWithFactory(key, factory);
  14412. };
  14413. /**
  14414. * Remove an externaly attached data from the Engine instance
  14415. * @param key the unique key that identifies the data
  14416. * @return true if the data was successfully removed, false if it doesn't exist
  14417. */
  14418. Engine.prototype.removeExternalData = function (key) {
  14419. if (!this._externalData) {
  14420. this._externalData = new BABYLON.StringDictionary();
  14421. }
  14422. return this._externalData.remove(key);
  14423. };
  14424. Engine.prototype.unbindAllAttributes = function () {
  14425. if (this._mustWipeVertexAttributes) {
  14426. this._mustWipeVertexAttributes = false;
  14427. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  14428. this._gl.disableVertexAttribArray(i);
  14429. this._vertexAttribArraysEnabled[i] = false;
  14430. this._currentBufferPointers[i].active = false;
  14431. }
  14432. return;
  14433. }
  14434. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  14435. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  14436. continue;
  14437. }
  14438. this._gl.disableVertexAttribArray(i);
  14439. this._vertexAttribArraysEnabled[i] = false;
  14440. this._currentBufferPointers[i].active = false;
  14441. }
  14442. };
  14443. Engine.prototype.releaseEffects = function () {
  14444. for (var name in this._compiledEffects) {
  14445. this._deleteProgram(this._compiledEffects[name]._program);
  14446. }
  14447. this._compiledEffects = {};
  14448. };
  14449. // Dispose
  14450. Engine.prototype.dispose = function () {
  14451. this.hideLoadingUI();
  14452. this.stopRenderLoop();
  14453. // Release postProcesses
  14454. while (this.postProcesses.length) {
  14455. this.postProcesses[0].dispose();
  14456. }
  14457. // Empty texture
  14458. if (this._emptyTexture) {
  14459. this._releaseTexture(this._emptyTexture);
  14460. this._emptyTexture = null;
  14461. }
  14462. if (this._emptyCubeTexture) {
  14463. this._releaseTexture(this._emptyCubeTexture);
  14464. this._emptyCubeTexture = null;
  14465. }
  14466. // Rescale PP
  14467. if (this._rescalePostProcess) {
  14468. this._rescalePostProcess.dispose();
  14469. }
  14470. // Release scenes
  14471. while (this.scenes.length) {
  14472. this.scenes[0].dispose();
  14473. }
  14474. // Release audio engine
  14475. if (Engine.audioEngine) {
  14476. Engine.audioEngine.dispose();
  14477. }
  14478. // Release effects
  14479. this.releaseEffects();
  14480. // Unbind
  14481. this.unbindAllAttributes();
  14482. if (this._dummyFramebuffer) {
  14483. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  14484. }
  14485. //WebVR
  14486. this.disableVR();
  14487. // Events
  14488. if (BABYLON.Tools.IsWindowObjectExist()) {
  14489. window.removeEventListener("blur", this._onBlur);
  14490. window.removeEventListener("focus", this._onFocus);
  14491. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  14492. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  14493. if (this._renderingCanvas) {
  14494. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  14495. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  14496. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  14497. if (!this._doNotHandleContextLost) {
  14498. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  14499. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  14500. }
  14501. }
  14502. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  14503. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  14504. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  14505. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  14506. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  14507. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  14508. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  14509. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  14510. if (this._onVrDisplayConnect) {
  14511. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  14512. if (this._onVrDisplayDisconnect) {
  14513. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  14514. }
  14515. if (this._onVrDisplayPresentChange) {
  14516. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  14517. }
  14518. this._onVrDisplayConnect = null;
  14519. this._onVrDisplayDisconnect = null;
  14520. }
  14521. }
  14522. // Remove from Instances
  14523. var index = Engine.Instances.indexOf(this);
  14524. if (index >= 0) {
  14525. Engine.Instances.splice(index, 1);
  14526. }
  14527. this._workingCanvas = null;
  14528. this._workingContext = null;
  14529. this._currentBufferPointers = [];
  14530. this._renderingCanvas = null;
  14531. this._currentProgram = null;
  14532. this.onResizeObservable.clear();
  14533. this.onCanvasBlurObservable.clear();
  14534. this.onCanvasFocusObservable.clear();
  14535. this.onCanvasPointerOutObservable.clear();
  14536. this.onBeginFrameObservable.clear();
  14537. this.onEndFrameObservable.clear();
  14538. BABYLON.Effect.ResetCache();
  14539. // Abort active requests
  14540. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  14541. var request = _a[_i];
  14542. request.abort();
  14543. }
  14544. };
  14545. // Loading screen
  14546. Engine.prototype.displayLoadingUI = function () {
  14547. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14548. return;
  14549. }
  14550. var loadingScreen = this.loadingScreen;
  14551. if (loadingScreen) {
  14552. loadingScreen.displayLoadingUI();
  14553. }
  14554. };
  14555. Engine.prototype.hideLoadingUI = function () {
  14556. if (!BABYLON.Tools.IsWindowObjectExist()) {
  14557. return;
  14558. }
  14559. var loadingScreen = this.loadingScreen;
  14560. if (loadingScreen) {
  14561. loadingScreen.hideLoadingUI();
  14562. }
  14563. };
  14564. Object.defineProperty(Engine.prototype, "loadingScreen", {
  14565. get: function () {
  14566. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  14567. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  14568. return this._loadingScreen;
  14569. },
  14570. set: function (loadingScreen) {
  14571. this._loadingScreen = loadingScreen;
  14572. },
  14573. enumerable: true,
  14574. configurable: true
  14575. });
  14576. Object.defineProperty(Engine.prototype, "loadingUIText", {
  14577. set: function (text) {
  14578. this.loadingScreen.loadingUIText = text;
  14579. },
  14580. enumerable: true,
  14581. configurable: true
  14582. });
  14583. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  14584. set: function (color) {
  14585. this.loadingScreen.loadingUIBackgroundColor = color;
  14586. },
  14587. enumerable: true,
  14588. configurable: true
  14589. });
  14590. Engine.prototype.attachContextLostEvent = function (callback) {
  14591. if (this._renderingCanvas) {
  14592. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  14593. }
  14594. };
  14595. Engine.prototype.attachContextRestoredEvent = function (callback) {
  14596. if (this._renderingCanvas) {
  14597. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  14598. }
  14599. };
  14600. Engine.prototype.getVertexShaderSource = function (program) {
  14601. var shaders = this._gl.getAttachedShaders(program);
  14602. if (!shaders) {
  14603. return null;
  14604. }
  14605. return this._gl.getShaderSource(shaders[0]);
  14606. };
  14607. Engine.prototype.getFragmentShaderSource = function (program) {
  14608. var shaders = this._gl.getAttachedShaders(program);
  14609. if (!shaders) {
  14610. return null;
  14611. }
  14612. return this._gl.getShaderSource(shaders[1]);
  14613. };
  14614. Engine.prototype.getError = function () {
  14615. return this._gl.getError();
  14616. };
  14617. // FPS
  14618. Engine.prototype.getFps = function () {
  14619. return this._fps;
  14620. };
  14621. Engine.prototype.getDeltaTime = function () {
  14622. return this._deltaTime;
  14623. };
  14624. Engine.prototype._measureFps = function () {
  14625. this._performanceMonitor.sampleFrame();
  14626. this._fps = this._performanceMonitor.averageFPS;
  14627. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  14628. };
  14629. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  14630. if (faceIndex === void 0) { faceIndex = -1; }
  14631. var gl = this._gl;
  14632. if (!this._dummyFramebuffer) {
  14633. var dummy = gl.createFramebuffer();
  14634. if (!dummy) {
  14635. throw new Error("Unable to create dummy framebuffer");
  14636. }
  14637. this._dummyFramebuffer = dummy;
  14638. }
  14639. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  14640. if (faceIndex > -1) {
  14641. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  14642. }
  14643. else {
  14644. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  14645. }
  14646. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  14647. var buffer;
  14648. switch (readType) {
  14649. case gl.UNSIGNED_BYTE:
  14650. buffer = new Uint8Array(4 * width * height);
  14651. readType = gl.UNSIGNED_BYTE;
  14652. break;
  14653. default:
  14654. buffer = new Float32Array(4 * width * height);
  14655. readType = gl.FLOAT;
  14656. break;
  14657. }
  14658. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  14659. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  14660. return buffer;
  14661. };
  14662. Engine.prototype._canRenderToFloatFramebuffer = function () {
  14663. if (this._webGLVersion > 1) {
  14664. return this._caps.colorBufferFloat;
  14665. }
  14666. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  14667. };
  14668. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  14669. if (this._webGLVersion > 1) {
  14670. return this._caps.colorBufferFloat;
  14671. }
  14672. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  14673. };
  14674. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  14675. Engine.prototype._canRenderToFramebuffer = function (type) {
  14676. var gl = this._gl;
  14677. //clear existing errors
  14678. while (gl.getError() !== gl.NO_ERROR) { }
  14679. var successful = true;
  14680. var texture = gl.createTexture();
  14681. gl.bindTexture(gl.TEXTURE_2D, texture);
  14682. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  14683. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14684. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14685. var fb = gl.createFramebuffer();
  14686. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  14687. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  14688. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  14689. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  14690. successful = successful && (gl.getError() === gl.NO_ERROR);
  14691. //try render by clearing frame buffer's color buffer
  14692. if (successful) {
  14693. gl.clear(gl.COLOR_BUFFER_BIT);
  14694. successful = successful && (gl.getError() === gl.NO_ERROR);
  14695. }
  14696. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  14697. if (successful) {
  14698. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  14699. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14700. var readFormat = gl.RGBA;
  14701. var readType = gl.UNSIGNED_BYTE;
  14702. var buffer = new Uint8Array(4);
  14703. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  14704. successful = successful && (gl.getError() === gl.NO_ERROR);
  14705. }
  14706. //clean up
  14707. gl.deleteTexture(texture);
  14708. gl.deleteFramebuffer(fb);
  14709. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14710. //clear accumulated errors
  14711. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  14712. return successful;
  14713. };
  14714. Engine.prototype._getWebGLTextureType = function (type) {
  14715. if (type === Engine.TEXTURETYPE_FLOAT) {
  14716. return this._gl.FLOAT;
  14717. }
  14718. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14719. // Add Half Float Constant.
  14720. return this._gl.HALF_FLOAT_OES;
  14721. }
  14722. return this._gl.UNSIGNED_BYTE;
  14723. };
  14724. ;
  14725. /** @ignore */
  14726. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  14727. if (this._webGLVersion === 1) {
  14728. return this._gl.RGBA;
  14729. }
  14730. if (type === Engine.TEXTURETYPE_FLOAT) {
  14731. if (format) {
  14732. switch (format) {
  14733. case Engine.TEXTUREFORMAT_R32F:
  14734. return this._gl.R32F;
  14735. case Engine.TEXTUREFORMAT_RG32F:
  14736. return this._gl.RG32F;
  14737. case Engine.TEXTUREFORMAT_RGB32F:
  14738. return this._gl.RGB32F;
  14739. }
  14740. }
  14741. return this._gl.RGBA32F;
  14742. }
  14743. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14744. return this._gl.RGBA16F;
  14745. }
  14746. return this._gl.RGBA;
  14747. };
  14748. ;
  14749. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  14750. if (type === Engine.TEXTURETYPE_FLOAT) {
  14751. return this._gl.RGBA32F;
  14752. }
  14753. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  14754. return this._gl.RGBA16F;
  14755. }
  14756. return this._gl.RGBA8;
  14757. };
  14758. ;
  14759. Engine.prototype.createQuery = function () {
  14760. return this._gl.createQuery();
  14761. };
  14762. Engine.prototype.deleteQuery = function (query) {
  14763. this._gl.deleteQuery(query);
  14764. return this;
  14765. };
  14766. Engine.prototype.isQueryResultAvailable = function (query) {
  14767. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  14768. };
  14769. Engine.prototype.getQueryResult = function (query) {
  14770. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  14771. };
  14772. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  14773. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14774. this._gl.beginQuery(glAlgorithm, query);
  14775. return this;
  14776. };
  14777. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  14778. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  14779. this._gl.endQuery(glAlgorithm);
  14780. return this;
  14781. };
  14782. /* Time queries */
  14783. Engine.prototype._createTimeQuery = function () {
  14784. var timerQuery = this._caps.timerQuery;
  14785. if (timerQuery.createQueryEXT) {
  14786. return timerQuery.createQueryEXT();
  14787. }
  14788. return this.createQuery();
  14789. };
  14790. Engine.prototype._deleteTimeQuery = function (query) {
  14791. var timerQuery = this._caps.timerQuery;
  14792. if (timerQuery.deleteQueryEXT) {
  14793. timerQuery.deleteQueryEXT(query);
  14794. return;
  14795. }
  14796. this.deleteQuery(query);
  14797. };
  14798. Engine.prototype._getTimeQueryResult = function (query) {
  14799. var timerQuery = this._caps.timerQuery;
  14800. if (timerQuery.getQueryObjectEXT) {
  14801. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  14802. }
  14803. return this.getQueryResult(query);
  14804. };
  14805. Engine.prototype._getTimeQueryAvailability = function (query) {
  14806. var timerQuery = this._caps.timerQuery;
  14807. if (timerQuery.getQueryObjectEXT) {
  14808. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  14809. }
  14810. return this.isQueryResultAvailable(query);
  14811. };
  14812. Engine.prototype.startTimeQuery = function () {
  14813. var timerQuery = this._caps.timerQuery;
  14814. if (!timerQuery) {
  14815. return null;
  14816. }
  14817. var token = new BABYLON._TimeToken();
  14818. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14819. if (this._caps.canUseTimestampForTimerQuery) {
  14820. token._startTimeQuery = this._createTimeQuery();
  14821. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  14822. }
  14823. else {
  14824. if (this._currentNonTimestampToken) {
  14825. return this._currentNonTimestampToken;
  14826. }
  14827. token._timeElapsedQuery = this._createTimeQuery();
  14828. if (timerQuery.beginQueryEXT) {
  14829. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14830. }
  14831. else {
  14832. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  14833. }
  14834. this._currentNonTimestampToken = token;
  14835. }
  14836. return token;
  14837. };
  14838. Engine.prototype.endTimeQuery = function (token) {
  14839. var timerQuery = this._caps.timerQuery;
  14840. if (!timerQuery || !token) {
  14841. return -1;
  14842. }
  14843. if (this._caps.canUseTimestampForTimerQuery) {
  14844. if (!token._startTimeQuery) {
  14845. return -1;
  14846. }
  14847. if (!token._endTimeQuery) {
  14848. token._endTimeQuery = this._createTimeQuery();
  14849. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  14850. }
  14851. }
  14852. else if (!token._timeElapsedQueryEnded) {
  14853. if (!token._timeElapsedQuery) {
  14854. return -1;
  14855. }
  14856. if (timerQuery.endQueryEXT) {
  14857. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  14858. }
  14859. else {
  14860. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  14861. }
  14862. token._timeElapsedQueryEnded = true;
  14863. }
  14864. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  14865. var available = false;
  14866. if (token._endTimeQuery) {
  14867. available = this._getTimeQueryAvailability(token._endTimeQuery);
  14868. }
  14869. else if (token._timeElapsedQuery) {
  14870. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  14871. }
  14872. if (available && !disjoint) {
  14873. var result = 0;
  14874. if (this._caps.canUseTimestampForTimerQuery) {
  14875. if (!token._startTimeQuery || !token._endTimeQuery) {
  14876. return -1;
  14877. }
  14878. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  14879. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  14880. result = timeEnd - timeStart;
  14881. this._deleteTimeQuery(token._startTimeQuery);
  14882. this._deleteTimeQuery(token._endTimeQuery);
  14883. token._startTimeQuery = null;
  14884. token._endTimeQuery = null;
  14885. }
  14886. else {
  14887. if (!token._timeElapsedQuery) {
  14888. return -1;
  14889. }
  14890. result = this._getTimeQueryResult(token._timeElapsedQuery);
  14891. this._deleteTimeQuery(token._timeElapsedQuery);
  14892. token._timeElapsedQuery = null;
  14893. token._timeElapsedQueryEnded = false;
  14894. this._currentNonTimestampToken = null;
  14895. }
  14896. return result;
  14897. }
  14898. return -1;
  14899. };
  14900. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  14901. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  14902. };
  14903. // Transform feedback
  14904. Engine.prototype.createTransformFeedback = function () {
  14905. return this._gl.createTransformFeedback();
  14906. };
  14907. Engine.prototype.deleteTransformFeedback = function (value) {
  14908. this._gl.deleteTransformFeedback(value);
  14909. };
  14910. Engine.prototype.bindTransformFeedback = function (value) {
  14911. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  14912. };
  14913. Engine.prototype.beginTransformFeedback = function (usePoints) {
  14914. if (usePoints === void 0) { usePoints = true; }
  14915. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  14916. };
  14917. Engine.prototype.endTransformFeedback = function () {
  14918. this._gl.endTransformFeedback();
  14919. };
  14920. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  14921. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  14922. };
  14923. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  14924. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  14925. };
  14926. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  14927. var _this = this;
  14928. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  14929. this._activeRequests.push(request);
  14930. request.onCompleteObservable.add(function (request) {
  14931. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  14932. });
  14933. return request;
  14934. };
  14935. /** @ignore */
  14936. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  14937. var _this = this;
  14938. return new Promise(function (resolve, reject) {
  14939. _this._loadFile(url, function (data) {
  14940. resolve(data);
  14941. }, undefined, database, useArrayBuffer, function (request, exception) {
  14942. reject(exception);
  14943. });
  14944. });
  14945. };
  14946. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  14947. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  14948. var onload = function (data) {
  14949. loadedFiles[index] = data;
  14950. loadedFiles._internalCount++;
  14951. if (loadedFiles._internalCount === 6) {
  14952. onfinish(loadedFiles);
  14953. }
  14954. };
  14955. var onerror = function (request, exception) {
  14956. if (onErrorCallBack && request) {
  14957. onErrorCallBack(request.status + " " + request.statusText, exception);
  14958. }
  14959. };
  14960. this._loadFile(url, onload, undefined, undefined, true, onerror);
  14961. };
  14962. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  14963. if (onError === void 0) { onError = null; }
  14964. var loadedFiles = [];
  14965. loadedFiles._internalCount = 0;
  14966. for (var index = 0; index < 6; index++) {
  14967. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  14968. }
  14969. };
  14970. // Statics
  14971. Engine.isSupported = function () {
  14972. try {
  14973. var tempcanvas = document.createElement("canvas");
  14974. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  14975. return gl != null && !!window.WebGLRenderingContext;
  14976. }
  14977. catch (e) {
  14978. return false;
  14979. }
  14980. };
  14981. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  14982. Engine.ExceptionList = [
  14983. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  14984. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14985. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  14986. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14987. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  14988. ];
  14989. Engine.Instances = new Array();
  14990. // Const statics
  14991. Engine._ALPHA_DISABLE = 0;
  14992. Engine._ALPHA_ADD = 1;
  14993. Engine._ALPHA_COMBINE = 2;
  14994. Engine._ALPHA_SUBTRACT = 3;
  14995. Engine._ALPHA_MULTIPLY = 4;
  14996. Engine._ALPHA_MAXIMIZED = 5;
  14997. Engine._ALPHA_ONEONE = 6;
  14998. Engine._ALPHA_PREMULTIPLIED = 7;
  14999. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15000. Engine._ALPHA_INTERPOLATE = 9;
  15001. Engine._ALPHA_SCREENMODE = 10;
  15002. Engine._DELAYLOADSTATE_NONE = 0;
  15003. Engine._DELAYLOADSTATE_LOADED = 1;
  15004. Engine._DELAYLOADSTATE_LOADING = 2;
  15005. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15006. Engine._TEXTUREFORMAT_ALPHA = 0;
  15007. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15008. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15009. Engine._TEXTUREFORMAT_RGB = 4;
  15010. Engine._TEXTUREFORMAT_RGBA = 5;
  15011. Engine._TEXTUREFORMAT_R32F = 6;
  15012. Engine._TEXTUREFORMAT_RG32F = 7;
  15013. Engine._TEXTUREFORMAT_RGB32F = 8;
  15014. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15015. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15016. Engine._TEXTURETYPE_FLOAT = 1;
  15017. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15018. // Depht or Stencil test Constants.
  15019. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15020. 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.
  15021. 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.
  15022. 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.
  15023. 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.
  15024. 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.
  15025. 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.
  15026. 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.
  15027. // Stencil Actions Constants.
  15028. Engine._KEEP = 0x1E00;
  15029. Engine._REPLACE = 0x1E01;
  15030. Engine._INCR = 0x1E02;
  15031. Engine._DECR = 0x1E03;
  15032. Engine._INVERT = 0x150A;
  15033. Engine._INCR_WRAP = 0x8507;
  15034. Engine._DECR_WRAP = 0x8508;
  15035. // Texture rescaling mode
  15036. Engine._SCALEMODE_FLOOR = 1;
  15037. Engine._SCALEMODE_NEAREST = 2;
  15038. Engine._SCALEMODE_CEILING = 3;
  15039. // Updatable statics so stick with vars here
  15040. Engine.CollisionsEpsilon = 0.001;
  15041. Engine.CodeRepository = "src/";
  15042. Engine.ShadersRepository = "src/Shaders/";
  15043. return Engine;
  15044. }());
  15045. BABYLON.Engine = Engine;
  15046. })(BABYLON || (BABYLON = {}));
  15047. //# sourceMappingURL=babylon.engine.js.map
  15048. var BABYLON;
  15049. (function (BABYLON) {
  15050. /**
  15051. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15052. */
  15053. var Node = /** @class */ (function () {
  15054. /**
  15055. * Creates a new Node
  15056. * @param {string} name - the name and id to be given to this node
  15057. * @param {BABYLON.Scene} the scene this node will be added to
  15058. */
  15059. function Node(name, scene) {
  15060. if (scene === void 0) { scene = null; }
  15061. /**
  15062. * Gets or sets a string used to store user defined state for the node
  15063. */
  15064. this.state = "";
  15065. /**
  15066. * Gets or sets an object used to store user defined information for the node
  15067. */
  15068. this.metadata = null;
  15069. /**
  15070. * Gets or sets a boolean used to define if the node must be serialized
  15071. */
  15072. this.doNotSerialize = false;
  15073. /** @ignore */
  15074. this._isDisposed = false;
  15075. /**
  15076. * Gets a list of {BABYLON.Animation} associated with the node
  15077. */
  15078. this.animations = new Array();
  15079. this._ranges = {};
  15080. this._isEnabled = true;
  15081. this._isReady = true;
  15082. /** @ignore */
  15083. this._currentRenderId = -1;
  15084. this._parentRenderId = -1;
  15085. /**
  15086. * An event triggered when the mesh is disposed
  15087. * @type {BABYLON.Observable}
  15088. */
  15089. this.onDisposeObservable = new BABYLON.Observable();
  15090. // Behaviors
  15091. this._behaviors = new Array();
  15092. this.name = name;
  15093. this.id = name;
  15094. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15095. this.uniqueId = this._scene.getUniqueId();
  15096. this._initCache();
  15097. }
  15098. /**
  15099. * Gets a boolean indicating if the node has been disposed
  15100. * @returns true if the node was disposed
  15101. */
  15102. Node.prototype.isDisposed = function () {
  15103. return this._isDisposed;
  15104. };
  15105. Object.defineProperty(Node.prototype, "parent", {
  15106. get: function () {
  15107. return this._parentNode;
  15108. },
  15109. /**
  15110. * Gets or sets the parent of the node
  15111. */
  15112. set: function (parent) {
  15113. if (this._parentNode === parent) {
  15114. return;
  15115. }
  15116. // Remove self from list of children of parent
  15117. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15118. var index = this._parentNode._children.indexOf(this);
  15119. if (index !== -1) {
  15120. this._parentNode._children.splice(index, 1);
  15121. }
  15122. }
  15123. // Store new parent
  15124. this._parentNode = parent;
  15125. // Add as child to new parent
  15126. if (this._parentNode) {
  15127. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15128. this._parentNode._children = new Array();
  15129. }
  15130. this._parentNode._children.push(this);
  15131. }
  15132. },
  15133. enumerable: true,
  15134. configurable: true
  15135. });
  15136. /**
  15137. * Gets a string idenfifying the name of the class
  15138. * @returns "Node" string
  15139. */
  15140. Node.prototype.getClassName = function () {
  15141. return "Node";
  15142. };
  15143. Object.defineProperty(Node.prototype, "onDispose", {
  15144. /**
  15145. * Sets a callback that will be raised when the node will be disposed
  15146. */
  15147. set: function (callback) {
  15148. if (this._onDisposeObserver) {
  15149. this.onDisposeObservable.remove(this._onDisposeObserver);
  15150. }
  15151. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15152. },
  15153. enumerable: true,
  15154. configurable: true
  15155. });
  15156. /**
  15157. * Gets the scene of the node
  15158. * @returns a {BABYLON.Scene}
  15159. */
  15160. Node.prototype.getScene = function () {
  15161. return this._scene;
  15162. };
  15163. /**
  15164. * Gets the engine of the node
  15165. * @returns a {BABYLON.Engine}
  15166. */
  15167. Node.prototype.getEngine = function () {
  15168. return this._scene.getEngine();
  15169. };
  15170. /**
  15171. * Attach a behavior to the node
  15172. * @see http://doc.babylonjs.com/features/behaviour
  15173. * @param behavior defines the behavior to attach
  15174. * @returns the current Node
  15175. */
  15176. Node.prototype.addBehavior = function (behavior) {
  15177. var _this = this;
  15178. var index = this._behaviors.indexOf(behavior);
  15179. if (index !== -1) {
  15180. return this;
  15181. }
  15182. behavior.init();
  15183. if (this._scene.isLoading) {
  15184. // We defer the attach when the scene will be loaded
  15185. var observer = this._scene.onDataLoadedObservable.add(function () {
  15186. behavior.attach(_this);
  15187. setTimeout(function () {
  15188. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15189. _this._scene.onDataLoadedObservable.remove(observer);
  15190. }, 0);
  15191. });
  15192. }
  15193. else {
  15194. behavior.attach(this);
  15195. }
  15196. this._behaviors.push(behavior);
  15197. return this;
  15198. };
  15199. /**
  15200. * Remove an attached behavior
  15201. * @see http://doc.babylonjs.com/features/behaviour
  15202. * @param behavior defines the behavior to attach
  15203. * @returns the current Node
  15204. */
  15205. Node.prototype.removeBehavior = function (behavior) {
  15206. var index = this._behaviors.indexOf(behavior);
  15207. if (index === -1) {
  15208. return this;
  15209. }
  15210. this._behaviors[index].detach();
  15211. this._behaviors.splice(index, 1);
  15212. return this;
  15213. };
  15214. Object.defineProperty(Node.prototype, "behaviors", {
  15215. /**
  15216. * Gets the list of attached behaviors
  15217. * @see http://doc.babylonjs.com/features/behaviour
  15218. */
  15219. get: function () {
  15220. return this._behaviors;
  15221. },
  15222. enumerable: true,
  15223. configurable: true
  15224. });
  15225. /**
  15226. * Gets an attached behavior by name
  15227. * @param name defines the name of the behavior to look for
  15228. * @see http://doc.babylonjs.com/features/behaviour
  15229. * @returns null if behavior was not found else the requested behavior
  15230. */
  15231. Node.prototype.getBehaviorByName = function (name) {
  15232. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15233. var behavior = _a[_i];
  15234. if (behavior.name === name) {
  15235. return behavior;
  15236. }
  15237. }
  15238. return null;
  15239. };
  15240. /**
  15241. * Returns the world matrix of the node
  15242. * @returns a matrix containing the node's world matrix
  15243. */
  15244. Node.prototype.getWorldMatrix = function () {
  15245. return BABYLON.Matrix.Identity();
  15246. };
  15247. // override it in derived class if you add new variables to the cache
  15248. // and call the parent class method
  15249. /** @ignore */
  15250. Node.prototype._initCache = function () {
  15251. this._cache = {};
  15252. this._cache.parent = undefined;
  15253. };
  15254. /** @ignore */
  15255. Node.prototype.updateCache = function (force) {
  15256. if (!force && this.isSynchronized())
  15257. return;
  15258. this._cache.parent = this.parent;
  15259. this._updateCache();
  15260. };
  15261. // override it in derived class if you add new variables to the cache
  15262. // and call the parent class method if !ignoreParentClass
  15263. /** @ignore */
  15264. Node.prototype._updateCache = function (ignoreParentClass) {
  15265. };
  15266. // override it in derived class if you add new variables to the cache
  15267. /** @ignore */
  15268. Node.prototype._isSynchronized = function () {
  15269. return true;
  15270. };
  15271. /** @ignore */
  15272. Node.prototype._markSyncedWithParent = function () {
  15273. if (this.parent) {
  15274. this._parentRenderId = this.parent._currentRenderId;
  15275. }
  15276. };
  15277. /** @ignore */
  15278. Node.prototype.isSynchronizedWithParent = function () {
  15279. if (!this.parent) {
  15280. return true;
  15281. }
  15282. if (this._parentRenderId !== this.parent._currentRenderId) {
  15283. return false;
  15284. }
  15285. return this.parent.isSynchronized();
  15286. };
  15287. /** @ignore */
  15288. Node.prototype.isSynchronized = function (updateCache) {
  15289. var check = this.hasNewParent();
  15290. check = check || !this.isSynchronizedWithParent();
  15291. check = check || !this._isSynchronized();
  15292. if (updateCache)
  15293. this.updateCache(true);
  15294. return !check;
  15295. };
  15296. /** @ignore */
  15297. Node.prototype.hasNewParent = function (update) {
  15298. if (this._cache.parent === this.parent)
  15299. return false;
  15300. if (update)
  15301. this._cache.parent = this.parent;
  15302. return true;
  15303. };
  15304. /**
  15305. * Is this node ready to be used/rendered
  15306. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15307. * @return true if the node is ready
  15308. */
  15309. Node.prototype.isReady = function (completeCheck) {
  15310. if (completeCheck === void 0) { completeCheck = false; }
  15311. return this._isReady;
  15312. };
  15313. /**
  15314. * Is this node enabled?
  15315. * 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
  15316. * @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
  15317. * @return whether this node (and its parent) is enabled
  15318. * @see setEnabled
  15319. */
  15320. Node.prototype.isEnabled = function (checkAncestors) {
  15321. if (checkAncestors === void 0) { checkAncestors = true; }
  15322. if (checkAncestors === false) {
  15323. return this._isEnabled;
  15324. }
  15325. if (this._isEnabled === false) {
  15326. return false;
  15327. }
  15328. if (this.parent !== undefined && this.parent !== null) {
  15329. return this.parent.isEnabled(checkAncestors);
  15330. }
  15331. return true;
  15332. };
  15333. /**
  15334. * Set the enabled state of this node
  15335. * @param value defines the new enabled state
  15336. * @see isEnabled
  15337. */
  15338. Node.prototype.setEnabled = function (value) {
  15339. this._isEnabled = value;
  15340. };
  15341. /**
  15342. * Is this node a descendant of the given node?
  15343. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15344. * @param ancestor defines the parent node to inspect
  15345. * @see parent
  15346. * @returns a boolean indicating if this node is a descendant of the given node
  15347. */
  15348. Node.prototype.isDescendantOf = function (ancestor) {
  15349. if (this.parent) {
  15350. if (this.parent === ancestor) {
  15351. return true;
  15352. }
  15353. return this.parent.isDescendantOf(ancestor);
  15354. }
  15355. return false;
  15356. };
  15357. /** @ignore */
  15358. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15359. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15360. if (!this._children) {
  15361. return;
  15362. }
  15363. for (var index = 0; index < this._children.length; index++) {
  15364. var item = this._children[index];
  15365. if (!predicate || predicate(item)) {
  15366. results.push(item);
  15367. }
  15368. if (!directDescendantsOnly) {
  15369. item._getDescendants(results, false, predicate);
  15370. }
  15371. }
  15372. };
  15373. /**
  15374. * Will return all nodes that have this node as ascendant
  15375. * @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
  15376. * @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
  15377. * @return all children nodes of all types
  15378. */
  15379. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  15380. var results = new Array();
  15381. this._getDescendants(results, directDescendantsOnly, predicate);
  15382. return results;
  15383. };
  15384. /**
  15385. * Get all child-meshes of this node
  15386. * @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
  15387. * @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
  15388. * @returns an array of {BABYLON.AbstractMesh}
  15389. */
  15390. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  15391. var results = [];
  15392. this._getDescendants(results, directDescendantsOnly, function (node) {
  15393. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  15394. });
  15395. return results;
  15396. };
  15397. /**
  15398. * Get all child-transformNodes of this node
  15399. * @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
  15400. * @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
  15401. * @returns an array of {BABYLON.TransformNode}
  15402. */
  15403. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  15404. var results = [];
  15405. this._getDescendants(results, directDescendantsOnly, function (node) {
  15406. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  15407. });
  15408. return results;
  15409. };
  15410. /**
  15411. * Get all direct children of this node
  15412. * @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
  15413. * @returns an array of {BABYLON.Node}
  15414. */
  15415. Node.prototype.getChildren = function (predicate) {
  15416. return this.getDescendants(true, predicate);
  15417. };
  15418. /** @ignore */
  15419. Node.prototype._setReady = function (state) {
  15420. if (state === this._isReady) {
  15421. return;
  15422. }
  15423. if (!state) {
  15424. this._isReady = false;
  15425. return;
  15426. }
  15427. this._isReady = true;
  15428. if (this.onReady) {
  15429. this.onReady(this);
  15430. }
  15431. };
  15432. /**
  15433. * Get an animation by name
  15434. * @param name defines the name of the animation to look for
  15435. * @returns null if not found else the requested animation
  15436. */
  15437. Node.prototype.getAnimationByName = function (name) {
  15438. for (var i = 0; i < this.animations.length; i++) {
  15439. var animation = this.animations[i];
  15440. if (animation.name === name) {
  15441. return animation;
  15442. }
  15443. }
  15444. return null;
  15445. };
  15446. /**
  15447. * Creates an animation range for this node
  15448. * @param name defines the name of the range
  15449. * @param from defines the starting key
  15450. * @param to defines the end key
  15451. */
  15452. Node.prototype.createAnimationRange = function (name, from, to) {
  15453. // check name not already in use
  15454. if (!this._ranges[name]) {
  15455. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  15456. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15457. if (this.animations[i]) {
  15458. this.animations[i].createRange(name, from, to);
  15459. }
  15460. }
  15461. }
  15462. };
  15463. /**
  15464. * Delete a specific animation range
  15465. * @param name defines the name of the range to delete
  15466. * @param deleteFrames defines if animation frames from the range must be deleted as well
  15467. */
  15468. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  15469. if (deleteFrames === void 0) { deleteFrames = true; }
  15470. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  15471. if (this.animations[i]) {
  15472. this.animations[i].deleteRange(name, deleteFrames);
  15473. }
  15474. }
  15475. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  15476. };
  15477. /**
  15478. * Get an animation range by name
  15479. * @param name defines the name of the animation range to look for
  15480. * @returns null if not found else the requested animation range
  15481. */
  15482. Node.prototype.getAnimationRange = function (name) {
  15483. return this._ranges[name];
  15484. };
  15485. /**
  15486. * Will start the animation sequence
  15487. * @param name defines the range frames for animation sequence
  15488. * @param loop defines if the animation should loop (false by default)
  15489. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  15490. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  15491. * @returns the object created for this animation. If range does not exist, it will return null
  15492. */
  15493. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  15494. var range = this.getAnimationRange(name);
  15495. if (!range) {
  15496. return null;
  15497. }
  15498. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  15499. };
  15500. /**
  15501. * Serialize animation ranges into a JSON compatible object
  15502. * @returns serialization object
  15503. */
  15504. Node.prototype.serializeAnimationRanges = function () {
  15505. var serializationRanges = [];
  15506. for (var name in this._ranges) {
  15507. var localRange = this._ranges[name];
  15508. if (!localRange) {
  15509. continue;
  15510. }
  15511. var range = {};
  15512. range.name = name;
  15513. range.from = localRange.from;
  15514. range.to = localRange.to;
  15515. serializationRanges.push(range);
  15516. }
  15517. return serializationRanges;
  15518. };
  15519. /**
  15520. * Computes the world matrix of the node
  15521. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  15522. * @returns the world matrix
  15523. */
  15524. Node.prototype.computeWorldMatrix = function (force) {
  15525. return BABYLON.Matrix.Identity();
  15526. };
  15527. /**
  15528. * Releases all associated resources
  15529. */
  15530. Node.prototype.dispose = function () {
  15531. this.parent = null;
  15532. // Callback
  15533. this.onDisposeObservable.notifyObservers(this);
  15534. this.onDisposeObservable.clear();
  15535. // Behaviors
  15536. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15537. var behavior = _a[_i];
  15538. behavior.detach();
  15539. }
  15540. this._behaviors = [];
  15541. this._isDisposed = true;
  15542. };
  15543. /**
  15544. * Parse animation range data from a serialization object and store them into a given node
  15545. * @param node defines where to store the animation ranges
  15546. * @param parsedNode defines the serialization object to read data from
  15547. * @param scene defines the hosting scene
  15548. */
  15549. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  15550. if (parsedNode.ranges) {
  15551. for (var index = 0; index < parsedNode.ranges.length; index++) {
  15552. var data = parsedNode.ranges[index];
  15553. node.createAnimationRange(data.name, data.from, data.to);
  15554. }
  15555. }
  15556. };
  15557. __decorate([
  15558. BABYLON.serialize()
  15559. ], Node.prototype, "name", void 0);
  15560. __decorate([
  15561. BABYLON.serialize()
  15562. ], Node.prototype, "id", void 0);
  15563. __decorate([
  15564. BABYLON.serialize()
  15565. ], Node.prototype, "uniqueId", void 0);
  15566. __decorate([
  15567. BABYLON.serialize()
  15568. ], Node.prototype, "state", void 0);
  15569. __decorate([
  15570. BABYLON.serialize()
  15571. ], Node.prototype, "metadata", void 0);
  15572. return Node;
  15573. }());
  15574. BABYLON.Node = Node;
  15575. })(BABYLON || (BABYLON = {}));
  15576. //# sourceMappingURL=babylon.node.js.map
  15577. var BABYLON;
  15578. (function (BABYLON) {
  15579. var BoundingSphere = /** @class */ (function () {
  15580. function BoundingSphere(minimum, maximum) {
  15581. this.minimum = minimum;
  15582. this.maximum = maximum;
  15583. this._tempRadiusVector = BABYLON.Vector3.Zero();
  15584. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  15585. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  15586. this.radius = distance * 0.5;
  15587. this.centerWorld = BABYLON.Vector3.Zero();
  15588. this._update(BABYLON.Matrix.Identity());
  15589. }
  15590. // Methods
  15591. BoundingSphere.prototype._update = function (world) {
  15592. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  15593. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  15594. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  15595. };
  15596. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  15597. for (var i = 0; i < 6; i++) {
  15598. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  15599. return false;
  15600. }
  15601. return true;
  15602. };
  15603. BoundingSphere.prototype.intersectsPoint = function (point) {
  15604. var x = this.centerWorld.x - point.x;
  15605. var y = this.centerWorld.y - point.y;
  15606. var z = this.centerWorld.z - point.z;
  15607. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15608. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  15609. return false;
  15610. return true;
  15611. };
  15612. // Statics
  15613. BoundingSphere.Intersects = function (sphere0, sphere1) {
  15614. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  15615. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  15616. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  15617. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  15618. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  15619. return false;
  15620. return true;
  15621. };
  15622. return BoundingSphere;
  15623. }());
  15624. BABYLON.BoundingSphere = BoundingSphere;
  15625. })(BABYLON || (BABYLON = {}));
  15626. //# sourceMappingURL=babylon.boundingSphere.js.map
  15627. var BABYLON;
  15628. (function (BABYLON) {
  15629. var BoundingBox = /** @class */ (function () {
  15630. function BoundingBox(minimum, maximum) {
  15631. this.minimum = minimum;
  15632. this.maximum = maximum;
  15633. this.vectors = new Array();
  15634. this.vectorsWorld = new Array();
  15635. // Bounding vectors
  15636. this.vectors.push(this.minimum.clone());
  15637. this.vectors.push(this.maximum.clone());
  15638. this.vectors.push(this.minimum.clone());
  15639. this.vectors[2].x = this.maximum.x;
  15640. this.vectors.push(this.minimum.clone());
  15641. this.vectors[3].y = this.maximum.y;
  15642. this.vectors.push(this.minimum.clone());
  15643. this.vectors[4].z = this.maximum.z;
  15644. this.vectors.push(this.maximum.clone());
  15645. this.vectors[5].z = this.minimum.z;
  15646. this.vectors.push(this.maximum.clone());
  15647. this.vectors[6].x = this.minimum.x;
  15648. this.vectors.push(this.maximum.clone());
  15649. this.vectors[7].y = this.minimum.y;
  15650. // OBB
  15651. this.center = this.maximum.add(this.minimum).scale(0.5);
  15652. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  15653. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  15654. // World
  15655. for (var index = 0; index < this.vectors.length; index++) {
  15656. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  15657. }
  15658. this.minimumWorld = BABYLON.Vector3.Zero();
  15659. this.maximumWorld = BABYLON.Vector3.Zero();
  15660. this.centerWorld = BABYLON.Vector3.Zero();
  15661. this.extendSizeWorld = BABYLON.Vector3.Zero();
  15662. this._update(BABYLON.Matrix.Identity());
  15663. }
  15664. // Methods
  15665. BoundingBox.prototype.getWorldMatrix = function () {
  15666. return this._worldMatrix;
  15667. };
  15668. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  15669. this._worldMatrix.copyFrom(matrix);
  15670. return this;
  15671. };
  15672. BoundingBox.prototype._update = function (world) {
  15673. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  15674. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  15675. for (var index = 0; index < this.vectors.length; index++) {
  15676. var v = this.vectorsWorld[index];
  15677. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  15678. if (v.x < this.minimumWorld.x)
  15679. this.minimumWorld.x = v.x;
  15680. if (v.y < this.minimumWorld.y)
  15681. this.minimumWorld.y = v.y;
  15682. if (v.z < this.minimumWorld.z)
  15683. this.minimumWorld.z = v.z;
  15684. if (v.x > this.maximumWorld.x)
  15685. this.maximumWorld.x = v.x;
  15686. if (v.y > this.maximumWorld.y)
  15687. this.maximumWorld.y = v.y;
  15688. if (v.z > this.maximumWorld.z)
  15689. this.maximumWorld.z = v.z;
  15690. }
  15691. // Extend
  15692. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  15693. this.extendSizeWorld.scaleInPlace(0.5);
  15694. // OBB
  15695. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  15696. this.centerWorld.scaleInPlace(0.5);
  15697. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  15698. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  15699. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  15700. this._worldMatrix = world;
  15701. };
  15702. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  15703. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  15704. };
  15705. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15706. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  15707. };
  15708. BoundingBox.prototype.intersectsPoint = function (point) {
  15709. var delta = -BABYLON.Epsilon;
  15710. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  15711. return false;
  15712. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  15713. return false;
  15714. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  15715. return false;
  15716. return true;
  15717. };
  15718. BoundingBox.prototype.intersectsSphere = function (sphere) {
  15719. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  15720. };
  15721. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  15722. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  15723. return false;
  15724. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  15725. return false;
  15726. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  15727. return false;
  15728. return true;
  15729. };
  15730. // Statics
  15731. BoundingBox.Intersects = function (box0, box1) {
  15732. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  15733. return false;
  15734. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  15735. return false;
  15736. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  15737. return false;
  15738. return true;
  15739. };
  15740. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  15741. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  15742. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  15743. return (num <= (sphereRadius * sphereRadius));
  15744. };
  15745. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  15746. for (var p = 0; p < 6; p++) {
  15747. for (var i = 0; i < 8; i++) {
  15748. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15749. return false;
  15750. }
  15751. }
  15752. }
  15753. return true;
  15754. };
  15755. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  15756. for (var p = 0; p < 6; p++) {
  15757. var inCount = 8;
  15758. for (var i = 0; i < 8; i++) {
  15759. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  15760. --inCount;
  15761. }
  15762. else {
  15763. break;
  15764. }
  15765. }
  15766. if (inCount === 0)
  15767. return false;
  15768. }
  15769. return true;
  15770. };
  15771. return BoundingBox;
  15772. }());
  15773. BABYLON.BoundingBox = BoundingBox;
  15774. })(BABYLON || (BABYLON = {}));
  15775. //# sourceMappingURL=babylon.boundingBox.js.map
  15776. var BABYLON;
  15777. (function (BABYLON) {
  15778. var computeBoxExtents = function (axis, box) {
  15779. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  15780. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  15781. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  15782. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  15783. var r = r0 + r1 + r2;
  15784. return {
  15785. min: p - r,
  15786. max: p + r
  15787. };
  15788. };
  15789. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  15790. var axisOverlap = function (axis, box0, box1) {
  15791. var result0 = computeBoxExtents(axis, box0);
  15792. var result1 = computeBoxExtents(axis, box1);
  15793. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  15794. };
  15795. var BoundingInfo = /** @class */ (function () {
  15796. function BoundingInfo(minimum, maximum) {
  15797. this.minimum = minimum;
  15798. this.maximum = maximum;
  15799. this._isLocked = false;
  15800. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  15801. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  15802. }
  15803. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  15804. get: function () {
  15805. return this._isLocked;
  15806. },
  15807. set: function (value) {
  15808. this._isLocked = value;
  15809. },
  15810. enumerable: true,
  15811. configurable: true
  15812. });
  15813. // Methods
  15814. BoundingInfo.prototype.update = function (world) {
  15815. if (this._isLocked) {
  15816. return;
  15817. }
  15818. this.boundingBox._update(world);
  15819. this.boundingSphere._update(world);
  15820. };
  15821. /**
  15822. * Recreate the bounding info to be centered around a specific point given a specific extend.
  15823. * @param center New center of the bounding info
  15824. * @param extend New extend of the bounding info
  15825. */
  15826. BoundingInfo.prototype.centerOn = function (center, extend) {
  15827. this.minimum = center.subtract(extend);
  15828. this.maximum = center.add(extend);
  15829. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  15830. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  15831. return this;
  15832. };
  15833. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  15834. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  15835. return false;
  15836. return this.boundingBox.isInFrustum(frustumPlanes);
  15837. };
  15838. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  15839. /**
  15840. * Gets the world distance between the min and max points of the bounding box
  15841. */
  15842. get: function () {
  15843. var boundingBox = this.boundingBox;
  15844. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  15845. return size.length();
  15846. },
  15847. enumerable: true,
  15848. configurable: true
  15849. });
  15850. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  15851. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  15852. };
  15853. BoundingInfo.prototype._checkCollision = function (collider) {
  15854. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  15855. };
  15856. BoundingInfo.prototype.intersectsPoint = function (point) {
  15857. if (!this.boundingSphere.centerWorld) {
  15858. return false;
  15859. }
  15860. if (!this.boundingSphere.intersectsPoint(point)) {
  15861. return false;
  15862. }
  15863. if (!this.boundingBox.intersectsPoint(point)) {
  15864. return false;
  15865. }
  15866. return true;
  15867. };
  15868. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  15869. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  15870. return false;
  15871. }
  15872. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  15873. return false;
  15874. }
  15875. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  15876. return false;
  15877. }
  15878. if (!precise) {
  15879. return true;
  15880. }
  15881. var box0 = this.boundingBox;
  15882. var box1 = boundingInfo.boundingBox;
  15883. if (!axisOverlap(box0.directions[0], box0, box1))
  15884. return false;
  15885. if (!axisOverlap(box0.directions[1], box0, box1))
  15886. return false;
  15887. if (!axisOverlap(box0.directions[2], box0, box1))
  15888. return false;
  15889. if (!axisOverlap(box1.directions[0], box0, box1))
  15890. return false;
  15891. if (!axisOverlap(box1.directions[1], box0, box1))
  15892. return false;
  15893. if (!axisOverlap(box1.directions[2], box0, box1))
  15894. return false;
  15895. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  15896. return false;
  15897. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  15898. return false;
  15899. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  15900. return false;
  15901. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  15902. return false;
  15903. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  15904. return false;
  15905. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  15906. return false;
  15907. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  15908. return false;
  15909. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  15910. return false;
  15911. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  15912. return false;
  15913. return true;
  15914. };
  15915. return BoundingInfo;
  15916. }());
  15917. BABYLON.BoundingInfo = BoundingInfo;
  15918. })(BABYLON || (BABYLON = {}));
  15919. //# sourceMappingURL=babylon.boundingInfo.js.map
  15920. var BABYLON;
  15921. (function (BABYLON) {
  15922. var TransformNode = /** @class */ (function (_super) {
  15923. __extends(TransformNode, _super);
  15924. function TransformNode(name, scene, isPure) {
  15925. if (scene === void 0) { scene = null; }
  15926. if (isPure === void 0) { isPure = true; }
  15927. var _this = _super.call(this, name, scene) || this;
  15928. // Properties
  15929. _this._rotation = BABYLON.Vector3.Zero();
  15930. _this._scaling = BABYLON.Vector3.One();
  15931. _this._isDirty = false;
  15932. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  15933. _this.scalingDeterminant = 1;
  15934. _this.infiniteDistance = false;
  15935. _this.position = BABYLON.Vector3.Zero();
  15936. _this._localWorld = BABYLON.Matrix.Zero();
  15937. _this._worldMatrix = BABYLON.Matrix.Zero();
  15938. _this._worldMatrixDeterminant = 0;
  15939. _this._absolutePosition = BABYLON.Vector3.Zero();
  15940. _this._pivotMatrix = BABYLON.Matrix.Identity();
  15941. _this._postMultiplyPivotMatrix = false;
  15942. _this._isWorldMatrixFrozen = false;
  15943. /**
  15944. * An event triggered after the world matrix is updated
  15945. * @type {BABYLON.Observable}
  15946. */
  15947. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  15948. _this._nonUniformScaling = false;
  15949. if (isPure) {
  15950. _this.getScene().addTransformNode(_this);
  15951. }
  15952. return _this;
  15953. }
  15954. Object.defineProperty(TransformNode.prototype, "rotation", {
  15955. /**
  15956. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  15957. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  15958. * Default : (0.0, 0.0, 0.0)
  15959. */
  15960. get: function () {
  15961. return this._rotation;
  15962. },
  15963. set: function (newRotation) {
  15964. this._rotation = newRotation;
  15965. },
  15966. enumerable: true,
  15967. configurable: true
  15968. });
  15969. Object.defineProperty(TransformNode.prototype, "scaling", {
  15970. /**
  15971. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15972. * Default : (1.0, 1.0, 1.0)
  15973. */
  15974. get: function () {
  15975. return this._scaling;
  15976. },
  15977. /**
  15978. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  15979. * Default : (1.0, 1.0, 1.0)
  15980. */
  15981. set: function (newScaling) {
  15982. this._scaling = newScaling;
  15983. },
  15984. enumerable: true,
  15985. configurable: true
  15986. });
  15987. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  15988. /**
  15989. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  15990. * It's null by default.
  15991. * 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)
  15992. */
  15993. get: function () {
  15994. return this._rotationQuaternion;
  15995. },
  15996. set: function (quaternion) {
  15997. this._rotationQuaternion = quaternion;
  15998. //reset the rotation vector.
  15999. if (quaternion && this.rotation.length()) {
  16000. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16001. }
  16002. },
  16003. enumerable: true,
  16004. configurable: true
  16005. });
  16006. /**
  16007. * Returns the latest update of the World matrix
  16008. * Returns a Matrix.
  16009. */
  16010. TransformNode.prototype.getWorldMatrix = function () {
  16011. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16012. this.computeWorldMatrix();
  16013. }
  16014. return this._worldMatrix;
  16015. };
  16016. /**
  16017. * Returns the latest update of the World matrix determinant.
  16018. */
  16019. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16020. return this._worldMatrixDeterminant;
  16021. };
  16022. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16023. /**
  16024. * Returns directly the latest state of the mesh World matrix.
  16025. * A Matrix is returned.
  16026. */
  16027. get: function () {
  16028. return this._worldMatrix;
  16029. },
  16030. enumerable: true,
  16031. configurable: true
  16032. });
  16033. /**
  16034. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16035. * Returns the AbstractMesh.
  16036. */
  16037. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16038. this._poseMatrix.copyFrom(matrix);
  16039. return this;
  16040. };
  16041. /**
  16042. * Returns the mesh Pose matrix.
  16043. * Returned object : Matrix
  16044. */
  16045. TransformNode.prototype.getPoseMatrix = function () {
  16046. return this._poseMatrix;
  16047. };
  16048. TransformNode.prototype._isSynchronized = function () {
  16049. if (this._isDirty) {
  16050. return false;
  16051. }
  16052. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16053. return false;
  16054. if (this._cache.pivotMatrixUpdated) {
  16055. return false;
  16056. }
  16057. if (this.infiniteDistance) {
  16058. return false;
  16059. }
  16060. if (!this._cache.position.equals(this.position))
  16061. return false;
  16062. if (this.rotationQuaternion) {
  16063. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16064. return false;
  16065. }
  16066. if (!this._cache.rotation.equals(this.rotation))
  16067. return false;
  16068. if (!this._cache.scaling.equals(this.scaling))
  16069. return false;
  16070. return true;
  16071. };
  16072. TransformNode.prototype._initCache = function () {
  16073. _super.prototype._initCache.call(this);
  16074. this._cache.localMatrixUpdated = false;
  16075. this._cache.position = BABYLON.Vector3.Zero();
  16076. this._cache.scaling = BABYLON.Vector3.Zero();
  16077. this._cache.rotation = BABYLON.Vector3.Zero();
  16078. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16079. this._cache.billboardMode = -1;
  16080. };
  16081. TransformNode.prototype.markAsDirty = function (property) {
  16082. if (property === "rotation") {
  16083. this.rotationQuaternion = null;
  16084. }
  16085. this._currentRenderId = Number.MAX_VALUE;
  16086. this._isDirty = true;
  16087. return this;
  16088. };
  16089. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16090. /**
  16091. * Returns the current mesh absolute position.
  16092. * Retuns a Vector3.
  16093. */
  16094. get: function () {
  16095. return this._absolutePosition;
  16096. },
  16097. enumerable: true,
  16098. configurable: true
  16099. });
  16100. /**
  16101. * Sets a new matrix to apply before all other transformation
  16102. * @param matrix defines the transform matrix
  16103. * @returns the current TransformNode
  16104. */
  16105. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16106. return this.setPivotMatrix(matrix, false);
  16107. };
  16108. /**
  16109. * Sets a new pivot matrix to the current node
  16110. * @param matrix defines the new pivot matrix to use
  16111. * @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
  16112. * @returns the current TransformNode
  16113. */
  16114. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16115. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16116. this._pivotMatrix = matrix.clone();
  16117. this._cache.pivotMatrixUpdated = true;
  16118. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16119. if (this._postMultiplyPivotMatrix) {
  16120. if (!this._pivotMatrixInverse) {
  16121. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16122. }
  16123. else {
  16124. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16125. }
  16126. }
  16127. return this;
  16128. };
  16129. /**
  16130. * Returns the mesh pivot matrix.
  16131. * Default : Identity.
  16132. * A Matrix is returned.
  16133. */
  16134. TransformNode.prototype.getPivotMatrix = function () {
  16135. return this._pivotMatrix;
  16136. };
  16137. /**
  16138. * Prevents the World matrix to be computed any longer.
  16139. * Returns the AbstractMesh.
  16140. */
  16141. TransformNode.prototype.freezeWorldMatrix = function () {
  16142. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16143. this.computeWorldMatrix(true);
  16144. this._isWorldMatrixFrozen = true;
  16145. return this;
  16146. };
  16147. /**
  16148. * Allows back the World matrix computation.
  16149. * Returns the AbstractMesh.
  16150. */
  16151. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16152. this._isWorldMatrixFrozen = false;
  16153. this.computeWorldMatrix(true);
  16154. return this;
  16155. };
  16156. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16157. /**
  16158. * True if the World matrix has been frozen.
  16159. * Returns a boolean.
  16160. */
  16161. get: function () {
  16162. return this._isWorldMatrixFrozen;
  16163. },
  16164. enumerable: true,
  16165. configurable: true
  16166. });
  16167. /**
  16168. * Retuns the mesh absolute position in the World.
  16169. * Returns a Vector3.
  16170. */
  16171. TransformNode.prototype.getAbsolutePosition = function () {
  16172. this.computeWorldMatrix();
  16173. return this._absolutePosition;
  16174. };
  16175. /**
  16176. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16177. * Returns the AbstractMesh.
  16178. */
  16179. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16180. if (!absolutePosition) {
  16181. return this;
  16182. }
  16183. var absolutePositionX;
  16184. var absolutePositionY;
  16185. var absolutePositionZ;
  16186. if (absolutePosition.x === undefined) {
  16187. if (arguments.length < 3) {
  16188. return this;
  16189. }
  16190. absolutePositionX = arguments[0];
  16191. absolutePositionY = arguments[1];
  16192. absolutePositionZ = arguments[2];
  16193. }
  16194. else {
  16195. absolutePositionX = absolutePosition.x;
  16196. absolutePositionY = absolutePosition.y;
  16197. absolutePositionZ = absolutePosition.z;
  16198. }
  16199. if (this.parent) {
  16200. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16201. invertParentWorldMatrix.invert();
  16202. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16203. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16204. }
  16205. else {
  16206. this.position.x = absolutePositionX;
  16207. this.position.y = absolutePositionY;
  16208. this.position.z = absolutePositionZ;
  16209. }
  16210. return this;
  16211. };
  16212. /**
  16213. * Sets the mesh position in its local space.
  16214. * Returns the AbstractMesh.
  16215. */
  16216. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16217. this.computeWorldMatrix();
  16218. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16219. return this;
  16220. };
  16221. /**
  16222. * Returns the mesh position in the local space from the current World matrix values.
  16223. * Returns a new Vector3.
  16224. */
  16225. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16226. this.computeWorldMatrix();
  16227. var invLocalWorldMatrix = this._localWorld.clone();
  16228. invLocalWorldMatrix.invert();
  16229. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16230. };
  16231. /**
  16232. * Translates the mesh along the passed Vector3 in its local space.
  16233. * Returns the AbstractMesh.
  16234. */
  16235. TransformNode.prototype.locallyTranslate = function (vector3) {
  16236. this.computeWorldMatrix(true);
  16237. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16238. return this;
  16239. };
  16240. /**
  16241. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16242. * @param targetPoint the position (must be in same space as current mesh) to look at
  16243. * @param yawCor optional yaw (y-axis) correction in radians
  16244. * @param pitchCor optional pitch (x-axis) correction in radians
  16245. * @param rollCor optional roll (z-axis) correction in radians
  16246. * @param space the choosen space of the target
  16247. * @returns the TransformNode.
  16248. */
  16249. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16250. if (yawCor === void 0) { yawCor = 0; }
  16251. if (pitchCor === void 0) { pitchCor = 0; }
  16252. if (rollCor === void 0) { rollCor = 0; }
  16253. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16254. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16255. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16256. targetPoint.subtractToRef(pos, dv);
  16257. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16258. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16259. var pitch = Math.atan2(dv.y, len);
  16260. if (this.rotationQuaternion) {
  16261. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16262. }
  16263. else {
  16264. this.rotation.x = pitch + pitchCor;
  16265. this.rotation.y = yaw + yawCor;
  16266. this.rotation.z = rollCor;
  16267. }
  16268. return this;
  16269. };
  16270. /**
  16271. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16272. * This Vector3 is expressed in the World space.
  16273. */
  16274. TransformNode.prototype.getDirection = function (localAxis) {
  16275. var result = BABYLON.Vector3.Zero();
  16276. this.getDirectionToRef(localAxis, result);
  16277. return result;
  16278. };
  16279. /**
  16280. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16281. * localAxis is expressed in the mesh local space.
  16282. * result is computed in the Wordl space from the mesh World matrix.
  16283. * Returns the AbstractMesh.
  16284. */
  16285. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16286. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16287. return this;
  16288. };
  16289. /**
  16290. * Sets a new pivot point to the current node
  16291. * @param point defines the new pivot point to use
  16292. * @param space defines if the point is in world or local space (local by default)
  16293. * @returns the current TransformNode
  16294. */
  16295. TransformNode.prototype.setPivotPoint = function (point, space) {
  16296. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16297. if (this.getScene().getRenderId() == 0) {
  16298. this.computeWorldMatrix(true);
  16299. }
  16300. var wm = this.getWorldMatrix();
  16301. if (space == BABYLON.Space.WORLD) {
  16302. var tmat = BABYLON.Tmp.Matrix[0];
  16303. wm.invertToRef(tmat);
  16304. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16305. }
  16306. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16307. };
  16308. /**
  16309. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16310. */
  16311. TransformNode.prototype.getPivotPoint = function () {
  16312. var point = BABYLON.Vector3.Zero();
  16313. this.getPivotPointToRef(point);
  16314. return point;
  16315. };
  16316. /**
  16317. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16318. * Returns the AbstractMesh.
  16319. */
  16320. TransformNode.prototype.getPivotPointToRef = function (result) {
  16321. result.x = -this._pivotMatrix.m[12];
  16322. result.y = -this._pivotMatrix.m[13];
  16323. result.z = -this._pivotMatrix.m[14];
  16324. return this;
  16325. };
  16326. /**
  16327. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16328. */
  16329. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16330. var point = BABYLON.Vector3.Zero();
  16331. this.getAbsolutePivotPointToRef(point);
  16332. return point;
  16333. };
  16334. /**
  16335. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  16336. * Returns the AbstractMesh.
  16337. */
  16338. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  16339. result.x = this._pivotMatrix.m[12];
  16340. result.y = this._pivotMatrix.m[13];
  16341. result.z = this._pivotMatrix.m[14];
  16342. this.getPivotPointToRef(result);
  16343. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  16344. return this;
  16345. };
  16346. /**
  16347. * Defines the passed node as the parent of the current node.
  16348. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  16349. * Returns the TransformNode.
  16350. */
  16351. TransformNode.prototype.setParent = function (node) {
  16352. if (node === null) {
  16353. var rotation = BABYLON.Tmp.Quaternion[0];
  16354. var position = BABYLON.Tmp.Vector3[0];
  16355. var scale = BABYLON.Tmp.Vector3[1];
  16356. if (this.parent && this.parent.computeWorldMatrix) {
  16357. this.parent.computeWorldMatrix(true);
  16358. }
  16359. this.computeWorldMatrix(true);
  16360. this.getWorldMatrix().decompose(scale, rotation, position);
  16361. if (this.rotationQuaternion) {
  16362. this.rotationQuaternion.copyFrom(rotation);
  16363. }
  16364. else {
  16365. rotation.toEulerAnglesToRef(this.rotation);
  16366. }
  16367. this.scaling.x = scale.x;
  16368. this.scaling.y = scale.y;
  16369. this.scaling.z = scale.z;
  16370. this.position.x = position.x;
  16371. this.position.y = position.y;
  16372. this.position.z = position.z;
  16373. }
  16374. else {
  16375. var rotation = BABYLON.Tmp.Quaternion[0];
  16376. var position = BABYLON.Tmp.Vector3[0];
  16377. var scale = BABYLON.Tmp.Vector3[1];
  16378. var diffMatrix = BABYLON.Tmp.Matrix[0];
  16379. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  16380. this.computeWorldMatrix(true);
  16381. node.computeWorldMatrix(true);
  16382. node.getWorldMatrix().invertToRef(invParentMatrix);
  16383. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  16384. diffMatrix.decompose(scale, rotation, position);
  16385. if (this.rotationQuaternion) {
  16386. this.rotationQuaternion.copyFrom(rotation);
  16387. }
  16388. else {
  16389. rotation.toEulerAnglesToRef(this.rotation);
  16390. }
  16391. this.position.x = position.x;
  16392. this.position.y = position.y;
  16393. this.position.z = position.z;
  16394. this.scaling.x = scale.x;
  16395. this.scaling.y = scale.y;
  16396. this.scaling.z = scale.z;
  16397. }
  16398. this.parent = node;
  16399. return this;
  16400. };
  16401. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  16402. get: function () {
  16403. return this._nonUniformScaling;
  16404. },
  16405. enumerable: true,
  16406. configurable: true
  16407. });
  16408. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  16409. if (this._nonUniformScaling === value) {
  16410. return false;
  16411. }
  16412. this._nonUniformScaling = true;
  16413. return true;
  16414. };
  16415. /**
  16416. * Attach the current TransformNode to another TransformNode associated with a bone
  16417. * @param bone Bone affecting the TransformNode
  16418. * @param affectedTransformNode TransformNode associated with the bone
  16419. */
  16420. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  16421. this._transformToBoneReferal = affectedTransformNode;
  16422. this.parent = bone;
  16423. if (bone.getWorldMatrix().determinant() < 0) {
  16424. this.scalingDeterminant *= -1;
  16425. }
  16426. return this;
  16427. };
  16428. TransformNode.prototype.detachFromBone = function () {
  16429. if (!this.parent) {
  16430. return this;
  16431. }
  16432. if (this.parent.getWorldMatrix().determinant() < 0) {
  16433. this.scalingDeterminant *= -1;
  16434. }
  16435. this._transformToBoneReferal = null;
  16436. this.parent = null;
  16437. return this;
  16438. };
  16439. /**
  16440. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  16441. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16442. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16443. * The passed axis is also normalized.
  16444. * Returns the AbstractMesh.
  16445. */
  16446. TransformNode.prototype.rotate = function (axis, amount, space) {
  16447. axis.normalize();
  16448. if (!this.rotationQuaternion) {
  16449. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16450. this.rotation = BABYLON.Vector3.Zero();
  16451. }
  16452. var rotationQuaternion;
  16453. if (!space || space === BABYLON.Space.LOCAL) {
  16454. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16455. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  16456. }
  16457. else {
  16458. if (this.parent) {
  16459. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16460. invertParentWorldMatrix.invert();
  16461. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  16462. }
  16463. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  16464. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16465. }
  16466. return this;
  16467. };
  16468. /**
  16469. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  16470. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  16471. * The passed axis is also normalized.
  16472. * Returns the AbstractMesh.
  16473. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  16474. */
  16475. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  16476. axis.normalize();
  16477. if (!this.rotationQuaternion) {
  16478. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  16479. this.rotation.copyFromFloats(0, 0, 0);
  16480. }
  16481. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  16482. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  16483. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  16484. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  16485. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  16486. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  16487. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  16488. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  16489. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  16490. return this;
  16491. };
  16492. /**
  16493. * Translates the mesh along the axis vector for the passed distance in the given space.
  16494. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  16495. * Returns the AbstractMesh.
  16496. */
  16497. TransformNode.prototype.translate = function (axis, distance, space) {
  16498. var displacementVector = axis.scale(distance);
  16499. if (!space || space === BABYLON.Space.LOCAL) {
  16500. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  16501. this.setPositionWithLocalVector(tempV3);
  16502. }
  16503. else {
  16504. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  16505. }
  16506. return this;
  16507. };
  16508. /**
  16509. * Adds a rotation step to the mesh current rotation.
  16510. * x, y, z are Euler angles expressed in radians.
  16511. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  16512. * This means this rotation is made in the mesh local space only.
  16513. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  16514. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  16515. * ```javascript
  16516. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  16517. * ```
  16518. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  16519. * 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.
  16520. * Returns the AbstractMesh.
  16521. */
  16522. TransformNode.prototype.addRotation = function (x, y, z) {
  16523. var rotationQuaternion;
  16524. if (this.rotationQuaternion) {
  16525. rotationQuaternion = this.rotationQuaternion;
  16526. }
  16527. else {
  16528. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  16529. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  16530. }
  16531. var accumulation = BABYLON.Tmp.Quaternion[0];
  16532. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  16533. rotationQuaternion.multiplyInPlace(accumulation);
  16534. if (!this.rotationQuaternion) {
  16535. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  16536. }
  16537. return this;
  16538. };
  16539. /**
  16540. * Computes the mesh World matrix and returns it.
  16541. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  16542. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  16543. * If the parameter `force`is set to `true`, the actual computation is done.
  16544. * Returns the mesh World Matrix.
  16545. */
  16546. TransformNode.prototype.computeWorldMatrix = function (force) {
  16547. if (this._isWorldMatrixFrozen) {
  16548. return this._worldMatrix;
  16549. }
  16550. if (!force && this.isSynchronized(true)) {
  16551. return this._worldMatrix;
  16552. }
  16553. this._cache.position.copyFrom(this.position);
  16554. this._cache.scaling.copyFrom(this.scaling);
  16555. this._cache.pivotMatrixUpdated = false;
  16556. this._cache.billboardMode = this.billboardMode;
  16557. this._currentRenderId = this.getScene().getRenderId();
  16558. this._isDirty = false;
  16559. // Scaling
  16560. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  16561. // Rotation
  16562. //rotate, if quaternion is set and rotation was used
  16563. if (this.rotationQuaternion) {
  16564. var len = this.rotation.length();
  16565. if (len) {
  16566. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  16567. this.rotation.copyFromFloats(0, 0, 0);
  16568. }
  16569. }
  16570. if (this.rotationQuaternion) {
  16571. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  16572. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  16573. }
  16574. else {
  16575. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  16576. this._cache.rotation.copyFrom(this.rotation);
  16577. }
  16578. // Translation
  16579. var camera = this.getScene().activeCamera;
  16580. if (this.infiniteDistance && !this.parent && camera) {
  16581. var cameraWorldMatrix = camera.getWorldMatrix();
  16582. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  16583. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  16584. }
  16585. else {
  16586. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  16587. }
  16588. // Composing transformations
  16589. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  16590. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16591. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  16592. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  16593. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  16594. // Need to decompose each rotation here
  16595. var currentPosition = BABYLON.Tmp.Vector3[3];
  16596. if (this.parent && this.parent.getWorldMatrix) {
  16597. if (this._transformToBoneReferal) {
  16598. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16599. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  16600. }
  16601. else {
  16602. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  16603. }
  16604. }
  16605. else {
  16606. currentPosition.copyFrom(this.position);
  16607. }
  16608. currentPosition.subtractInPlace(camera.globalPosition);
  16609. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  16610. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  16611. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  16612. }
  16613. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  16614. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  16615. }
  16616. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  16617. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  16618. }
  16619. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  16620. }
  16621. else {
  16622. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  16623. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  16624. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  16625. }
  16626. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  16627. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  16628. }
  16629. // Local world
  16630. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  16631. // Parent
  16632. if (this.parent && this.parent.getWorldMatrix) {
  16633. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  16634. if (this._transformToBoneReferal) {
  16635. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16636. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  16637. }
  16638. else {
  16639. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  16640. }
  16641. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  16642. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  16643. this._worldMatrix.copyFrom(this._localWorld);
  16644. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  16645. }
  16646. else {
  16647. if (this._transformToBoneReferal) {
  16648. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  16649. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  16650. }
  16651. else {
  16652. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  16653. }
  16654. }
  16655. this._markSyncedWithParent();
  16656. }
  16657. else {
  16658. this._worldMatrix.copyFrom(this._localWorld);
  16659. }
  16660. // Post multiply inverse of pivotMatrix
  16661. if (this._postMultiplyPivotMatrix) {
  16662. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  16663. }
  16664. // Normal matrix
  16665. if (this.scaling.isNonUniform) {
  16666. this._updateNonUniformScalingState(true);
  16667. }
  16668. else if (this.parent && this.parent._nonUniformScaling) {
  16669. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  16670. }
  16671. else {
  16672. this._updateNonUniformScalingState(false);
  16673. }
  16674. this._afterComputeWorldMatrix();
  16675. // Absolute position
  16676. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  16677. // Callbacks
  16678. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  16679. if (!this._poseMatrix) {
  16680. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  16681. }
  16682. // Cache the determinant
  16683. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  16684. return this._worldMatrix;
  16685. };
  16686. TransformNode.prototype._afterComputeWorldMatrix = function () {
  16687. };
  16688. /**
  16689. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  16690. * @param func: callback function to add
  16691. *
  16692. * Returns the TransformNode.
  16693. */
  16694. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  16695. this.onAfterWorldMatrixUpdateObservable.add(func);
  16696. return this;
  16697. };
  16698. /**
  16699. * Removes a registered callback function.
  16700. * Returns the TransformNode.
  16701. */
  16702. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  16703. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  16704. return this;
  16705. };
  16706. /**
  16707. * Clone the current transform node
  16708. * Returns the new transform node
  16709. * @param name Name of the new clone
  16710. * @param newParent New parent for the clone
  16711. * @param doNotCloneChildren Do not clone children hierarchy
  16712. */
  16713. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  16714. var _this = this;
  16715. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  16716. result.name = name;
  16717. result.id = name;
  16718. if (newParent) {
  16719. result.parent = newParent;
  16720. }
  16721. if (!doNotCloneChildren) {
  16722. // Children
  16723. var directDescendants = this.getDescendants(true);
  16724. for (var index = 0; index < directDescendants.length; index++) {
  16725. var child = directDescendants[index];
  16726. if (child.clone) {
  16727. child.clone(name + "." + child.name, result);
  16728. }
  16729. }
  16730. }
  16731. return result;
  16732. };
  16733. TransformNode.prototype.serialize = function (currentSerializationObject) {
  16734. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  16735. serializationObject.type = this.getClassName();
  16736. // Parent
  16737. if (this.parent) {
  16738. serializationObject.parentId = this.parent.id;
  16739. }
  16740. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  16741. serializationObject.tags = BABYLON.Tags.GetTags(this);
  16742. }
  16743. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  16744. serializationObject.isEnabled = this.isEnabled();
  16745. // Parent
  16746. if (this.parent) {
  16747. serializationObject.parentId = this.parent.id;
  16748. }
  16749. return serializationObject;
  16750. };
  16751. // Statics
  16752. /**
  16753. * Returns a new TransformNode object parsed from the source provided.
  16754. * The parameter `parsedMesh` is the source.
  16755. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  16756. */
  16757. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  16758. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  16759. if (BABYLON.Tags) {
  16760. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  16761. }
  16762. if (parsedTransformNode.localMatrix) {
  16763. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  16764. }
  16765. else if (parsedTransformNode.pivotMatrix) {
  16766. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  16767. }
  16768. transformNode.setEnabled(parsedTransformNode.isEnabled);
  16769. // Parent
  16770. if (parsedTransformNode.parentId) {
  16771. transformNode._waitingParentId = parsedTransformNode.parentId;
  16772. }
  16773. return transformNode;
  16774. };
  16775. /**
  16776. * Disposes the TransformNode.
  16777. * By default, all the children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  16778. * Returns nothing.
  16779. */
  16780. TransformNode.prototype.dispose = function (doNotRecurse) {
  16781. // Animations
  16782. this.getScene().stopAnimation(this);
  16783. // Remove from scene
  16784. this.getScene().removeTransformNode(this);
  16785. if (!doNotRecurse) {
  16786. // Children
  16787. var objects = this.getDescendants(true);
  16788. for (var index = 0; index < objects.length; index++) {
  16789. objects[index].dispose();
  16790. }
  16791. }
  16792. else {
  16793. var childMeshes = this.getChildMeshes(true);
  16794. for (index = 0; index < childMeshes.length; index++) {
  16795. var child = childMeshes[index];
  16796. child.parent = null;
  16797. child.computeWorldMatrix(true);
  16798. }
  16799. }
  16800. this.onAfterWorldMatrixUpdateObservable.clear();
  16801. _super.prototype.dispose.call(this);
  16802. };
  16803. // Statics
  16804. TransformNode.BILLBOARDMODE_NONE = 0;
  16805. TransformNode.BILLBOARDMODE_X = 1;
  16806. TransformNode.BILLBOARDMODE_Y = 2;
  16807. TransformNode.BILLBOARDMODE_Z = 4;
  16808. TransformNode.BILLBOARDMODE_ALL = 7;
  16809. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  16810. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  16811. __decorate([
  16812. BABYLON.serializeAsVector3()
  16813. ], TransformNode.prototype, "_rotation", void 0);
  16814. __decorate([
  16815. BABYLON.serializeAsQuaternion()
  16816. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  16817. __decorate([
  16818. BABYLON.serializeAsVector3()
  16819. ], TransformNode.prototype, "_scaling", void 0);
  16820. __decorate([
  16821. BABYLON.serialize()
  16822. ], TransformNode.prototype, "billboardMode", void 0);
  16823. __decorate([
  16824. BABYLON.serialize()
  16825. ], TransformNode.prototype, "scalingDeterminant", void 0);
  16826. __decorate([
  16827. BABYLON.serialize()
  16828. ], TransformNode.prototype, "infiniteDistance", void 0);
  16829. __decorate([
  16830. BABYLON.serializeAsVector3()
  16831. ], TransformNode.prototype, "position", void 0);
  16832. return TransformNode;
  16833. }(BABYLON.Node));
  16834. BABYLON.TransformNode = TransformNode;
  16835. })(BABYLON || (BABYLON = {}));
  16836. //# sourceMappingURL=babylon.transformNode.js.map
  16837. var BABYLON;
  16838. (function (BABYLON) {
  16839. var AbstractMesh = /** @class */ (function (_super) {
  16840. __extends(AbstractMesh, _super);
  16841. // Constructor
  16842. function AbstractMesh(name, scene) {
  16843. if (scene === void 0) { scene = null; }
  16844. var _this = _super.call(this, name, scene, false) || this;
  16845. _this._facetNb = 0; // facet number
  16846. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  16847. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  16848. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  16849. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  16850. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  16851. _this._subDiv = {
  16852. max: 1,
  16853. X: 1,
  16854. Y: 1,
  16855. Z: 1
  16856. };
  16857. _this._facetDepthSort = false; // is the facet depth sort to be computed
  16858. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  16859. // Events
  16860. /**
  16861. * An event triggered when this mesh collides with another one
  16862. * @type {BABYLON.Observable}
  16863. */
  16864. _this.onCollideObservable = new BABYLON.Observable();
  16865. /**
  16866. * An event triggered when the collision's position changes
  16867. * @type {BABYLON.Observable}
  16868. */
  16869. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  16870. /**
  16871. * An event triggered when material is changed
  16872. * @type {BABYLON.Observable}
  16873. */
  16874. _this.onMaterialChangedObservable = new BABYLON.Observable();
  16875. // Properties
  16876. _this.definedFacingForward = true; // orientation for POV movement & rotation
  16877. /**
  16878. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  16879. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  16880. * or
  16881. * 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.
  16882. * for more info check WebGl documentations
  16883. */
  16884. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  16885. /**
  16886. * 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:
  16887. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  16888. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  16889. * 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.
  16890. */
  16891. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  16892. /**
  16893. * 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.
  16894. * The default value is -1 which means don't break the query and wait till the result.
  16895. */
  16896. _this.occlusionRetryCount = -1;
  16897. _this._occlusionInternalRetryCounter = 0;
  16898. _this._isOccluded = false;
  16899. _this._isOcclusionQueryInProgress = false;
  16900. _this._visibility = 1.0;
  16901. _this.alphaIndex = Number.MAX_VALUE;
  16902. _this.isVisible = true;
  16903. _this.isPickable = true;
  16904. _this.showBoundingBox = false;
  16905. _this.showSubMeshesBoundingBox = false;
  16906. _this.isBlocker = false;
  16907. _this.enablePointerMoveEvents = false;
  16908. _this.renderingGroupId = 0;
  16909. _this._receiveShadows = false;
  16910. _this.renderOutline = false;
  16911. _this.outlineColor = BABYLON.Color3.Red();
  16912. _this.outlineWidth = 0.02;
  16913. _this.renderOverlay = false;
  16914. _this.overlayColor = BABYLON.Color3.Red();
  16915. _this.overlayAlpha = 0.5;
  16916. _this._hasVertexAlpha = false;
  16917. _this._useVertexColors = true;
  16918. _this._computeBonesUsingShaders = true;
  16919. _this._numBoneInfluencers = 4;
  16920. _this._applyFog = true;
  16921. _this.useOctreeForRenderingSelection = true;
  16922. _this.useOctreeForPicking = true;
  16923. _this.useOctreeForCollisions = true;
  16924. _this._layerMask = 0x0FFFFFFF;
  16925. /**
  16926. * True if the mesh must be rendered in any case.
  16927. */
  16928. _this.alwaysSelectAsActiveMesh = false;
  16929. /**
  16930. * This scene's action manager
  16931. * @type {BABYLON.ActionManager}
  16932. */
  16933. _this.actionManager = null;
  16934. // Physics
  16935. _this.physicsImpostor = null;
  16936. // Collisions
  16937. _this._checkCollisions = false;
  16938. _this._collisionMask = -1;
  16939. _this._collisionGroup = -1;
  16940. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  16941. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  16942. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16943. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  16944. // Edges
  16945. _this.edgesWidth = 1;
  16946. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  16947. // Cache
  16948. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  16949. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  16950. _this._renderId = 0;
  16951. _this._intersectionsInProgress = new Array();
  16952. _this._unIndexed = false;
  16953. _this._lightSources = new Array();
  16954. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  16955. if (collidedMesh === void 0) { collidedMesh = null; }
  16956. //TODO move this to the collision coordinator!
  16957. if (_this.getScene().workerCollisions)
  16958. newPosition.multiplyInPlace(_this._collider._radius);
  16959. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  16960. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  16961. _this.position.addInPlace(_this._diffPositionForCollisions);
  16962. }
  16963. if (collidedMesh) {
  16964. _this.onCollideObservable.notifyObservers(collidedMesh);
  16965. }
  16966. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  16967. };
  16968. _this.getScene().addMesh(_this);
  16969. _this._resyncLightSources();
  16970. return _this;
  16971. }
  16972. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  16973. get: function () {
  16974. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  16975. },
  16976. enumerable: true,
  16977. configurable: true
  16978. });
  16979. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  16980. get: function () {
  16981. return BABYLON.TransformNode.BILLBOARDMODE_X;
  16982. },
  16983. enumerable: true,
  16984. configurable: true
  16985. });
  16986. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  16987. get: function () {
  16988. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  16989. },
  16990. enumerable: true,
  16991. configurable: true
  16992. });
  16993. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  16994. get: function () {
  16995. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  16996. },
  16997. enumerable: true,
  16998. configurable: true
  16999. });
  17000. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17001. get: function () {
  17002. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17003. },
  17004. enumerable: true,
  17005. configurable: true
  17006. });
  17007. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17008. /**
  17009. * Read-only : the number of facets in the mesh
  17010. */
  17011. get: function () {
  17012. return this._facetNb;
  17013. },
  17014. enumerable: true,
  17015. configurable: true
  17016. });
  17017. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17018. /**
  17019. * The number (integer) of subdivisions per axis in the partioning space
  17020. */
  17021. get: function () {
  17022. return this._partitioningSubdivisions;
  17023. },
  17024. set: function (nb) {
  17025. this._partitioningSubdivisions = nb;
  17026. },
  17027. enumerable: true,
  17028. configurable: true
  17029. });
  17030. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17031. /**
  17032. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17033. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17034. */
  17035. get: function () {
  17036. return this._partitioningBBoxRatio;
  17037. },
  17038. set: function (ratio) {
  17039. this._partitioningBBoxRatio = ratio;
  17040. },
  17041. enumerable: true,
  17042. configurable: true
  17043. });
  17044. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17045. /**
  17046. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17047. * Works only for updatable meshes.
  17048. * Doesn't work with multi-materials.
  17049. */
  17050. get: function () {
  17051. return this._facetDepthSort;
  17052. },
  17053. set: function (sort) {
  17054. this._facetDepthSort = sort;
  17055. },
  17056. enumerable: true,
  17057. configurable: true
  17058. });
  17059. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17060. /**
  17061. * The location (Vector3) where the facet depth sort must be computed from.
  17062. * By default, the active camera position.
  17063. * Used only when facet depth sort is enabled.
  17064. */
  17065. get: function () {
  17066. return this._facetDepthSortFrom;
  17067. },
  17068. set: function (location) {
  17069. this._facetDepthSortFrom = location;
  17070. },
  17071. enumerable: true,
  17072. configurable: true
  17073. });
  17074. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17075. /**
  17076. * Read-only boolean : is the feature facetData enabled ?
  17077. */
  17078. get: function () {
  17079. return this._facetDataEnabled;
  17080. },
  17081. enumerable: true,
  17082. configurable: true
  17083. });
  17084. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17085. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17086. return false;
  17087. }
  17088. this._markSubMeshesAsMiscDirty();
  17089. return true;
  17090. };
  17091. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17092. set: function (callback) {
  17093. if (this._onCollideObserver) {
  17094. this.onCollideObservable.remove(this._onCollideObserver);
  17095. }
  17096. this._onCollideObserver = this.onCollideObservable.add(callback);
  17097. },
  17098. enumerable: true,
  17099. configurable: true
  17100. });
  17101. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17102. set: function (callback) {
  17103. if (this._onCollisionPositionChangeObserver) {
  17104. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17105. }
  17106. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17107. },
  17108. enumerable: true,
  17109. configurable: true
  17110. });
  17111. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17112. /**
  17113. * Property isOccluded : 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.
  17114. */
  17115. get: function () {
  17116. return this._isOccluded;
  17117. },
  17118. set: function (value) {
  17119. this._isOccluded = value;
  17120. },
  17121. enumerable: true,
  17122. configurable: true
  17123. });
  17124. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17125. /**
  17126. * Flag to check the progress status of the query
  17127. */
  17128. get: function () {
  17129. return this._isOcclusionQueryInProgress;
  17130. },
  17131. enumerable: true,
  17132. configurable: true
  17133. });
  17134. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17135. /**
  17136. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17137. */
  17138. get: function () {
  17139. return this._visibility;
  17140. },
  17141. /**
  17142. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17143. */
  17144. set: function (value) {
  17145. if (this._visibility === value) {
  17146. return;
  17147. }
  17148. this._visibility = value;
  17149. this._markSubMeshesAsMiscDirty();
  17150. },
  17151. enumerable: true,
  17152. configurable: true
  17153. });
  17154. Object.defineProperty(AbstractMesh.prototype, "material", {
  17155. get: function () {
  17156. return this._material;
  17157. },
  17158. set: function (value) {
  17159. if (this._material === value) {
  17160. return;
  17161. }
  17162. this._material = value;
  17163. if (this.onMaterialChangedObservable.hasObservers) {
  17164. this.onMaterialChangedObservable.notifyObservers(this);
  17165. }
  17166. if (!this.subMeshes) {
  17167. return;
  17168. }
  17169. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17170. var subMesh = _a[_i];
  17171. subMesh.setEffect(null);
  17172. }
  17173. },
  17174. enumerable: true,
  17175. configurable: true
  17176. });
  17177. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17178. get: function () {
  17179. return this._receiveShadows;
  17180. },
  17181. set: function (value) {
  17182. if (this._receiveShadows === value) {
  17183. return;
  17184. }
  17185. this._receiveShadows = value;
  17186. this._markSubMeshesAsLightDirty();
  17187. },
  17188. enumerable: true,
  17189. configurable: true
  17190. });
  17191. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17192. get: function () {
  17193. return this._hasVertexAlpha;
  17194. },
  17195. set: function (value) {
  17196. if (this._hasVertexAlpha === value) {
  17197. return;
  17198. }
  17199. this._hasVertexAlpha = value;
  17200. this._markSubMeshesAsAttributesDirty();
  17201. this._markSubMeshesAsMiscDirty();
  17202. },
  17203. enumerable: true,
  17204. configurable: true
  17205. });
  17206. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17207. get: function () {
  17208. return this._useVertexColors;
  17209. },
  17210. set: function (value) {
  17211. if (this._useVertexColors === value) {
  17212. return;
  17213. }
  17214. this._useVertexColors = value;
  17215. this._markSubMeshesAsAttributesDirty();
  17216. },
  17217. enumerable: true,
  17218. configurable: true
  17219. });
  17220. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17221. get: function () {
  17222. return this._computeBonesUsingShaders;
  17223. },
  17224. set: function (value) {
  17225. if (this._computeBonesUsingShaders === value) {
  17226. return;
  17227. }
  17228. this._computeBonesUsingShaders = value;
  17229. this._markSubMeshesAsAttributesDirty();
  17230. },
  17231. enumerable: true,
  17232. configurable: true
  17233. });
  17234. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17235. get: function () {
  17236. return this._numBoneInfluencers;
  17237. },
  17238. set: function (value) {
  17239. if (this._numBoneInfluencers === value) {
  17240. return;
  17241. }
  17242. this._numBoneInfluencers = value;
  17243. this._markSubMeshesAsAttributesDirty();
  17244. },
  17245. enumerable: true,
  17246. configurable: true
  17247. });
  17248. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17249. get: function () {
  17250. return this._applyFog;
  17251. },
  17252. set: function (value) {
  17253. if (this._applyFog === value) {
  17254. return;
  17255. }
  17256. this._applyFog = value;
  17257. this._markSubMeshesAsMiscDirty();
  17258. },
  17259. enumerable: true,
  17260. configurable: true
  17261. });
  17262. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17263. get: function () {
  17264. return this._layerMask;
  17265. },
  17266. set: function (value) {
  17267. if (value === this._layerMask) {
  17268. return;
  17269. }
  17270. this._layerMask = value;
  17271. this._resyncLightSources();
  17272. },
  17273. enumerable: true,
  17274. configurable: true
  17275. });
  17276. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17277. get: function () {
  17278. return this._collisionMask;
  17279. },
  17280. set: function (mask) {
  17281. this._collisionMask = !isNaN(mask) ? mask : -1;
  17282. },
  17283. enumerable: true,
  17284. configurable: true
  17285. });
  17286. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17287. get: function () {
  17288. return this._collisionGroup;
  17289. },
  17290. set: function (mask) {
  17291. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17292. },
  17293. enumerable: true,
  17294. configurable: true
  17295. });
  17296. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17297. get: function () {
  17298. return null;
  17299. },
  17300. enumerable: true,
  17301. configurable: true
  17302. });
  17303. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17304. get: function () {
  17305. return this._skeleton;
  17306. },
  17307. set: function (value) {
  17308. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17309. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17310. }
  17311. if (value && value.needInitialSkinMatrix) {
  17312. value._registerMeshWithPoseMatrix(this);
  17313. }
  17314. this._skeleton = value;
  17315. if (!this._skeleton) {
  17316. this._bonesTransformMatrices = null;
  17317. }
  17318. this._markSubMeshesAsAttributesDirty();
  17319. },
  17320. enumerable: true,
  17321. configurable: true
  17322. });
  17323. /**
  17324. * Returns the string "AbstractMesh"
  17325. */
  17326. AbstractMesh.prototype.getClassName = function () {
  17327. return "AbstractMesh";
  17328. };
  17329. /**
  17330. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17331. */
  17332. AbstractMesh.prototype.toString = function (fullDetails) {
  17333. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17334. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17335. if (this._skeleton) {
  17336. ret += ", skeleton: " + this._skeleton.name;
  17337. }
  17338. if (fullDetails) {
  17339. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17340. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17341. }
  17342. return ret;
  17343. };
  17344. AbstractMesh.prototype._rebuild = function () {
  17345. if (this._occlusionQuery) {
  17346. this._occlusionQuery = null;
  17347. }
  17348. if (this._edgesRenderer) {
  17349. this._edgesRenderer._rebuild();
  17350. }
  17351. if (!this.subMeshes) {
  17352. return;
  17353. }
  17354. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17355. var subMesh = _a[_i];
  17356. subMesh._rebuild();
  17357. }
  17358. };
  17359. AbstractMesh.prototype._resyncLightSources = function () {
  17360. this._lightSources.length = 0;
  17361. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  17362. var light = _a[_i];
  17363. if (!light.isEnabled()) {
  17364. continue;
  17365. }
  17366. if (light.canAffectMesh(this)) {
  17367. this._lightSources.push(light);
  17368. }
  17369. }
  17370. this._markSubMeshesAsLightDirty();
  17371. };
  17372. AbstractMesh.prototype._resyncLighSource = function (light) {
  17373. var isIn = light.isEnabled() && light.canAffectMesh(this);
  17374. var index = this._lightSources.indexOf(light);
  17375. if (index === -1) {
  17376. if (!isIn) {
  17377. return;
  17378. }
  17379. this._lightSources.push(light);
  17380. }
  17381. else {
  17382. if (isIn) {
  17383. return;
  17384. }
  17385. this._lightSources.splice(index, 1);
  17386. }
  17387. this._markSubMeshesAsLightDirty();
  17388. };
  17389. AbstractMesh.prototype._removeLightSource = function (light) {
  17390. var index = this._lightSources.indexOf(light);
  17391. if (index === -1) {
  17392. return;
  17393. }
  17394. this._lightSources.splice(index, 1);
  17395. this._markSubMeshesAsLightDirty();
  17396. };
  17397. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  17398. if (!this.subMeshes) {
  17399. return;
  17400. }
  17401. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17402. var subMesh = _a[_i];
  17403. if (subMesh._materialDefines) {
  17404. func(subMesh._materialDefines);
  17405. }
  17406. }
  17407. };
  17408. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  17409. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  17410. };
  17411. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  17412. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  17413. };
  17414. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  17415. if (!this.subMeshes) {
  17416. return;
  17417. }
  17418. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17419. var subMesh = _a[_i];
  17420. var material = subMesh.getMaterial();
  17421. if (material) {
  17422. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  17423. }
  17424. }
  17425. };
  17426. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  17427. /**
  17428. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17429. * Default : (1.0, 1.0, 1.0)
  17430. */
  17431. get: function () {
  17432. return this._scaling;
  17433. },
  17434. /**
  17435. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  17436. * Default : (1.0, 1.0, 1.0)
  17437. */
  17438. set: function (newScaling) {
  17439. this._scaling = newScaling;
  17440. if (this.physicsImpostor) {
  17441. this.physicsImpostor.forceUpdate();
  17442. }
  17443. },
  17444. enumerable: true,
  17445. configurable: true
  17446. });
  17447. // Methods
  17448. /**
  17449. * Disables the mesh edger rendering mode.
  17450. * Returns the AbstractMesh.
  17451. */
  17452. AbstractMesh.prototype.disableEdgesRendering = function () {
  17453. if (this._edgesRenderer) {
  17454. this._edgesRenderer.dispose();
  17455. this._edgesRenderer = null;
  17456. }
  17457. return this;
  17458. };
  17459. /**
  17460. * Enables the edge rendering mode on the mesh.
  17461. * This mode makes the mesh edges visible.
  17462. * Returns the AbstractMesh.
  17463. */
  17464. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  17465. if (epsilon === void 0) { epsilon = 0.95; }
  17466. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  17467. this.disableEdgesRendering();
  17468. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  17469. return this;
  17470. };
  17471. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  17472. /**
  17473. * Returns true if the mesh is blocked. Used by the class Mesh.
  17474. * Returns the boolean `false` by default.
  17475. */
  17476. get: function () {
  17477. return false;
  17478. },
  17479. enumerable: true,
  17480. configurable: true
  17481. });
  17482. /**
  17483. * Returns the mesh itself by default, used by the class Mesh.
  17484. * Returned type : AbstractMesh
  17485. */
  17486. AbstractMesh.prototype.getLOD = function (camera) {
  17487. return this;
  17488. };
  17489. /**
  17490. * Returns 0 by default, used by the class Mesh.
  17491. * Returns an integer.
  17492. */
  17493. AbstractMesh.prototype.getTotalVertices = function () {
  17494. return 0;
  17495. };
  17496. /**
  17497. * Returns null by default, used by the class Mesh.
  17498. * Returned type : integer array
  17499. */
  17500. AbstractMesh.prototype.getIndices = function () {
  17501. return null;
  17502. };
  17503. /**
  17504. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  17505. * Returned type : float array or Float32Array
  17506. */
  17507. AbstractMesh.prototype.getVerticesData = function (kind) {
  17508. return null;
  17509. };
  17510. /**
  17511. * Sets the vertex data of the mesh geometry for the requested `kind`.
  17512. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  17513. * The `data` are either a numeric array either a Float32Array.
  17514. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  17515. * 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).
  17516. * Note that a new underlying VertexBuffer object is created each call.
  17517. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  17518. *
  17519. * Possible `kind` values :
  17520. * - BABYLON.VertexBuffer.PositionKind
  17521. * - BABYLON.VertexBuffer.UVKind
  17522. * - BABYLON.VertexBuffer.UV2Kind
  17523. * - BABYLON.VertexBuffer.UV3Kind
  17524. * - BABYLON.VertexBuffer.UV4Kind
  17525. * - BABYLON.VertexBuffer.UV5Kind
  17526. * - BABYLON.VertexBuffer.UV6Kind
  17527. * - BABYLON.VertexBuffer.ColorKind
  17528. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17529. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17530. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17531. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17532. *
  17533. * Returns the Mesh.
  17534. */
  17535. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  17536. return this;
  17537. };
  17538. /**
  17539. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  17540. * If the mesh has no geometry, it is simply returned as it is.
  17541. * The `data` are either a numeric array either a Float32Array.
  17542. * No new underlying VertexBuffer object is created.
  17543. * 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.
  17544. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  17545. *
  17546. * Possible `kind` values :
  17547. * - BABYLON.VertexBuffer.PositionKind
  17548. * - BABYLON.VertexBuffer.UVKind
  17549. * - BABYLON.VertexBuffer.UV2Kind
  17550. * - BABYLON.VertexBuffer.UV3Kind
  17551. * - BABYLON.VertexBuffer.UV4Kind
  17552. * - BABYLON.VertexBuffer.UV5Kind
  17553. * - BABYLON.VertexBuffer.UV6Kind
  17554. * - BABYLON.VertexBuffer.ColorKind
  17555. * - BABYLON.VertexBuffer.MatricesIndicesKind
  17556. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  17557. * - BABYLON.VertexBuffer.MatricesWeightsKind
  17558. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  17559. *
  17560. * Returns the Mesh.
  17561. */
  17562. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  17563. return this;
  17564. };
  17565. /**
  17566. * Sets the mesh indices.
  17567. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  17568. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  17569. * This method creates a new index buffer each call.
  17570. * Returns the Mesh.
  17571. */
  17572. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  17573. return this;
  17574. };
  17575. /** Returns false by default, used by the class Mesh.
  17576. * Returns a boolean
  17577. */
  17578. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  17579. return false;
  17580. };
  17581. /**
  17582. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  17583. * Returns a BoundingInfo
  17584. */
  17585. AbstractMesh.prototype.getBoundingInfo = function () {
  17586. if (this._masterMesh) {
  17587. return this._masterMesh.getBoundingInfo();
  17588. }
  17589. if (!this._boundingInfo) {
  17590. // this._boundingInfo is being created here
  17591. this._updateBoundingInfo();
  17592. }
  17593. // cannot be null.
  17594. return this._boundingInfo;
  17595. };
  17596. /**
  17597. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  17598. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  17599. */
  17600. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  17601. if (includeDescendants === void 0) { includeDescendants = true; }
  17602. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  17603. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  17604. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  17605. if (maxDimension === 0) {
  17606. return this;
  17607. }
  17608. var scale = 1 / maxDimension;
  17609. this.scaling.scaleInPlace(scale);
  17610. return this;
  17611. };
  17612. /**
  17613. * Sets a mesh new object BoundingInfo.
  17614. * Returns the AbstractMesh.
  17615. */
  17616. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  17617. this._boundingInfo = boundingInfo;
  17618. return this;
  17619. };
  17620. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  17621. get: function () {
  17622. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  17623. },
  17624. enumerable: true,
  17625. configurable: true
  17626. });
  17627. AbstractMesh.prototype._preActivate = function () {
  17628. };
  17629. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  17630. };
  17631. AbstractMesh.prototype._activate = function (renderId) {
  17632. this._renderId = renderId;
  17633. };
  17634. /**
  17635. * Returns the latest update of the World matrix
  17636. * Returns a Matrix.
  17637. */
  17638. AbstractMesh.prototype.getWorldMatrix = function () {
  17639. if (this._masterMesh) {
  17640. return this._masterMesh.getWorldMatrix();
  17641. }
  17642. return _super.prototype.getWorldMatrix.call(this);
  17643. };
  17644. /**
  17645. * Returns the latest update of the World matrix determinant.
  17646. */
  17647. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  17648. if (this._masterMesh) {
  17649. return this._masterMesh._getWorldMatrixDeterminant();
  17650. }
  17651. return _super.prototype._getWorldMatrixDeterminant.call(this);
  17652. };
  17653. // ================================== Point of View Movement =================================
  17654. /**
  17655. * Perform relative position change from the point of view of behind the front of the mesh.
  17656. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17657. * Supports definition of mesh facing forward or backward.
  17658. * @param {number} amountRight
  17659. * @param {number} amountUp
  17660. * @param {number} amountForward
  17661. *
  17662. * Returns the AbstractMesh.
  17663. */
  17664. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  17665. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  17666. return this;
  17667. };
  17668. /**
  17669. * Calculate relative position change from the point of view of behind the front of the mesh.
  17670. * This is performed taking into account the meshes current rotation, so you do not have to care.
  17671. * Supports definition of mesh facing forward or backward.
  17672. * @param {number} amountRight
  17673. * @param {number} amountUp
  17674. * @param {number} amountForward
  17675. *
  17676. * Returns a new Vector3.
  17677. */
  17678. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  17679. var rotMatrix = new BABYLON.Matrix();
  17680. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17681. rotQuaternion.toRotationMatrix(rotMatrix);
  17682. var translationDelta = BABYLON.Vector3.Zero();
  17683. var defForwardMult = this.definedFacingForward ? -1 : 1;
  17684. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  17685. return translationDelta;
  17686. };
  17687. // ================================== Point of View Rotation =================================
  17688. /**
  17689. * Perform relative rotation change from the point of view of behind the front of the mesh.
  17690. * Supports definition of mesh facing forward or backward.
  17691. * @param {number} flipBack
  17692. * @param {number} twirlClockwise
  17693. * @param {number} tiltRight
  17694. *
  17695. * Returns the AbstractMesh.
  17696. */
  17697. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17698. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  17699. return this;
  17700. };
  17701. /**
  17702. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  17703. * Supports definition of mesh facing forward or backward.
  17704. * @param {number} flipBack
  17705. * @param {number} twirlClockwise
  17706. * @param {number} tiltRight
  17707. *
  17708. * Returns a new Vector3.
  17709. */
  17710. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  17711. var defForwardMult = this.definedFacingForward ? 1 : -1;
  17712. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  17713. };
  17714. /**
  17715. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  17716. * @param includeDescendants Include bounding info from descendants as well (true by default).
  17717. */
  17718. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  17719. if (includeDescendants === void 0) { includeDescendants = true; }
  17720. this.computeWorldMatrix(true);
  17721. var min;
  17722. var max;
  17723. var boundingInfo = this.getBoundingInfo();
  17724. if (!this.subMeshes) {
  17725. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  17726. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  17727. }
  17728. else {
  17729. min = boundingInfo.boundingBox.minimumWorld;
  17730. max = boundingInfo.boundingBox.maximumWorld;
  17731. }
  17732. if (includeDescendants) {
  17733. var descendants = this.getDescendants(false);
  17734. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  17735. var descendant = descendants_1[_i];
  17736. var childMesh = descendant;
  17737. childMesh.computeWorldMatrix(true);
  17738. //make sure we have the needed params to get mix and max
  17739. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  17740. continue;
  17741. }
  17742. var childBoundingInfo = childMesh.getBoundingInfo();
  17743. var boundingBox = childBoundingInfo.boundingBox;
  17744. var minBox = boundingBox.minimumWorld;
  17745. var maxBox = boundingBox.maximumWorld;
  17746. BABYLON.Tools.CheckExtends(minBox, min, max);
  17747. BABYLON.Tools.CheckExtends(maxBox, min, max);
  17748. }
  17749. }
  17750. return {
  17751. min: min,
  17752. max: max
  17753. };
  17754. };
  17755. /**
  17756. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  17757. * Returns the AbstractMesh.
  17758. */
  17759. AbstractMesh.prototype._updateBoundingInfo = function () {
  17760. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  17761. this._boundingInfo.update(this.worldMatrixFromCache);
  17762. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  17763. return this;
  17764. };
  17765. /**
  17766. * Update a mesh's children BoundingInfo objects only.
  17767. * Returns the AbstractMesh.
  17768. */
  17769. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  17770. if (!this.subMeshes) {
  17771. return this;
  17772. }
  17773. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  17774. var subMesh = this.subMeshes[subIndex];
  17775. if (!subMesh.IsGlobal) {
  17776. subMesh.updateBoundingInfo(matrix);
  17777. }
  17778. }
  17779. return this;
  17780. };
  17781. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  17782. // Bounding info
  17783. this._updateBoundingInfo();
  17784. };
  17785. /**
  17786. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  17787. * A mesh is in the frustum if its bounding box intersects the frustum.
  17788. * Boolean returned.
  17789. */
  17790. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  17791. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  17792. };
  17793. /**
  17794. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  17795. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  17796. * Boolean returned.
  17797. */
  17798. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  17799. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  17800. ;
  17801. };
  17802. /**
  17803. * True if the mesh intersects another mesh or a SolidParticle object.
  17804. * 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)
  17805. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  17806. * Returns a boolean.
  17807. */
  17808. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  17809. if (precise === void 0) { precise = false; }
  17810. if (!this._boundingInfo || !mesh._boundingInfo) {
  17811. return false;
  17812. }
  17813. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  17814. return true;
  17815. }
  17816. if (includeDescendants) {
  17817. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  17818. var child = _a[_i];
  17819. if (child.intersectsMesh(mesh, precise, true)) {
  17820. return true;
  17821. }
  17822. }
  17823. }
  17824. return false;
  17825. };
  17826. /**
  17827. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  17828. * Returns a boolean.
  17829. */
  17830. AbstractMesh.prototype.intersectsPoint = function (point) {
  17831. if (!this._boundingInfo) {
  17832. return false;
  17833. }
  17834. return this._boundingInfo.intersectsPoint(point);
  17835. };
  17836. AbstractMesh.prototype.getPhysicsImpostor = function () {
  17837. return this.physicsImpostor;
  17838. };
  17839. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  17840. if (camera === void 0) { camera = null; }
  17841. if (!camera) {
  17842. camera = this.getScene().activeCamera;
  17843. }
  17844. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  17845. };
  17846. /**
  17847. * Returns the distance from the mesh to the active camera.
  17848. * Returns a float.
  17849. */
  17850. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  17851. if (camera === void 0) { camera = null; }
  17852. if (!camera) {
  17853. camera = this.getScene().activeCamera;
  17854. }
  17855. return this.absolutePosition.subtract(camera.position).length();
  17856. };
  17857. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  17858. if (!this.physicsImpostor) {
  17859. return this;
  17860. }
  17861. this.physicsImpostor.applyImpulse(force, contactPoint);
  17862. return this;
  17863. };
  17864. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  17865. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  17866. return this;
  17867. }
  17868. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  17869. mainPivot: pivot1,
  17870. connectedPivot: pivot2,
  17871. nativeParams: options
  17872. });
  17873. return this;
  17874. };
  17875. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  17876. // Collisions
  17877. /**
  17878. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  17879. * Default `false`.
  17880. */
  17881. get: function () {
  17882. return this._checkCollisions;
  17883. },
  17884. set: function (collisionEnabled) {
  17885. this._checkCollisions = collisionEnabled;
  17886. if (this.getScene().workerCollisions) {
  17887. this.getScene().collisionCoordinator.onMeshUpdated(this);
  17888. }
  17889. },
  17890. enumerable: true,
  17891. configurable: true
  17892. });
  17893. Object.defineProperty(AbstractMesh.prototype, "collider", {
  17894. /**
  17895. * Gets Collider object used to compute collisions (not physics)
  17896. */
  17897. get: function () {
  17898. return this._collider;
  17899. },
  17900. enumerable: true,
  17901. configurable: true
  17902. });
  17903. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  17904. var globalPosition = this.getAbsolutePosition();
  17905. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  17906. if (!this._collider) {
  17907. this._collider = new BABYLON.Collider();
  17908. }
  17909. this._collider._radius = this.ellipsoid;
  17910. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  17911. return this;
  17912. };
  17913. // Submeshes octree
  17914. /**
  17915. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  17916. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  17917. * Returns an Octree of submeshes.
  17918. */
  17919. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  17920. if (maxCapacity === void 0) { maxCapacity = 64; }
  17921. if (maxDepth === void 0) { maxDepth = 2; }
  17922. if (!this._submeshesOctree) {
  17923. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  17924. }
  17925. this.computeWorldMatrix(true);
  17926. var boundingInfo = this.getBoundingInfo();
  17927. // Update octree
  17928. var bbox = boundingInfo.boundingBox;
  17929. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  17930. return this._submeshesOctree;
  17931. };
  17932. // Collisions
  17933. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  17934. this._generatePointsArray();
  17935. if (!this._positions) {
  17936. return this;
  17937. }
  17938. // Transformation
  17939. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  17940. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  17941. subMesh._lastColliderWorldVertices = [];
  17942. subMesh._trianglePlanes = [];
  17943. var start = subMesh.verticesStart;
  17944. var end = (subMesh.verticesStart + subMesh.verticesCount);
  17945. for (var i = start; i < end; i++) {
  17946. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  17947. }
  17948. }
  17949. // Collide
  17950. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  17951. if (collider.collisionFound) {
  17952. collider.collidedMesh = this;
  17953. }
  17954. return this;
  17955. };
  17956. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  17957. var subMeshes;
  17958. var len;
  17959. // Octrees
  17960. if (this._submeshesOctree && this.useOctreeForCollisions) {
  17961. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  17962. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  17963. len = intersections.length;
  17964. subMeshes = intersections.data;
  17965. }
  17966. else {
  17967. subMeshes = this.subMeshes;
  17968. len = subMeshes.length;
  17969. }
  17970. for (var index = 0; index < len; index++) {
  17971. var subMesh = subMeshes[index];
  17972. // Bounding test
  17973. if (len > 1 && !subMesh._checkCollision(collider))
  17974. continue;
  17975. this._collideForSubMesh(subMesh, transformMatrix, collider);
  17976. }
  17977. return this;
  17978. };
  17979. AbstractMesh.prototype._checkCollision = function (collider) {
  17980. // Bounding box test
  17981. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  17982. return this;
  17983. // Transformation matrix
  17984. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  17985. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  17986. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  17987. return this;
  17988. };
  17989. // Picking
  17990. AbstractMesh.prototype._generatePointsArray = function () {
  17991. return false;
  17992. };
  17993. /**
  17994. * Checks if the passed Ray intersects with the mesh.
  17995. * Returns an object PickingInfo.
  17996. */
  17997. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  17998. var pickingInfo = new BABYLON.PickingInfo();
  17999. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18000. return pickingInfo;
  18001. }
  18002. if (!this._generatePointsArray()) {
  18003. return pickingInfo;
  18004. }
  18005. var intersectInfo = null;
  18006. // Octrees
  18007. var subMeshes;
  18008. var len;
  18009. if (this._submeshesOctree && this.useOctreeForPicking) {
  18010. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18011. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18012. len = intersections.length;
  18013. subMeshes = intersections.data;
  18014. }
  18015. else {
  18016. subMeshes = this.subMeshes;
  18017. len = subMeshes.length;
  18018. }
  18019. for (var index = 0; index < len; index++) {
  18020. var subMesh = subMeshes[index];
  18021. // Bounding test
  18022. if (len > 1 && !subMesh.canIntersects(ray))
  18023. continue;
  18024. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18025. if (currentIntersectInfo) {
  18026. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18027. intersectInfo = currentIntersectInfo;
  18028. intersectInfo.subMeshId = index;
  18029. if (fastCheck) {
  18030. break;
  18031. }
  18032. }
  18033. }
  18034. }
  18035. if (intersectInfo) {
  18036. // Get picked point
  18037. var world = this.getWorldMatrix();
  18038. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18039. var direction = ray.direction.clone();
  18040. direction = direction.scale(intersectInfo.distance);
  18041. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18042. var pickedPoint = worldOrigin.add(worldDirection);
  18043. // Return result
  18044. pickingInfo.hit = true;
  18045. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18046. pickingInfo.pickedPoint = pickedPoint;
  18047. pickingInfo.pickedMesh = this;
  18048. pickingInfo.bu = intersectInfo.bu || 0;
  18049. pickingInfo.bv = intersectInfo.bv || 0;
  18050. pickingInfo.faceId = intersectInfo.faceId;
  18051. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18052. return pickingInfo;
  18053. }
  18054. return pickingInfo;
  18055. };
  18056. /**
  18057. * Clones the mesh, used by the class Mesh.
  18058. * Just returns `null` for an AbstractMesh.
  18059. */
  18060. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18061. return null;
  18062. };
  18063. /**
  18064. * Disposes all the mesh submeshes.
  18065. * Returns the AbstractMesh.
  18066. */
  18067. AbstractMesh.prototype.releaseSubMeshes = function () {
  18068. if (this.subMeshes) {
  18069. while (this.subMeshes.length) {
  18070. this.subMeshes[0].dispose();
  18071. }
  18072. }
  18073. else {
  18074. this.subMeshes = new Array();
  18075. }
  18076. return this;
  18077. };
  18078. /**
  18079. * Disposes the AbstractMesh.
  18080. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  18081. * Returns nothing.
  18082. */
  18083. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18084. var _this = this;
  18085. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18086. var index;
  18087. // Action manager
  18088. if (this.actionManager !== undefined && this.actionManager !== null) {
  18089. this.actionManager.dispose();
  18090. this.actionManager = null;
  18091. }
  18092. // Skeleton
  18093. this.skeleton = null;
  18094. // Physics
  18095. if (this.physicsImpostor) {
  18096. this.physicsImpostor.dispose();
  18097. }
  18098. // Intersections in progress
  18099. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18100. var other = this._intersectionsInProgress[index];
  18101. var pos = other._intersectionsInProgress.indexOf(this);
  18102. other._intersectionsInProgress.splice(pos, 1);
  18103. }
  18104. this._intersectionsInProgress = [];
  18105. // Lights
  18106. var lights = this.getScene().lights;
  18107. lights.forEach(function (light) {
  18108. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18109. if (meshIndex !== -1) {
  18110. light.includedOnlyMeshes.splice(meshIndex, 1);
  18111. }
  18112. meshIndex = light.excludedMeshes.indexOf(_this);
  18113. if (meshIndex !== -1) {
  18114. light.excludedMeshes.splice(meshIndex, 1);
  18115. }
  18116. // Shadow generators
  18117. var generator = light.getShadowGenerator();
  18118. if (generator) {
  18119. var shadowMap = generator.getShadowMap();
  18120. if (shadowMap && shadowMap.renderList) {
  18121. meshIndex = shadowMap.renderList.indexOf(_this);
  18122. if (meshIndex !== -1) {
  18123. shadowMap.renderList.splice(meshIndex, 1);
  18124. }
  18125. }
  18126. }
  18127. });
  18128. // Edges
  18129. if (this._edgesRenderer) {
  18130. this._edgesRenderer.dispose();
  18131. this._edgesRenderer = null;
  18132. }
  18133. // SubMeshes
  18134. if (this.getClassName() !== "InstancedMesh") {
  18135. this.releaseSubMeshes();
  18136. }
  18137. // Octree
  18138. var sceneOctree = this.getScene().selectionOctree;
  18139. if (sceneOctree !== undefined && sceneOctree !== null) {
  18140. var index = sceneOctree.dynamicContent.indexOf(this);
  18141. if (index !== -1) {
  18142. sceneOctree.dynamicContent.splice(index, 1);
  18143. }
  18144. }
  18145. // Query
  18146. var engine = this.getScene().getEngine();
  18147. if (this._occlusionQuery) {
  18148. this._isOcclusionQueryInProgress = false;
  18149. engine.deleteQuery(this._occlusionQuery);
  18150. this._occlusionQuery = null;
  18151. }
  18152. // Engine
  18153. engine.wipeCaches();
  18154. // Remove from scene
  18155. this.getScene().removeMesh(this);
  18156. if (disposeMaterialAndTextures) {
  18157. if (this.material) {
  18158. this.material.dispose(false, true);
  18159. }
  18160. }
  18161. if (!doNotRecurse) {
  18162. // Particles
  18163. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18164. if (this.getScene().particleSystems[index].emitter === this) {
  18165. this.getScene().particleSystems[index].dispose();
  18166. index--;
  18167. }
  18168. }
  18169. }
  18170. // facet data
  18171. if (this._facetDataEnabled) {
  18172. this.disableFacetData();
  18173. }
  18174. this.onAfterWorldMatrixUpdateObservable.clear();
  18175. this.onCollideObservable.clear();
  18176. this.onCollisionPositionChangeObservable.clear();
  18177. _super.prototype.dispose.call(this, doNotRecurse);
  18178. };
  18179. /**
  18180. * Adds the passed mesh as a child to the current mesh.
  18181. * Returns the AbstractMesh.
  18182. */
  18183. AbstractMesh.prototype.addChild = function (mesh) {
  18184. mesh.setParent(this);
  18185. return this;
  18186. };
  18187. /**
  18188. * Removes the passed mesh from the current mesh children list.
  18189. * Returns the AbstractMesh.
  18190. */
  18191. AbstractMesh.prototype.removeChild = function (mesh) {
  18192. mesh.setParent(null);
  18193. return this;
  18194. };
  18195. // Facet data
  18196. /**
  18197. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18198. * Returns the AbstractMesh.
  18199. */
  18200. AbstractMesh.prototype._initFacetData = function () {
  18201. if (!this._facetNormals) {
  18202. this._facetNormals = new Array();
  18203. }
  18204. if (!this._facetPositions) {
  18205. this._facetPositions = new Array();
  18206. }
  18207. if (!this._facetPartitioning) {
  18208. this._facetPartitioning = new Array();
  18209. }
  18210. this._facetNb = (this.getIndices().length / 3) | 0;
  18211. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18212. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18213. for (var f = 0; f < this._facetNb; f++) {
  18214. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18215. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18216. }
  18217. this._facetDataEnabled = true;
  18218. return this;
  18219. };
  18220. /**
  18221. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18222. * This method can be called within the render loop.
  18223. * 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.
  18224. * Returns the AbstractMesh.
  18225. */
  18226. AbstractMesh.prototype.updateFacetData = function () {
  18227. if (!this._facetDataEnabled) {
  18228. this._initFacetData();
  18229. }
  18230. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18231. var indices = this.getIndices();
  18232. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18233. var bInfo = this.getBoundingInfo();
  18234. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18235. // init arrays, matrix and sort function on first call
  18236. this._facetDepthSortEnabled = true;
  18237. if (indices instanceof Uint16Array) {
  18238. this._depthSortedIndices = new Uint16Array(indices);
  18239. }
  18240. else if (indices instanceof Uint32Array) {
  18241. this._depthSortedIndices = new Uint32Array(indices);
  18242. }
  18243. else {
  18244. var needs32bits = false;
  18245. for (var i = 0; i < indices.length; i++) {
  18246. if (indices[i] > 65535) {
  18247. needs32bits = true;
  18248. break;
  18249. }
  18250. }
  18251. if (needs32bits) {
  18252. this._depthSortedIndices = new Uint32Array(indices);
  18253. }
  18254. else {
  18255. this._depthSortedIndices = new Uint16Array(indices);
  18256. }
  18257. }
  18258. this._facetDepthSortFunction = function (f1, f2) {
  18259. return (f2.sqDistance - f1.sqDistance);
  18260. };
  18261. if (!this._facetDepthSortFrom) {
  18262. var camera = this.getScene().activeCamera;
  18263. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18264. }
  18265. this._depthSortedFacets = [];
  18266. for (var f = 0; f < this._facetNb; f++) {
  18267. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18268. this._depthSortedFacets.push(depthSortedFacet);
  18269. }
  18270. this._invertedMatrix = BABYLON.Matrix.Identity();
  18271. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18272. }
  18273. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18274. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18275. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18276. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18277. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18278. this._subDiv.max = this._partitioningSubdivisions;
  18279. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18280. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18281. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18282. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18283. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18284. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18285. // set the parameters for ComputeNormals()
  18286. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18287. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18288. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18289. this._facetParameters.bInfo = bInfo;
  18290. this._facetParameters.bbSize = this._bbSize;
  18291. this._facetParameters.subDiv = this._subDiv;
  18292. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18293. this._facetParameters.depthSort = this._facetDepthSort;
  18294. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18295. this.computeWorldMatrix(true);
  18296. this._worldMatrix.invertToRef(this._invertedMatrix);
  18297. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18298. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18299. }
  18300. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18301. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18302. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18303. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18304. var l = (this._depthSortedIndices.length / 3) | 0;
  18305. for (var f = 0; f < l; f++) {
  18306. var sind = this._depthSortedFacets[f].ind;
  18307. this._depthSortedIndices[f * 3] = indices[sind];
  18308. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18309. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18310. }
  18311. this.updateIndices(this._depthSortedIndices);
  18312. }
  18313. return this;
  18314. };
  18315. /**
  18316. * Returns the facetLocalNormals array.
  18317. * The normals are expressed in the mesh local space.
  18318. */
  18319. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18320. if (!this._facetNormals) {
  18321. this.updateFacetData();
  18322. }
  18323. return this._facetNormals;
  18324. };
  18325. /**
  18326. * Returns the facetLocalPositions array.
  18327. * The facet positions are expressed in the mesh local space.
  18328. */
  18329. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18330. if (!this._facetPositions) {
  18331. this.updateFacetData();
  18332. }
  18333. return this._facetPositions;
  18334. };
  18335. /**
  18336. * Returns the facetLocalPartioning array.
  18337. */
  18338. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18339. if (!this._facetPartitioning) {
  18340. this.updateFacetData();
  18341. }
  18342. return this._facetPartitioning;
  18343. };
  18344. /**
  18345. * Returns the i-th facet position in the world system.
  18346. * This method allocates a new Vector3 per call.
  18347. */
  18348. AbstractMesh.prototype.getFacetPosition = function (i) {
  18349. var pos = BABYLON.Vector3.Zero();
  18350. this.getFacetPositionToRef(i, pos);
  18351. return pos;
  18352. };
  18353. /**
  18354. * Sets the reference Vector3 with the i-th facet position in the world system.
  18355. * Returns the AbstractMesh.
  18356. */
  18357. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  18358. var localPos = (this.getFacetLocalPositions())[i];
  18359. var world = this.getWorldMatrix();
  18360. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  18361. return this;
  18362. };
  18363. /**
  18364. * Returns the i-th facet normal in the world system.
  18365. * This method allocates a new Vector3 per call.
  18366. */
  18367. AbstractMesh.prototype.getFacetNormal = function (i) {
  18368. var norm = BABYLON.Vector3.Zero();
  18369. this.getFacetNormalToRef(i, norm);
  18370. return norm;
  18371. };
  18372. /**
  18373. * Sets the reference Vector3 with the i-th facet normal in the world system.
  18374. * Returns the AbstractMesh.
  18375. */
  18376. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  18377. var localNorm = (this.getFacetLocalNormals())[i];
  18378. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  18379. return this;
  18380. };
  18381. /**
  18382. * 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).
  18383. */
  18384. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  18385. var bInfo = this.getBoundingInfo();
  18386. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  18387. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  18388. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  18389. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  18390. return null;
  18391. }
  18392. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  18393. };
  18394. /**
  18395. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  18396. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  18397. * If checkFace is 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.
  18398. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18399. * 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.
  18400. */
  18401. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  18402. if (checkFace === void 0) { checkFace = false; }
  18403. if (facing === void 0) { facing = true; }
  18404. var world = this.getWorldMatrix();
  18405. var invMat = BABYLON.Tmp.Matrix[5];
  18406. world.invertToRef(invMat);
  18407. var invVect = BABYLON.Tmp.Vector3[8];
  18408. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  18409. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  18410. if (projected) {
  18411. // tranform the local computed projected vector to world coordinates
  18412. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  18413. }
  18414. return closest;
  18415. };
  18416. /**
  18417. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  18418. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  18419. * If checkFace is 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.
  18420. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  18421. * 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.
  18422. */
  18423. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  18424. if (checkFace === void 0) { checkFace = false; }
  18425. if (facing === void 0) { facing = true; }
  18426. var closest = null;
  18427. var tmpx = 0.0;
  18428. var tmpy = 0.0;
  18429. var tmpz = 0.0;
  18430. var d = 0.0; // tmp dot facet normal * facet position
  18431. var t0 = 0.0;
  18432. var projx = 0.0;
  18433. var projy = 0.0;
  18434. var projz = 0.0;
  18435. // Get all the facets in the same partitioning block than (x, y, z)
  18436. var facetPositions = this.getFacetLocalPositions();
  18437. var facetNormals = this.getFacetLocalNormals();
  18438. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  18439. if (!facetsInBlock) {
  18440. return null;
  18441. }
  18442. // Get the closest facet to (x, y, z)
  18443. var shortest = Number.MAX_VALUE; // init distance vars
  18444. var tmpDistance = shortest;
  18445. var fib; // current facet in the block
  18446. var norm; // current facet normal
  18447. var p0; // current facet barycenter position
  18448. // loop on all the facets in the current partitioning block
  18449. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  18450. fib = facetsInBlock[idx];
  18451. norm = facetNormals[fib];
  18452. p0 = facetPositions[fib];
  18453. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  18454. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  18455. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  18456. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  18457. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  18458. projx = x + norm.x * t0;
  18459. projy = y + norm.y * t0;
  18460. projz = z + norm.z * t0;
  18461. tmpx = projx - x;
  18462. tmpy = projy - y;
  18463. tmpz = projz - z;
  18464. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  18465. if (tmpDistance < shortest) {
  18466. shortest = tmpDistance;
  18467. closest = fib;
  18468. if (projected) {
  18469. projected.x = projx;
  18470. projected.y = projy;
  18471. projected.z = projz;
  18472. }
  18473. }
  18474. }
  18475. }
  18476. return closest;
  18477. };
  18478. /**
  18479. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  18480. */
  18481. AbstractMesh.prototype.getFacetDataParameters = function () {
  18482. return this._facetParameters;
  18483. };
  18484. /**
  18485. * Disables the feature FacetData and frees the related memory.
  18486. * Returns the AbstractMesh.
  18487. */
  18488. AbstractMesh.prototype.disableFacetData = function () {
  18489. if (this._facetDataEnabled) {
  18490. this._facetDataEnabled = false;
  18491. this._facetPositions = new Array();
  18492. this._facetNormals = new Array();
  18493. this._facetPartitioning = new Array();
  18494. this._facetParameters = null;
  18495. this._depthSortedIndices = new Uint32Array(0);
  18496. }
  18497. return this;
  18498. };
  18499. /**
  18500. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  18501. * Returns the mesh.
  18502. */
  18503. AbstractMesh.prototype.updateIndices = function (indices) {
  18504. return this;
  18505. };
  18506. /**
  18507. * The mesh Geometry. Actually used by the Mesh object.
  18508. * Returns a blank geometry object.
  18509. */
  18510. /**
  18511. * Creates new normals data for the mesh.
  18512. * @param updatable.
  18513. */
  18514. AbstractMesh.prototype.createNormals = function (updatable) {
  18515. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18516. var indices = this.getIndices();
  18517. var normals;
  18518. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18519. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18520. }
  18521. else {
  18522. normals = [];
  18523. }
  18524. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  18525. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  18526. };
  18527. /**
  18528. * Align the mesh with a normal.
  18529. * Returns the mesh.
  18530. */
  18531. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  18532. if (!upDirection) {
  18533. upDirection = BABYLON.Axis.Y;
  18534. }
  18535. var axisX = BABYLON.Tmp.Vector3[0];
  18536. var axisZ = BABYLON.Tmp.Vector3[1];
  18537. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  18538. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  18539. if (this.rotationQuaternion) {
  18540. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  18541. }
  18542. else {
  18543. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  18544. }
  18545. return this;
  18546. };
  18547. AbstractMesh.prototype.checkOcclusionQuery = function () {
  18548. var engine = this.getEngine();
  18549. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  18550. this._isOccluded = false;
  18551. return;
  18552. }
  18553. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  18554. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  18555. if (isOcclusionQueryAvailable) {
  18556. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  18557. this._isOcclusionQueryInProgress = false;
  18558. this._occlusionInternalRetryCounter = 0;
  18559. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  18560. }
  18561. else {
  18562. this._occlusionInternalRetryCounter++;
  18563. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  18564. this._isOcclusionQueryInProgress = false;
  18565. this._occlusionInternalRetryCounter = 0;
  18566. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  18567. // if strict continue the last state of the object.
  18568. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  18569. }
  18570. else {
  18571. return;
  18572. }
  18573. }
  18574. }
  18575. var scene = this.getScene();
  18576. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  18577. if (!this._occlusionQuery) {
  18578. this._occlusionQuery = engine.createQuery();
  18579. }
  18580. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  18581. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  18582. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  18583. this._isOcclusionQueryInProgress = true;
  18584. };
  18585. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  18586. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  18587. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  18588. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  18589. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  18590. return AbstractMesh;
  18591. }(BABYLON.TransformNode));
  18592. BABYLON.AbstractMesh = AbstractMesh;
  18593. })(BABYLON || (BABYLON = {}));
  18594. //# sourceMappingURL=babylon.abstractMesh.js.map
  18595. var BABYLON;
  18596. (function (BABYLON) {
  18597. /**
  18598. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  18599. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  18600. * 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.
  18601. */
  18602. var Light = /** @class */ (function (_super) {
  18603. __extends(Light, _super);
  18604. /**
  18605. * Creates a Light object in the scene.
  18606. * Documentation : http://doc.babylonjs.com/tutorials/lights
  18607. * @param name The firendly name of the light
  18608. * @param scene The scene the light belongs too
  18609. */
  18610. function Light(name, scene) {
  18611. var _this = _super.call(this, name, scene) || this;
  18612. /**
  18613. * Diffuse gives the basic color to an object.
  18614. */
  18615. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  18616. /**
  18617. * Specular produces a highlight color on an object.
  18618. * Note: This is note affecting PBR materials.
  18619. */
  18620. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  18621. /**
  18622. * Strength of the light.
  18623. * Note: By default it is define in the framework own unit.
  18624. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  18625. */
  18626. _this.intensity = 1.0;
  18627. /**
  18628. * Defines how far from the source the light is impacting in scene units.
  18629. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  18630. */
  18631. _this.range = Number.MAX_VALUE;
  18632. /**
  18633. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  18634. * of light.
  18635. */
  18636. _this._photometricScale = 1.0;
  18637. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  18638. _this._radius = 0.00001;
  18639. /**
  18640. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  18641. * exceeding the number allowed of the materials.
  18642. */
  18643. _this.renderPriority = 0;
  18644. /**
  18645. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  18646. * the current shadow generator.
  18647. */
  18648. _this.shadowEnabled = true;
  18649. _this._excludeWithLayerMask = 0;
  18650. _this._includeOnlyWithLayerMask = 0;
  18651. _this._lightmapMode = 0;
  18652. /**
  18653. * @ignore Internal use only.
  18654. */
  18655. _this._excludedMeshesIds = new Array();
  18656. /**
  18657. * @ignore Internal use only.
  18658. */
  18659. _this._includedOnlyMeshesIds = new Array();
  18660. _this.getScene().addLight(_this);
  18661. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  18662. _this._buildUniformLayout();
  18663. _this.includedOnlyMeshes = new Array();
  18664. _this.excludedMeshes = new Array();
  18665. _this._resyncMeshes();
  18666. return _this;
  18667. }
  18668. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  18669. /**
  18670. * If every light affecting the material is in this lightmapMode,
  18671. * material.lightmapTexture adds or multiplies
  18672. * (depends on material.useLightmapAsShadowmap)
  18673. * after every other light calculations.
  18674. */
  18675. get: function () {
  18676. return Light._LIGHTMAP_DEFAULT;
  18677. },
  18678. enumerable: true,
  18679. configurable: true
  18680. });
  18681. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  18682. /**
  18683. * material.lightmapTexture as only diffuse lighting from this light
  18684. * adds only specular lighting from this light
  18685. * adds dynamic shadows
  18686. */
  18687. get: function () {
  18688. return Light._LIGHTMAP_SPECULAR;
  18689. },
  18690. enumerable: true,
  18691. configurable: true
  18692. });
  18693. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  18694. /**
  18695. * material.lightmapTexture as only lighting
  18696. * no light calculation from this light
  18697. * only adds dynamic shadows from this light
  18698. */
  18699. get: function () {
  18700. return Light._LIGHTMAP_SHADOWSONLY;
  18701. },
  18702. enumerable: true,
  18703. configurable: true
  18704. });
  18705. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  18706. /**
  18707. * Each light type uses the default quantity according to its type:
  18708. * point/spot lights use luminous intensity
  18709. * directional lights use illuminance
  18710. */
  18711. get: function () {
  18712. return Light._INTENSITYMODE_AUTOMATIC;
  18713. },
  18714. enumerable: true,
  18715. configurable: true
  18716. });
  18717. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  18718. /**
  18719. * lumen (lm)
  18720. */
  18721. get: function () {
  18722. return Light._INTENSITYMODE_LUMINOUSPOWER;
  18723. },
  18724. enumerable: true,
  18725. configurable: true
  18726. });
  18727. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  18728. /**
  18729. * candela (lm/sr)
  18730. */
  18731. get: function () {
  18732. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  18733. },
  18734. enumerable: true,
  18735. configurable: true
  18736. });
  18737. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  18738. /**
  18739. * lux (lm/m^2)
  18740. */
  18741. get: function () {
  18742. return Light._INTENSITYMODE_ILLUMINANCE;
  18743. },
  18744. enumerable: true,
  18745. configurable: true
  18746. });
  18747. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  18748. /**
  18749. * nit (cd/m^2)
  18750. */
  18751. get: function () {
  18752. return Light._INTENSITYMODE_LUMINANCE;
  18753. },
  18754. enumerable: true,
  18755. configurable: true
  18756. });
  18757. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  18758. /**
  18759. * Light type const id of the point light.
  18760. */
  18761. get: function () {
  18762. return Light._LIGHTTYPEID_POINTLIGHT;
  18763. },
  18764. enumerable: true,
  18765. configurable: true
  18766. });
  18767. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  18768. /**
  18769. * Light type const id of the directional light.
  18770. */
  18771. get: function () {
  18772. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  18773. },
  18774. enumerable: true,
  18775. configurable: true
  18776. });
  18777. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  18778. /**
  18779. * Light type const id of the spot light.
  18780. */
  18781. get: function () {
  18782. return Light._LIGHTTYPEID_SPOTLIGHT;
  18783. },
  18784. enumerable: true,
  18785. configurable: true
  18786. });
  18787. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  18788. /**
  18789. * Light type const id of the hemispheric light.
  18790. */
  18791. get: function () {
  18792. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  18793. },
  18794. enumerable: true,
  18795. configurable: true
  18796. });
  18797. Object.defineProperty(Light.prototype, "intensityMode", {
  18798. /**
  18799. * Gets the photometric scale used to interpret the intensity.
  18800. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18801. */
  18802. get: function () {
  18803. return this._intensityMode;
  18804. },
  18805. /**
  18806. * Sets the photometric scale used to interpret the intensity.
  18807. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  18808. */
  18809. set: function (value) {
  18810. this._intensityMode = value;
  18811. this._computePhotometricScale();
  18812. },
  18813. enumerable: true,
  18814. configurable: true
  18815. });
  18816. ;
  18817. ;
  18818. Object.defineProperty(Light.prototype, "radius", {
  18819. /**
  18820. * Gets the light radius used by PBR Materials to simulate soft area lights.
  18821. */
  18822. get: function () {
  18823. return this._radius;
  18824. },
  18825. /**
  18826. * sets the light radius used by PBR Materials to simulate soft area lights.
  18827. */
  18828. set: function (value) {
  18829. this._radius = value;
  18830. this._computePhotometricScale();
  18831. },
  18832. enumerable: true,
  18833. configurable: true
  18834. });
  18835. ;
  18836. ;
  18837. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  18838. /**
  18839. * Gets the only meshes impacted by this light.
  18840. */
  18841. get: function () {
  18842. return this._includedOnlyMeshes;
  18843. },
  18844. /**
  18845. * Sets the only meshes impacted by this light.
  18846. */
  18847. set: function (value) {
  18848. this._includedOnlyMeshes = value;
  18849. this._hookArrayForIncludedOnly(value);
  18850. },
  18851. enumerable: true,
  18852. configurable: true
  18853. });
  18854. Object.defineProperty(Light.prototype, "excludedMeshes", {
  18855. /**
  18856. * Gets the meshes not impacted by this light.
  18857. */
  18858. get: function () {
  18859. return this._excludedMeshes;
  18860. },
  18861. /**
  18862. * Sets the meshes not impacted by this light.
  18863. */
  18864. set: function (value) {
  18865. this._excludedMeshes = value;
  18866. this._hookArrayForExcluded(value);
  18867. },
  18868. enumerable: true,
  18869. configurable: true
  18870. });
  18871. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  18872. /**
  18873. * Gets the layer id use to find what meshes are not impacted by the light.
  18874. * Inactive if 0
  18875. */
  18876. get: function () {
  18877. return this._excludeWithLayerMask;
  18878. },
  18879. /**
  18880. * Sets the layer id use to find what meshes are not impacted by the light.
  18881. * Inactive if 0
  18882. */
  18883. set: function (value) {
  18884. this._excludeWithLayerMask = value;
  18885. this._resyncMeshes();
  18886. },
  18887. enumerable: true,
  18888. configurable: true
  18889. });
  18890. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  18891. /**
  18892. * Gets the layer id use to find what meshes are impacted by the light.
  18893. * Inactive if 0
  18894. */
  18895. get: function () {
  18896. return this._includeOnlyWithLayerMask;
  18897. },
  18898. /**
  18899. * Sets the layer id use to find what meshes are impacted by the light.
  18900. * Inactive if 0
  18901. */
  18902. set: function (value) {
  18903. this._includeOnlyWithLayerMask = value;
  18904. this._resyncMeshes();
  18905. },
  18906. enumerable: true,
  18907. configurable: true
  18908. });
  18909. Object.defineProperty(Light.prototype, "lightmapMode", {
  18910. /**
  18911. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18912. */
  18913. get: function () {
  18914. return this._lightmapMode;
  18915. },
  18916. /**
  18917. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  18918. */
  18919. set: function (value) {
  18920. if (this._lightmapMode === value) {
  18921. return;
  18922. }
  18923. this._lightmapMode = value;
  18924. this._markMeshesAsLightDirty();
  18925. },
  18926. enumerable: true,
  18927. configurable: true
  18928. });
  18929. /**
  18930. * Returns the string "Light".
  18931. * @returns the class name
  18932. */
  18933. Light.prototype.getClassName = function () {
  18934. return "Light";
  18935. };
  18936. /**
  18937. * Converts the light information to a readable string for debug purpose.
  18938. * @param fullDetails Supports for multiple levels of logging within scene loading
  18939. * @returns the human readable light info
  18940. */
  18941. Light.prototype.toString = function (fullDetails) {
  18942. var ret = "Name: " + this.name;
  18943. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  18944. if (this.animations) {
  18945. for (var i = 0; i < this.animations.length; i++) {
  18946. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  18947. }
  18948. }
  18949. if (fullDetails) {
  18950. }
  18951. return ret;
  18952. };
  18953. /**
  18954. * Set the enabled state of this node.
  18955. * @param value - the new enabled state
  18956. * @see isEnabled
  18957. */
  18958. Light.prototype.setEnabled = function (value) {
  18959. _super.prototype.setEnabled.call(this, value);
  18960. this._resyncMeshes();
  18961. };
  18962. /**
  18963. * Returns the Light associated shadow generator if any.
  18964. * @return the associated shadow generator.
  18965. */
  18966. Light.prototype.getShadowGenerator = function () {
  18967. return this._shadowGenerator;
  18968. };
  18969. /**
  18970. * Returns a Vector3, the absolute light position in the World.
  18971. * @returns the world space position of the light
  18972. */
  18973. Light.prototype.getAbsolutePosition = function () {
  18974. return BABYLON.Vector3.Zero();
  18975. };
  18976. /**
  18977. * Specifies if the light will affect the passed mesh.
  18978. * @param mesh The mesh to test against the light
  18979. * @return true the mesh is affected otherwise, false.
  18980. */
  18981. Light.prototype.canAffectMesh = function (mesh) {
  18982. if (!mesh) {
  18983. return true;
  18984. }
  18985. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  18986. return false;
  18987. }
  18988. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  18989. return false;
  18990. }
  18991. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  18992. return false;
  18993. }
  18994. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  18995. return false;
  18996. }
  18997. return true;
  18998. };
  18999. /**
  19000. * Computes and Returns the light World matrix.
  19001. * @returns the world matrix
  19002. */
  19003. Light.prototype.getWorldMatrix = function () {
  19004. this._currentRenderId = this.getScene().getRenderId();
  19005. var worldMatrix = this._getWorldMatrix();
  19006. if (this.parent && this.parent.getWorldMatrix) {
  19007. if (!this._parentedWorldMatrix) {
  19008. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19009. }
  19010. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19011. this._markSyncedWithParent();
  19012. return this._parentedWorldMatrix;
  19013. }
  19014. return worldMatrix;
  19015. };
  19016. /**
  19017. * Sort function to order lights for rendering.
  19018. * @param a First Light object to compare to second.
  19019. * @param b Second Light object to compare first.
  19020. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19021. */
  19022. Light.CompareLightsPriority = function (a, b) {
  19023. //shadow-casting lights have priority over non-shadow-casting lights
  19024. //the renderPrioirty is a secondary sort criterion
  19025. if (a.shadowEnabled !== b.shadowEnabled) {
  19026. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19027. }
  19028. return b.renderPriority - a.renderPriority;
  19029. };
  19030. /**
  19031. * Disposes the light.
  19032. */
  19033. Light.prototype.dispose = function () {
  19034. if (this._shadowGenerator) {
  19035. this._shadowGenerator.dispose();
  19036. this._shadowGenerator = null;
  19037. }
  19038. // Animations
  19039. this.getScene().stopAnimation(this);
  19040. // Remove from meshes
  19041. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19042. var mesh = _a[_i];
  19043. mesh._removeLightSource(this);
  19044. }
  19045. this._uniformBuffer.dispose();
  19046. // Remove from scene
  19047. this.getScene().removeLight(this);
  19048. _super.prototype.dispose.call(this);
  19049. };
  19050. /**
  19051. * Returns the light type ID (integer).
  19052. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19053. */
  19054. Light.prototype.getTypeID = function () {
  19055. return 0;
  19056. };
  19057. /**
  19058. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19059. * @returns the scaled intensity in intensity mode unit
  19060. */
  19061. Light.prototype.getScaledIntensity = function () {
  19062. return this._photometricScale * this.intensity;
  19063. };
  19064. /**
  19065. * Returns a new Light object, named "name", from the current one.
  19066. * @param name The name of the cloned light
  19067. * @returns the new created light
  19068. */
  19069. Light.prototype.clone = function (name) {
  19070. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19071. if (!constructor) {
  19072. return null;
  19073. }
  19074. return BABYLON.SerializationHelper.Clone(constructor, this);
  19075. };
  19076. /**
  19077. * Serializes the current light into a Serialization object.
  19078. * @returns the serialized object.
  19079. */
  19080. Light.prototype.serialize = function () {
  19081. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19082. // Type
  19083. serializationObject.type = this.getTypeID();
  19084. // Parent
  19085. if (this.parent) {
  19086. serializationObject.parentId = this.parent.id;
  19087. }
  19088. // Inclusion / exclusions
  19089. if (this.excludedMeshes.length > 0) {
  19090. serializationObject.excludedMeshesIds = [];
  19091. this.excludedMeshes.forEach(function (mesh) {
  19092. serializationObject.excludedMeshesIds.push(mesh.id);
  19093. });
  19094. }
  19095. if (this.includedOnlyMeshes.length > 0) {
  19096. serializationObject.includedOnlyMeshesIds = [];
  19097. this.includedOnlyMeshes.forEach(function (mesh) {
  19098. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19099. });
  19100. }
  19101. // Animations
  19102. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19103. serializationObject.ranges = this.serializeAnimationRanges();
  19104. return serializationObject;
  19105. };
  19106. /**
  19107. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19108. * This new light is named "name" and added to the passed scene.
  19109. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19110. * @param name The friendly name of the light
  19111. * @param scene The scene the new light will belong to
  19112. * @returns the constructor function
  19113. */
  19114. Light.GetConstructorFromName = function (type, name, scene) {
  19115. switch (type) {
  19116. case 0:
  19117. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19118. case 1:
  19119. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19120. case 2:
  19121. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19122. case 3:
  19123. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19124. }
  19125. return null;
  19126. };
  19127. /**
  19128. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19129. * @param parsedLight The JSON representation of the light
  19130. * @param scene The scene to create the parsed light in
  19131. * @returns the created light after parsing
  19132. */
  19133. Light.Parse = function (parsedLight, scene) {
  19134. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19135. if (!constructor) {
  19136. return null;
  19137. }
  19138. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19139. // Inclusion / exclusions
  19140. if (parsedLight.excludedMeshesIds) {
  19141. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19142. }
  19143. if (parsedLight.includedOnlyMeshesIds) {
  19144. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19145. }
  19146. // Parent
  19147. if (parsedLight.parentId) {
  19148. light._waitingParentId = parsedLight.parentId;
  19149. }
  19150. // Animations
  19151. if (parsedLight.animations) {
  19152. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19153. var parsedAnimation = parsedLight.animations[animationIndex];
  19154. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19155. }
  19156. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19157. }
  19158. if (parsedLight.autoAnimate) {
  19159. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19160. }
  19161. return light;
  19162. };
  19163. Light.prototype._hookArrayForExcluded = function (array) {
  19164. var _this = this;
  19165. var oldPush = array.push;
  19166. array.push = function () {
  19167. var items = [];
  19168. for (var _i = 0; _i < arguments.length; _i++) {
  19169. items[_i] = arguments[_i];
  19170. }
  19171. var result = oldPush.apply(array, items);
  19172. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19173. var item = items_1[_a];
  19174. item._resyncLighSource(_this);
  19175. }
  19176. return result;
  19177. };
  19178. var oldSplice = array.splice;
  19179. array.splice = function (index, deleteCount) {
  19180. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19181. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19182. var item = deleted_1[_i];
  19183. item._resyncLighSource(_this);
  19184. }
  19185. return deleted;
  19186. };
  19187. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19188. var item = array_1[_i];
  19189. item._resyncLighSource(this);
  19190. }
  19191. };
  19192. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19193. var _this = this;
  19194. var oldPush = array.push;
  19195. array.push = function () {
  19196. var items = [];
  19197. for (var _i = 0; _i < arguments.length; _i++) {
  19198. items[_i] = arguments[_i];
  19199. }
  19200. var result = oldPush.apply(array, items);
  19201. _this._resyncMeshes();
  19202. return result;
  19203. };
  19204. var oldSplice = array.splice;
  19205. array.splice = function (index, deleteCount) {
  19206. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19207. _this._resyncMeshes();
  19208. return deleted;
  19209. };
  19210. this._resyncMeshes();
  19211. };
  19212. Light.prototype._resyncMeshes = function () {
  19213. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19214. var mesh = _a[_i];
  19215. mesh._resyncLighSource(this);
  19216. }
  19217. };
  19218. /**
  19219. * Forces the meshes to update their light related information in their rendering used effects
  19220. * @ignore Internal Use Only
  19221. */
  19222. Light.prototype._markMeshesAsLightDirty = function () {
  19223. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19224. var mesh = _a[_i];
  19225. if (mesh._lightSources.indexOf(this) !== -1) {
  19226. mesh._markSubMeshesAsLightDirty();
  19227. }
  19228. }
  19229. };
  19230. /**
  19231. * Recomputes the cached photometric scale if needed.
  19232. */
  19233. Light.prototype._computePhotometricScale = function () {
  19234. this._photometricScale = this._getPhotometricScale();
  19235. this.getScene().resetCachedMaterial();
  19236. };
  19237. /**
  19238. * Returns the Photometric Scale according to the light type and intensity mode.
  19239. */
  19240. Light.prototype._getPhotometricScale = function () {
  19241. var photometricScale = 0.0;
  19242. var lightTypeID = this.getTypeID();
  19243. //get photometric mode
  19244. var photometricMode = this.intensityMode;
  19245. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19246. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19247. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19248. }
  19249. else {
  19250. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19251. }
  19252. }
  19253. //compute photometric scale
  19254. switch (lightTypeID) {
  19255. case Light.LIGHTTYPEID_POINTLIGHT:
  19256. case Light.LIGHTTYPEID_SPOTLIGHT:
  19257. switch (photometricMode) {
  19258. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19259. photometricScale = 1.0 / (4.0 * Math.PI);
  19260. break;
  19261. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19262. photometricScale = 1.0;
  19263. break;
  19264. case Light.INTENSITYMODE_LUMINANCE:
  19265. photometricScale = this.radius * this.radius;
  19266. break;
  19267. }
  19268. break;
  19269. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19270. switch (photometricMode) {
  19271. case Light.INTENSITYMODE_ILLUMINANCE:
  19272. photometricScale = 1.0;
  19273. break;
  19274. case Light.INTENSITYMODE_LUMINANCE:
  19275. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19276. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19277. var apexAngleRadians = this.radius;
  19278. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19279. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19280. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19281. photometricScale = solidAngle;
  19282. break;
  19283. }
  19284. break;
  19285. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19286. // No fall off in hemisperic light.
  19287. photometricScale = 1.0;
  19288. break;
  19289. }
  19290. return photometricScale;
  19291. };
  19292. /**
  19293. * Reorder the light in the scene according to their defined priority.
  19294. * @ignore Internal Use Only
  19295. */
  19296. Light.prototype._reorderLightsInScene = function () {
  19297. var scene = this.getScene();
  19298. if (this._renderPriority != 0) {
  19299. scene.requireLightSorting = true;
  19300. }
  19301. this.getScene().sortLightsByPriority();
  19302. };
  19303. //lightmapMode Consts
  19304. Light._LIGHTMAP_DEFAULT = 0;
  19305. Light._LIGHTMAP_SPECULAR = 1;
  19306. Light._LIGHTMAP_SHADOWSONLY = 2;
  19307. // Intensity Mode Consts
  19308. Light._INTENSITYMODE_AUTOMATIC = 0;
  19309. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19310. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19311. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19312. Light._INTENSITYMODE_LUMINANCE = 4;
  19313. // Light types ids const.
  19314. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19315. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19316. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19317. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19318. __decorate([
  19319. BABYLON.serializeAsColor3()
  19320. ], Light.prototype, "diffuse", void 0);
  19321. __decorate([
  19322. BABYLON.serializeAsColor3()
  19323. ], Light.prototype, "specular", void 0);
  19324. __decorate([
  19325. BABYLON.serialize()
  19326. ], Light.prototype, "intensity", void 0);
  19327. __decorate([
  19328. BABYLON.serialize()
  19329. ], Light.prototype, "range", void 0);
  19330. __decorate([
  19331. BABYLON.serialize()
  19332. ], Light.prototype, "intensityMode", null);
  19333. __decorate([
  19334. BABYLON.serialize()
  19335. ], Light.prototype, "radius", null);
  19336. __decorate([
  19337. BABYLON.serialize()
  19338. ], Light.prototype, "_renderPriority", void 0);
  19339. __decorate([
  19340. BABYLON.expandToProperty("_reorderLightsInScene")
  19341. ], Light.prototype, "renderPriority", void 0);
  19342. __decorate([
  19343. BABYLON.serialize()
  19344. ], Light.prototype, "shadowEnabled", void 0);
  19345. __decorate([
  19346. BABYLON.serialize("excludeWithLayerMask")
  19347. ], Light.prototype, "_excludeWithLayerMask", void 0);
  19348. __decorate([
  19349. BABYLON.serialize("includeOnlyWithLayerMask")
  19350. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  19351. __decorate([
  19352. BABYLON.serialize("lightmapMode")
  19353. ], Light.prototype, "_lightmapMode", void 0);
  19354. return Light;
  19355. }(BABYLON.Node));
  19356. BABYLON.Light = Light;
  19357. })(BABYLON || (BABYLON = {}));
  19358. //# sourceMappingURL=babylon.light.js.map
  19359. var BABYLON;
  19360. (function (BABYLON) {
  19361. var Camera = /** @class */ (function (_super) {
  19362. __extends(Camera, _super);
  19363. function Camera(name, position, scene) {
  19364. var _this = _super.call(this, name, scene) || this;
  19365. /**
  19366. * The vector the camera should consider as up.
  19367. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  19368. */
  19369. _this.upVector = BABYLON.Vector3.Up();
  19370. _this.orthoLeft = null;
  19371. _this.orthoRight = null;
  19372. _this.orthoBottom = null;
  19373. _this.orthoTop = null;
  19374. /**
  19375. * FOV is set in Radians. (default is 0.8)
  19376. */
  19377. _this.fov = 0.8;
  19378. _this.minZ = 1;
  19379. _this.maxZ = 10000.0;
  19380. _this.inertia = 0.9;
  19381. _this.mode = Camera.PERSPECTIVE_CAMERA;
  19382. _this.isIntermediate = false;
  19383. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  19384. /**
  19385. * Restricts the camera to viewing objects with the same layerMask.
  19386. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  19387. */
  19388. _this.layerMask = 0x0FFFFFFF;
  19389. /**
  19390. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  19391. */
  19392. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  19393. // Camera rig members
  19394. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  19395. _this._rigCameras = new Array();
  19396. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  19397. _this._skipRendering = false;
  19398. _this.customRenderTargets = new Array();
  19399. // Observables
  19400. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  19401. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  19402. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  19403. _this.onRestoreStateObservable = new BABYLON.Observable();
  19404. // Cache
  19405. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  19406. _this._projectionMatrix = new BABYLON.Matrix();
  19407. _this._doNotComputeProjectionMatrix = false;
  19408. _this._postProcesses = new Array();
  19409. _this._transformMatrix = BABYLON.Matrix.Zero();
  19410. _this._activeMeshes = new BABYLON.SmartArray(256);
  19411. _this._globalPosition = BABYLON.Vector3.Zero();
  19412. _this._refreshFrustumPlanes = true;
  19413. _this.getScene().addCamera(_this);
  19414. if (!_this.getScene().activeCamera) {
  19415. _this.getScene().activeCamera = _this;
  19416. }
  19417. _this.position = position;
  19418. return _this;
  19419. }
  19420. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  19421. get: function () {
  19422. return Camera._PERSPECTIVE_CAMERA;
  19423. },
  19424. enumerable: true,
  19425. configurable: true
  19426. });
  19427. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  19428. get: function () {
  19429. return Camera._ORTHOGRAPHIC_CAMERA;
  19430. },
  19431. enumerable: true,
  19432. configurable: true
  19433. });
  19434. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  19435. /**
  19436. * This is the default FOV mode for perspective cameras.
  19437. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  19438. *
  19439. */
  19440. get: function () {
  19441. return Camera._FOVMODE_VERTICAL_FIXED;
  19442. },
  19443. enumerable: true,
  19444. configurable: true
  19445. });
  19446. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  19447. /**
  19448. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  19449. *
  19450. */
  19451. get: function () {
  19452. return Camera._FOVMODE_HORIZONTAL_FIXED;
  19453. },
  19454. enumerable: true,
  19455. configurable: true
  19456. });
  19457. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  19458. get: function () {
  19459. return Camera._RIG_MODE_NONE;
  19460. },
  19461. enumerable: true,
  19462. configurable: true
  19463. });
  19464. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  19465. get: function () {
  19466. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  19467. },
  19468. enumerable: true,
  19469. configurable: true
  19470. });
  19471. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  19472. get: function () {
  19473. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  19474. },
  19475. enumerable: true,
  19476. configurable: true
  19477. });
  19478. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  19479. get: function () {
  19480. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19481. },
  19482. enumerable: true,
  19483. configurable: true
  19484. });
  19485. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  19486. get: function () {
  19487. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  19488. },
  19489. enumerable: true,
  19490. configurable: true
  19491. });
  19492. Object.defineProperty(Camera, "RIG_MODE_VR", {
  19493. get: function () {
  19494. return Camera._RIG_MODE_VR;
  19495. },
  19496. enumerable: true,
  19497. configurable: true
  19498. });
  19499. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  19500. get: function () {
  19501. return Camera._RIG_MODE_WEBVR;
  19502. },
  19503. enumerable: true,
  19504. configurable: true
  19505. });
  19506. /**
  19507. * Store current camera state (fov, position, etc..)
  19508. */
  19509. Camera.prototype.storeState = function () {
  19510. this._stateStored = true;
  19511. this._storedFov = this.fov;
  19512. return this;
  19513. };
  19514. /**
  19515. * Restores the camera state values if it has been stored. You must call storeState() first
  19516. */
  19517. Camera.prototype._restoreStateValues = function () {
  19518. if (!this._stateStored) {
  19519. return false;
  19520. }
  19521. this.fov = this._storedFov;
  19522. return true;
  19523. };
  19524. /**
  19525. * Restored camera state. You must call storeState() first
  19526. */
  19527. Camera.prototype.restoreState = function () {
  19528. if (this._restoreStateValues()) {
  19529. this.onRestoreStateObservable.notifyObservers(this);
  19530. return true;
  19531. }
  19532. return false;
  19533. };
  19534. Camera.prototype.getClassName = function () {
  19535. return "Camera";
  19536. };
  19537. /**
  19538. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19539. */
  19540. Camera.prototype.toString = function (fullDetails) {
  19541. var ret = "Name: " + this.name;
  19542. ret += ", type: " + this.getClassName();
  19543. if (this.animations) {
  19544. for (var i = 0; i < this.animations.length; i++) {
  19545. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19546. }
  19547. }
  19548. if (fullDetails) {
  19549. }
  19550. return ret;
  19551. };
  19552. Object.defineProperty(Camera.prototype, "globalPosition", {
  19553. get: function () {
  19554. return this._globalPosition;
  19555. },
  19556. enumerable: true,
  19557. configurable: true
  19558. });
  19559. Camera.prototype.getActiveMeshes = function () {
  19560. return this._activeMeshes;
  19561. };
  19562. Camera.prototype.isActiveMesh = function (mesh) {
  19563. return (this._activeMeshes.indexOf(mesh) !== -1);
  19564. };
  19565. //Cache
  19566. Camera.prototype._initCache = function () {
  19567. _super.prototype._initCache.call(this);
  19568. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19569. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19570. this._cache.mode = undefined;
  19571. this._cache.minZ = undefined;
  19572. this._cache.maxZ = undefined;
  19573. this._cache.fov = undefined;
  19574. this._cache.fovMode = undefined;
  19575. this._cache.aspectRatio = undefined;
  19576. this._cache.orthoLeft = undefined;
  19577. this._cache.orthoRight = undefined;
  19578. this._cache.orthoBottom = undefined;
  19579. this._cache.orthoTop = undefined;
  19580. this._cache.renderWidth = undefined;
  19581. this._cache.renderHeight = undefined;
  19582. };
  19583. Camera.prototype._updateCache = function (ignoreParentClass) {
  19584. if (!ignoreParentClass) {
  19585. _super.prototype._updateCache.call(this);
  19586. }
  19587. this._cache.position.copyFrom(this.position);
  19588. this._cache.upVector.copyFrom(this.upVector);
  19589. };
  19590. // Synchronized
  19591. Camera.prototype._isSynchronized = function () {
  19592. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  19593. };
  19594. Camera.prototype._isSynchronizedViewMatrix = function () {
  19595. if (!_super.prototype._isSynchronized.call(this))
  19596. return false;
  19597. return this._cache.position.equals(this.position)
  19598. && this._cache.upVector.equals(this.upVector)
  19599. && this.isSynchronizedWithParent();
  19600. };
  19601. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  19602. var check = this._cache.mode === this.mode
  19603. && this._cache.minZ === this.minZ
  19604. && this._cache.maxZ === this.maxZ;
  19605. if (!check) {
  19606. return false;
  19607. }
  19608. var engine = this.getEngine();
  19609. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19610. check = this._cache.fov === this.fov
  19611. && this._cache.fovMode === this.fovMode
  19612. && this._cache.aspectRatio === engine.getAspectRatio(this);
  19613. }
  19614. else {
  19615. check = this._cache.orthoLeft === this.orthoLeft
  19616. && this._cache.orthoRight === this.orthoRight
  19617. && this._cache.orthoBottom === this.orthoBottom
  19618. && this._cache.orthoTop === this.orthoTop
  19619. && this._cache.renderWidth === engine.getRenderWidth()
  19620. && this._cache.renderHeight === engine.getRenderHeight();
  19621. }
  19622. return check;
  19623. };
  19624. // Controls
  19625. Camera.prototype.attachControl = function (element, noPreventDefault) {
  19626. };
  19627. Camera.prototype.detachControl = function (element) {
  19628. };
  19629. Camera.prototype.update = function () {
  19630. this._checkInputs();
  19631. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19632. this._updateRigCameras();
  19633. }
  19634. };
  19635. Camera.prototype._checkInputs = function () {
  19636. this.onAfterCheckInputsObservable.notifyObservers(this);
  19637. };
  19638. Object.defineProperty(Camera.prototype, "rigCameras", {
  19639. get: function () {
  19640. return this._rigCameras;
  19641. },
  19642. enumerable: true,
  19643. configurable: true
  19644. });
  19645. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  19646. get: function () {
  19647. return this._rigPostProcess;
  19648. },
  19649. enumerable: true,
  19650. configurable: true
  19651. });
  19652. Camera.prototype._cascadePostProcessesToRigCams = function () {
  19653. // invalidate framebuffer
  19654. if (this._postProcesses.length > 0) {
  19655. this._postProcesses[0].markTextureDirty();
  19656. }
  19657. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  19658. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  19659. var cam = this._rigCameras[i];
  19660. var rigPostProcess = cam._rigPostProcess;
  19661. // for VR rig, there does not have to be a post process
  19662. if (rigPostProcess) {
  19663. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  19664. if (isPass) {
  19665. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  19666. cam.isIntermediate = this._postProcesses.length === 0;
  19667. }
  19668. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  19669. rigPostProcess.markTextureDirty();
  19670. }
  19671. else {
  19672. cam._postProcesses = this._postProcesses.slice(0);
  19673. }
  19674. }
  19675. };
  19676. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  19677. if (insertAt === void 0) { insertAt = null; }
  19678. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  19679. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  19680. return 0;
  19681. }
  19682. if (insertAt == null || insertAt < 0) {
  19683. this._postProcesses.push(postProcess);
  19684. }
  19685. else {
  19686. this._postProcesses.splice(insertAt, 0, postProcess);
  19687. }
  19688. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19689. return this._postProcesses.indexOf(postProcess);
  19690. };
  19691. Camera.prototype.detachPostProcess = function (postProcess) {
  19692. var idx = this._postProcesses.indexOf(postProcess);
  19693. if (idx !== -1) {
  19694. this._postProcesses.splice(idx, 1);
  19695. }
  19696. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  19697. };
  19698. Camera.prototype.getWorldMatrix = function () {
  19699. if (!this._worldMatrix) {
  19700. this._worldMatrix = BABYLON.Matrix.Identity();
  19701. }
  19702. var viewMatrix = this.getViewMatrix();
  19703. viewMatrix.invertToRef(this._worldMatrix);
  19704. return this._worldMatrix;
  19705. };
  19706. Camera.prototype._getViewMatrix = function () {
  19707. return BABYLON.Matrix.Identity();
  19708. };
  19709. Camera.prototype.getViewMatrix = function (force) {
  19710. if (!force && this._isSynchronizedViewMatrix()) {
  19711. return this._computedViewMatrix;
  19712. }
  19713. this.updateCache();
  19714. this._computedViewMatrix = this._getViewMatrix();
  19715. this._currentRenderId = this.getScene().getRenderId();
  19716. this._refreshFrustumPlanes = true;
  19717. if (!this.parent || !this.parent.getWorldMatrix) {
  19718. this._globalPosition.copyFrom(this.position);
  19719. }
  19720. else {
  19721. if (!this._worldMatrix) {
  19722. this._worldMatrix = BABYLON.Matrix.Identity();
  19723. }
  19724. this._computedViewMatrix.invertToRef(this._worldMatrix);
  19725. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  19726. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  19727. this._computedViewMatrix.invert();
  19728. this._markSyncedWithParent();
  19729. }
  19730. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  19731. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  19732. }
  19733. this.onViewMatrixChangedObservable.notifyObservers(this);
  19734. return this._computedViewMatrix;
  19735. };
  19736. Camera.prototype.freezeProjectionMatrix = function (projection) {
  19737. this._doNotComputeProjectionMatrix = true;
  19738. if (projection !== undefined) {
  19739. this._projectionMatrix = projection;
  19740. }
  19741. };
  19742. ;
  19743. Camera.prototype.unfreezeProjectionMatrix = function () {
  19744. this._doNotComputeProjectionMatrix = false;
  19745. };
  19746. ;
  19747. Camera.prototype.getProjectionMatrix = function (force) {
  19748. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  19749. return this._projectionMatrix;
  19750. }
  19751. // Cache
  19752. this._cache.mode = this.mode;
  19753. this._cache.minZ = this.minZ;
  19754. this._cache.maxZ = this.maxZ;
  19755. // Matrix
  19756. this._refreshFrustumPlanes = true;
  19757. var engine = this.getEngine();
  19758. var scene = this.getScene();
  19759. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  19760. this._cache.fov = this.fov;
  19761. this._cache.fovMode = this.fovMode;
  19762. this._cache.aspectRatio = engine.getAspectRatio(this);
  19763. if (this.minZ <= 0) {
  19764. this.minZ = 0.1;
  19765. }
  19766. if (scene.useRightHandedSystem) {
  19767. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19768. }
  19769. else {
  19770. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  19771. }
  19772. }
  19773. else {
  19774. var halfWidth = engine.getRenderWidth() / 2.0;
  19775. var halfHeight = engine.getRenderHeight() / 2.0;
  19776. if (scene.useRightHandedSystem) {
  19777. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19778. }
  19779. else {
  19780. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  19781. }
  19782. this._cache.orthoLeft = this.orthoLeft;
  19783. this._cache.orthoRight = this.orthoRight;
  19784. this._cache.orthoBottom = this.orthoBottom;
  19785. this._cache.orthoTop = this.orthoTop;
  19786. this._cache.renderWidth = engine.getRenderWidth();
  19787. this._cache.renderHeight = engine.getRenderHeight();
  19788. }
  19789. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  19790. return this._projectionMatrix;
  19791. };
  19792. Camera.prototype.getTranformationMatrix = function () {
  19793. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  19794. return this._transformMatrix;
  19795. };
  19796. Camera.prototype.updateFrustumPlanes = function () {
  19797. if (!this._refreshFrustumPlanes) {
  19798. return;
  19799. }
  19800. this.getTranformationMatrix();
  19801. if (!this._frustumPlanes) {
  19802. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  19803. }
  19804. else {
  19805. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  19806. }
  19807. this._refreshFrustumPlanes = false;
  19808. };
  19809. Camera.prototype.isInFrustum = function (target) {
  19810. this.updateFrustumPlanes();
  19811. return target.isInFrustum(this._frustumPlanes);
  19812. };
  19813. Camera.prototype.isCompletelyInFrustum = function (target) {
  19814. this.updateFrustumPlanes();
  19815. return target.isCompletelyInFrustum(this._frustumPlanes);
  19816. };
  19817. Camera.prototype.getForwardRay = function (length, transform, origin) {
  19818. if (length === void 0) { length = 100; }
  19819. if (!transform) {
  19820. transform = this.getWorldMatrix();
  19821. }
  19822. if (!origin) {
  19823. origin = this.position;
  19824. }
  19825. var forward = new BABYLON.Vector3(0, 0, 1);
  19826. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  19827. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  19828. return new BABYLON.Ray(origin, direction, length);
  19829. };
  19830. Camera.prototype.dispose = function () {
  19831. // Observables
  19832. this.onViewMatrixChangedObservable.clear();
  19833. this.onProjectionMatrixChangedObservable.clear();
  19834. this.onAfterCheckInputsObservable.clear();
  19835. this.onRestoreStateObservable.clear();
  19836. // Inputs
  19837. if (this.inputs) {
  19838. this.inputs.clear();
  19839. }
  19840. // Animations
  19841. this.getScene().stopAnimation(this);
  19842. // Remove from scene
  19843. this.getScene().removeCamera(this);
  19844. while (this._rigCameras.length > 0) {
  19845. var camera = this._rigCameras.pop();
  19846. if (camera) {
  19847. camera.dispose();
  19848. }
  19849. }
  19850. // Postprocesses
  19851. if (this._rigPostProcess) {
  19852. this._rigPostProcess.dispose(this);
  19853. this._rigPostProcess = null;
  19854. this._postProcesses = [];
  19855. }
  19856. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19857. this._rigPostProcess = null;
  19858. this._postProcesses = [];
  19859. }
  19860. else {
  19861. var i = this._postProcesses.length;
  19862. while (--i >= 0) {
  19863. this._postProcesses[i].dispose(this);
  19864. }
  19865. }
  19866. // Render targets
  19867. var i = this.customRenderTargets.length;
  19868. while (--i >= 0) {
  19869. this.customRenderTargets[i].dispose();
  19870. }
  19871. this.customRenderTargets = [];
  19872. // Active Meshes
  19873. this._activeMeshes.dispose();
  19874. _super.prototype.dispose.call(this);
  19875. };
  19876. Object.defineProperty(Camera.prototype, "leftCamera", {
  19877. // ---- Camera rigs section ----
  19878. get: function () {
  19879. if (this._rigCameras.length < 1) {
  19880. return null;
  19881. }
  19882. return this._rigCameras[0];
  19883. },
  19884. enumerable: true,
  19885. configurable: true
  19886. });
  19887. Object.defineProperty(Camera.prototype, "rightCamera", {
  19888. get: function () {
  19889. if (this._rigCameras.length < 2) {
  19890. return null;
  19891. }
  19892. return this._rigCameras[1];
  19893. },
  19894. enumerable: true,
  19895. configurable: true
  19896. });
  19897. Camera.prototype.getLeftTarget = function () {
  19898. if (this._rigCameras.length < 1) {
  19899. return null;
  19900. }
  19901. return this._rigCameras[0].getTarget();
  19902. };
  19903. Camera.prototype.getRightTarget = function () {
  19904. if (this._rigCameras.length < 2) {
  19905. return null;
  19906. }
  19907. return this._rigCameras[1].getTarget();
  19908. };
  19909. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  19910. if (this.cameraRigMode === mode) {
  19911. return;
  19912. }
  19913. while (this._rigCameras.length > 0) {
  19914. var camera = this._rigCameras.pop();
  19915. if (camera) {
  19916. camera.dispose();
  19917. }
  19918. }
  19919. this.cameraRigMode = mode;
  19920. this._cameraRigParams = {};
  19921. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  19922. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  19923. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  19924. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  19925. // create the rig cameras, unless none
  19926. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  19927. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  19928. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  19929. if (leftCamera && rightCamera) {
  19930. this._rigCameras.push(leftCamera);
  19931. this._rigCameras.push(rightCamera);
  19932. }
  19933. }
  19934. switch (this.cameraRigMode) {
  19935. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  19936. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19937. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  19938. break;
  19939. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  19940. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  19941. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  19942. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  19943. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  19944. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  19945. break;
  19946. case Camera.RIG_MODE_VR:
  19947. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  19948. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  19949. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19950. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19951. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  19952. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  19953. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  19954. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  19955. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19956. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19957. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  19958. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  19959. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  19960. if (metrics.compensateDistortion) {
  19961. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  19962. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  19963. }
  19964. break;
  19965. case Camera.RIG_MODE_WEBVR:
  19966. if (rigParams.vrDisplay) {
  19967. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  19968. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  19969. //Left eye
  19970. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  19971. this._rigCameras[0].setCameraRigParameter("left", true);
  19972. //leaving this for future reference
  19973. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  19974. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  19975. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  19976. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19977. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19978. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19979. this._rigCameras[0].parent = this;
  19980. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  19981. //Right eye
  19982. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  19983. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  19984. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  19985. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  19986. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  19987. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  19988. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  19989. this._rigCameras[1].parent = this;
  19990. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  19991. if (Camera.UseAlternateWebVRRendering) {
  19992. this._rigCameras[1]._skipRendering = true;
  19993. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  19994. }
  19995. }
  19996. break;
  19997. }
  19998. this._cascadePostProcessesToRigCams();
  19999. this.update();
  20000. };
  20001. Camera.prototype._getVRProjectionMatrix = function () {
  20002. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20003. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20004. return this._projectionMatrix;
  20005. };
  20006. Camera.prototype._updateCameraRotationMatrix = function () {
  20007. //Here for WebVR
  20008. };
  20009. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20010. //Here for WebVR
  20011. };
  20012. /**
  20013. * This function MUST be overwritten by the different WebVR cameras available.
  20014. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20015. */
  20016. Camera.prototype._getWebVRProjectionMatrix = function () {
  20017. return BABYLON.Matrix.Identity();
  20018. };
  20019. /**
  20020. * This function MUST be overwritten by the different WebVR cameras available.
  20021. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20022. */
  20023. Camera.prototype._getWebVRViewMatrix = function () {
  20024. return BABYLON.Matrix.Identity();
  20025. };
  20026. Camera.prototype.setCameraRigParameter = function (name, value) {
  20027. if (!this._cameraRigParams) {
  20028. this._cameraRigParams = {};
  20029. }
  20030. this._cameraRigParams[name] = value;
  20031. //provisionnally:
  20032. if (name === "interaxialDistance") {
  20033. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20034. }
  20035. };
  20036. /**
  20037. * needs to be overridden by children so sub has required properties to be copied
  20038. */
  20039. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20040. return null;
  20041. };
  20042. /**
  20043. * May need to be overridden by children
  20044. */
  20045. Camera.prototype._updateRigCameras = function () {
  20046. for (var i = 0; i < this._rigCameras.length; i++) {
  20047. this._rigCameras[i].minZ = this.minZ;
  20048. this._rigCameras[i].maxZ = this.maxZ;
  20049. this._rigCameras[i].fov = this.fov;
  20050. }
  20051. // only update viewport when ANAGLYPH
  20052. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20053. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20054. }
  20055. };
  20056. Camera.prototype._setupInputs = function () {
  20057. };
  20058. Camera.prototype.serialize = function () {
  20059. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20060. // Type
  20061. serializationObject.type = this.getClassName();
  20062. // Parent
  20063. if (this.parent) {
  20064. serializationObject.parentId = this.parent.id;
  20065. }
  20066. if (this.inputs) {
  20067. this.inputs.serialize(serializationObject);
  20068. }
  20069. // Animations
  20070. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20071. serializationObject.ranges = this.serializeAnimationRanges();
  20072. return serializationObject;
  20073. };
  20074. Camera.prototype.clone = function (name) {
  20075. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20076. };
  20077. Camera.prototype.getDirection = function (localAxis) {
  20078. var result = BABYLON.Vector3.Zero();
  20079. this.getDirectionToRef(localAxis, result);
  20080. return result;
  20081. };
  20082. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20083. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20084. };
  20085. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20086. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20087. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20088. switch (type) {
  20089. case "ArcRotateCamera":
  20090. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20091. case "DeviceOrientationCamera":
  20092. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20093. case "FollowCamera":
  20094. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20095. case "ArcFollowCamera":
  20096. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20097. case "GamepadCamera":
  20098. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20099. case "TouchCamera":
  20100. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20101. case "VirtualJoysticksCamera":
  20102. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20103. case "WebVRFreeCamera":
  20104. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20105. case "WebVRGamepadCamera":
  20106. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20107. case "VRDeviceOrientationFreeCamera":
  20108. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20109. case "VRDeviceOrientationGamepadCamera":
  20110. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20111. case "AnaglyphArcRotateCamera":
  20112. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20113. case "AnaglyphFreeCamera":
  20114. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20115. case "AnaglyphGamepadCamera":
  20116. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20117. case "AnaglyphUniversalCamera":
  20118. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20119. case "StereoscopicArcRotateCamera":
  20120. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20121. case "StereoscopicFreeCamera":
  20122. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20123. case "StereoscopicGamepadCamera":
  20124. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20125. case "StereoscopicUniversalCamera":
  20126. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20127. case "FreeCamera":// Forcing Universal here
  20128. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20129. default:// Universal Camera is the default value
  20130. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20131. }
  20132. };
  20133. Camera.prototype.computeWorldMatrix = function () {
  20134. return this.getWorldMatrix();
  20135. };
  20136. Camera.Parse = function (parsedCamera, scene) {
  20137. var type = parsedCamera.type;
  20138. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20139. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20140. // Parent
  20141. if (parsedCamera.parentId) {
  20142. camera._waitingParentId = parsedCamera.parentId;
  20143. }
  20144. //If camera has an input manager, let it parse inputs settings
  20145. if (camera.inputs) {
  20146. camera.inputs.parse(parsedCamera);
  20147. camera._setupInputs();
  20148. }
  20149. if (camera.setPosition) {
  20150. camera.position.copyFromFloats(0, 0, 0);
  20151. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20152. }
  20153. // Target
  20154. if (parsedCamera.target) {
  20155. if (camera.setTarget) {
  20156. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20157. }
  20158. }
  20159. // Apply 3d rig, when found
  20160. if (parsedCamera.cameraRigMode) {
  20161. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20162. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20163. }
  20164. // Animations
  20165. if (parsedCamera.animations) {
  20166. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20167. var parsedAnimation = parsedCamera.animations[animationIndex];
  20168. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20169. }
  20170. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20171. }
  20172. if (parsedCamera.autoAnimate) {
  20173. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20174. }
  20175. return camera;
  20176. };
  20177. // Statics
  20178. Camera._PERSPECTIVE_CAMERA = 0;
  20179. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20180. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20181. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20182. Camera._RIG_MODE_NONE = 0;
  20183. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20184. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20185. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20186. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20187. Camera._RIG_MODE_VR = 20;
  20188. Camera._RIG_MODE_WEBVR = 21;
  20189. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20190. Camera.UseAlternateWebVRRendering = false;
  20191. __decorate([
  20192. BABYLON.serializeAsVector3()
  20193. ], Camera.prototype, "position", void 0);
  20194. __decorate([
  20195. BABYLON.serializeAsVector3()
  20196. ], Camera.prototype, "upVector", void 0);
  20197. __decorate([
  20198. BABYLON.serialize()
  20199. ], Camera.prototype, "orthoLeft", void 0);
  20200. __decorate([
  20201. BABYLON.serialize()
  20202. ], Camera.prototype, "orthoRight", void 0);
  20203. __decorate([
  20204. BABYLON.serialize()
  20205. ], Camera.prototype, "orthoBottom", void 0);
  20206. __decorate([
  20207. BABYLON.serialize()
  20208. ], Camera.prototype, "orthoTop", void 0);
  20209. __decorate([
  20210. BABYLON.serialize()
  20211. ], Camera.prototype, "fov", void 0);
  20212. __decorate([
  20213. BABYLON.serialize()
  20214. ], Camera.prototype, "minZ", void 0);
  20215. __decorate([
  20216. BABYLON.serialize()
  20217. ], Camera.prototype, "maxZ", void 0);
  20218. __decorate([
  20219. BABYLON.serialize()
  20220. ], Camera.prototype, "inertia", void 0);
  20221. __decorate([
  20222. BABYLON.serialize()
  20223. ], Camera.prototype, "mode", void 0);
  20224. __decorate([
  20225. BABYLON.serialize()
  20226. ], Camera.prototype, "layerMask", void 0);
  20227. __decorate([
  20228. BABYLON.serialize()
  20229. ], Camera.prototype, "fovMode", void 0);
  20230. __decorate([
  20231. BABYLON.serialize()
  20232. ], Camera.prototype, "cameraRigMode", void 0);
  20233. __decorate([
  20234. BABYLON.serialize()
  20235. ], Camera.prototype, "interaxialDistance", void 0);
  20236. __decorate([
  20237. BABYLON.serialize()
  20238. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20239. return Camera;
  20240. }(BABYLON.Node));
  20241. BABYLON.Camera = Camera;
  20242. })(BABYLON || (BABYLON = {}));
  20243. //# sourceMappingURL=babylon.camera.js.map
  20244. var BABYLON;
  20245. (function (BABYLON) {
  20246. var RenderingManager = /** @class */ (function () {
  20247. function RenderingManager(scene) {
  20248. this._renderingGroups = new Array();
  20249. this._autoClearDepthStencil = {};
  20250. this._customOpaqueSortCompareFn = {};
  20251. this._customAlphaTestSortCompareFn = {};
  20252. this._customTransparentSortCompareFn = {};
  20253. this._renderinGroupInfo = null;
  20254. this._scene = scene;
  20255. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20256. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20257. }
  20258. }
  20259. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20260. if (depth === void 0) { depth = true; }
  20261. if (stencil === void 0) { stencil = true; }
  20262. if (this._depthStencilBufferAlreadyCleaned) {
  20263. return;
  20264. }
  20265. this._scene.getEngine().clear(null, false, depth, stencil);
  20266. this._depthStencilBufferAlreadyCleaned = true;
  20267. };
  20268. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20269. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20270. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20271. var info = null;
  20272. if (observable) {
  20273. if (!this._renderinGroupInfo) {
  20274. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20275. }
  20276. info = this._renderinGroupInfo;
  20277. info.scene = this._scene;
  20278. info.camera = this._scene.activeCamera;
  20279. }
  20280. // Dispatch sprites
  20281. if (renderSprites) {
  20282. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20283. var manager = this._scene.spriteManagers[index];
  20284. this.dispatchSprites(manager);
  20285. }
  20286. }
  20287. // Render
  20288. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20289. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20290. var renderingGroup = this._renderingGroups[index];
  20291. if (!renderingGroup && !observable)
  20292. continue;
  20293. var renderingGroupMask = 0;
  20294. // Fire PRECLEAR stage
  20295. if (observable && info) {
  20296. renderingGroupMask = Math.pow(2, index);
  20297. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20298. info.renderingGroupId = index;
  20299. observable.notifyObservers(info, renderingGroupMask);
  20300. }
  20301. // Clear depth/stencil if needed
  20302. if (RenderingManager.AUTOCLEAR) {
  20303. var autoClear = this._autoClearDepthStencil[index];
  20304. if (autoClear && autoClear.autoClear) {
  20305. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20306. }
  20307. }
  20308. if (observable && info) {
  20309. // Fire PREOPAQUE stage
  20310. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  20311. observable.notifyObservers(info, renderingGroupMask);
  20312. // Fire PRETRANSPARENT stage
  20313. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  20314. observable.notifyObservers(info, renderingGroupMask);
  20315. }
  20316. if (renderingGroup)
  20317. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  20318. // Fire POSTTRANSPARENT stage
  20319. if (observable && info) {
  20320. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  20321. observable.notifyObservers(info, renderingGroupMask);
  20322. }
  20323. }
  20324. };
  20325. RenderingManager.prototype.reset = function () {
  20326. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20327. var renderingGroup = this._renderingGroups[index];
  20328. if (renderingGroup) {
  20329. renderingGroup.prepare();
  20330. }
  20331. }
  20332. };
  20333. RenderingManager.prototype.dispose = function () {
  20334. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20335. var renderingGroup = this._renderingGroups[index];
  20336. if (renderingGroup) {
  20337. renderingGroup.dispose();
  20338. }
  20339. }
  20340. this._renderingGroups.length = 0;
  20341. };
  20342. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  20343. if (this._renderingGroups[renderingGroupId] === undefined) {
  20344. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  20345. }
  20346. };
  20347. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  20348. var renderingGroupId = spriteManager.renderingGroupId || 0;
  20349. this._prepareRenderingGroup(renderingGroupId);
  20350. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  20351. };
  20352. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  20353. var renderingGroupId = particleSystem.renderingGroupId || 0;
  20354. this._prepareRenderingGroup(renderingGroupId);
  20355. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  20356. };
  20357. /**
  20358. * @param subMesh The submesh to dispatch
  20359. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20360. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20361. */
  20362. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  20363. if (mesh === undefined) {
  20364. mesh = subMesh.getMesh();
  20365. }
  20366. var renderingGroupId = mesh.renderingGroupId || 0;
  20367. this._prepareRenderingGroup(renderingGroupId);
  20368. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  20369. };
  20370. /**
  20371. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20372. * This allowed control for front to back rendering or reversly depending of the special needs.
  20373. *
  20374. * @param renderingGroupId The rendering group id corresponding to its index
  20375. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20376. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20377. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20378. */
  20379. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20380. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20381. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20382. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20383. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  20384. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  20385. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  20386. if (this._renderingGroups[renderingGroupId]) {
  20387. var group = this._renderingGroups[renderingGroupId];
  20388. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  20389. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  20390. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  20391. }
  20392. };
  20393. /**
  20394. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20395. *
  20396. * @param renderingGroupId The rendering group id corresponding to its index
  20397. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20398. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20399. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20400. */
  20401. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20402. if (depth === void 0) { depth = true; }
  20403. if (stencil === void 0) { stencil = true; }
  20404. this._autoClearDepthStencil[renderingGroupId] = {
  20405. autoClear: autoClearDepthStencil,
  20406. depth: depth,
  20407. stencil: stencil
  20408. };
  20409. };
  20410. /**
  20411. * The max id used for rendering groups (not included)
  20412. */
  20413. RenderingManager.MAX_RENDERINGGROUPS = 4;
  20414. /**
  20415. * The min id used for rendering groups (included)
  20416. */
  20417. RenderingManager.MIN_RENDERINGGROUPS = 0;
  20418. /**
  20419. * Used to globally prevent autoclearing scenes.
  20420. */
  20421. RenderingManager.AUTOCLEAR = true;
  20422. return RenderingManager;
  20423. }());
  20424. BABYLON.RenderingManager = RenderingManager;
  20425. })(BABYLON || (BABYLON = {}));
  20426. //# sourceMappingURL=babylon.renderingManager.js.map
  20427. var BABYLON;
  20428. (function (BABYLON) {
  20429. var RenderingGroup = /** @class */ (function () {
  20430. /**
  20431. * Creates a new rendering group.
  20432. * @param index The rendering group index
  20433. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  20434. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  20435. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  20436. */
  20437. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20438. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20439. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20440. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20441. this.index = index;
  20442. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  20443. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  20444. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  20445. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  20446. this._particleSystems = new BABYLON.SmartArray(256);
  20447. this._spriteManagers = new BABYLON.SmartArray(256);
  20448. this._edgesRenderers = new BABYLON.SmartArray(16);
  20449. this._scene = scene;
  20450. this.opaqueSortCompareFn = opaqueSortCompareFn;
  20451. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  20452. this.transparentSortCompareFn = transparentSortCompareFn;
  20453. }
  20454. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  20455. /**
  20456. * Set the opaque sort comparison function.
  20457. * If null the sub meshes will be render in the order they were created
  20458. */
  20459. set: function (value) {
  20460. this._opaqueSortCompareFn = value;
  20461. if (value) {
  20462. this._renderOpaque = this.renderOpaqueSorted;
  20463. }
  20464. else {
  20465. this._renderOpaque = RenderingGroup.renderUnsorted;
  20466. }
  20467. },
  20468. enumerable: true,
  20469. configurable: true
  20470. });
  20471. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  20472. /**
  20473. * Set the alpha test sort comparison function.
  20474. * If null the sub meshes will be render in the order they were created
  20475. */
  20476. set: function (value) {
  20477. this._alphaTestSortCompareFn = value;
  20478. if (value) {
  20479. this._renderAlphaTest = this.renderAlphaTestSorted;
  20480. }
  20481. else {
  20482. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  20483. }
  20484. },
  20485. enumerable: true,
  20486. configurable: true
  20487. });
  20488. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  20489. /**
  20490. * Set the transparent sort comparison function.
  20491. * If null the sub meshes will be render in the order they were created
  20492. */
  20493. set: function (value) {
  20494. if (value) {
  20495. this._transparentSortCompareFn = value;
  20496. }
  20497. else {
  20498. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  20499. }
  20500. this._renderTransparent = this.renderTransparentSorted;
  20501. },
  20502. enumerable: true,
  20503. configurable: true
  20504. });
  20505. /**
  20506. * Render all the sub meshes contained in the group.
  20507. * @param customRenderFunction Used to override the default render behaviour of the group.
  20508. * @returns true if rendered some submeshes.
  20509. */
  20510. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  20511. if (customRenderFunction) {
  20512. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  20513. return;
  20514. }
  20515. var engine = this._scene.getEngine();
  20516. // Depth only
  20517. if (this._depthOnlySubMeshes.length !== 0) {
  20518. engine.setColorWrite(false);
  20519. this._renderAlphaTest(this._depthOnlySubMeshes);
  20520. engine.setColorWrite(true);
  20521. }
  20522. // Opaque
  20523. if (this._opaqueSubMeshes.length !== 0) {
  20524. this._renderOpaque(this._opaqueSubMeshes);
  20525. }
  20526. // Alpha test
  20527. if (this._alphaTestSubMeshes.length !== 0) {
  20528. this._renderAlphaTest(this._alphaTestSubMeshes);
  20529. }
  20530. var stencilState = engine.getStencilBuffer();
  20531. engine.setStencilBuffer(false);
  20532. // Sprites
  20533. if (renderSprites) {
  20534. this._renderSprites();
  20535. }
  20536. // Particles
  20537. if (renderParticles) {
  20538. this._renderParticles(activeMeshes);
  20539. }
  20540. if (this.onBeforeTransparentRendering) {
  20541. this.onBeforeTransparentRendering();
  20542. }
  20543. // Transparent
  20544. if (this._transparentSubMeshes.length !== 0) {
  20545. this._renderTransparent(this._transparentSubMeshes);
  20546. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20547. }
  20548. // Set back stencil to false in case it changes before the edge renderer.
  20549. engine.setStencilBuffer(false);
  20550. // Edges
  20551. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  20552. this._edgesRenderers.data[edgesRendererIndex].render();
  20553. }
  20554. // Restore Stencil state.
  20555. engine.setStencilBuffer(stencilState);
  20556. };
  20557. /**
  20558. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  20559. * @param subMeshes The submeshes to render
  20560. */
  20561. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  20562. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  20563. };
  20564. /**
  20565. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  20566. * @param subMeshes The submeshes to render
  20567. */
  20568. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  20569. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  20570. };
  20571. /**
  20572. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  20573. * @param subMeshes The submeshes to render
  20574. */
  20575. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  20576. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  20577. };
  20578. /**
  20579. * Renders the submeshes in a specified order.
  20580. * @param subMeshes The submeshes to sort before render
  20581. * @param sortCompareFn The comparison function use to sort
  20582. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  20583. * @param transparent Specifies to activate blending if true
  20584. */
  20585. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  20586. var subIndex = 0;
  20587. var subMesh;
  20588. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  20589. for (; subIndex < subMeshes.length; subIndex++) {
  20590. subMesh = subMeshes.data[subIndex];
  20591. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  20592. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  20593. }
  20594. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  20595. if (sortCompareFn) {
  20596. sortedArray.sort(sortCompareFn);
  20597. }
  20598. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  20599. subMesh = sortedArray[subIndex];
  20600. if (transparent) {
  20601. var material = subMesh.getMaterial();
  20602. if (material && material.needDepthPrePass) {
  20603. var engine = material.getScene().getEngine();
  20604. engine.setColorWrite(false);
  20605. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20606. subMesh.render(false);
  20607. engine.setColorWrite(true);
  20608. }
  20609. }
  20610. subMesh.render(transparent);
  20611. }
  20612. };
  20613. /**
  20614. * Renders the submeshes in the order they were dispatched (no sort applied).
  20615. * @param subMeshes The submeshes to render
  20616. */
  20617. RenderingGroup.renderUnsorted = function (subMeshes) {
  20618. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  20619. var submesh = subMeshes.data[subIndex];
  20620. submesh.render(false);
  20621. }
  20622. };
  20623. /**
  20624. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20625. * are rendered back to front if in the same alpha index.
  20626. *
  20627. * @param a The first submesh
  20628. * @param b The second submesh
  20629. * @returns The result of the comparison
  20630. */
  20631. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  20632. // Alpha index first
  20633. if (a._alphaIndex > b._alphaIndex) {
  20634. return 1;
  20635. }
  20636. if (a._alphaIndex < b._alphaIndex) {
  20637. return -1;
  20638. }
  20639. // Then distance to camera
  20640. return RenderingGroup.backToFrontSortCompare(a, b);
  20641. };
  20642. /**
  20643. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20644. * are rendered back to front.
  20645. *
  20646. * @param a The first submesh
  20647. * @param b The second submesh
  20648. * @returns The result of the comparison
  20649. */
  20650. RenderingGroup.backToFrontSortCompare = function (a, b) {
  20651. // Then distance to camera
  20652. if (a._distanceToCamera < b._distanceToCamera) {
  20653. return 1;
  20654. }
  20655. if (a._distanceToCamera > b._distanceToCamera) {
  20656. return -1;
  20657. }
  20658. return 0;
  20659. };
  20660. /**
  20661. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  20662. * are rendered front to back (prevent overdraw).
  20663. *
  20664. * @param a The first submesh
  20665. * @param b The second submesh
  20666. * @returns The result of the comparison
  20667. */
  20668. RenderingGroup.frontToBackSortCompare = function (a, b) {
  20669. // Then distance to camera
  20670. if (a._distanceToCamera < b._distanceToCamera) {
  20671. return -1;
  20672. }
  20673. if (a._distanceToCamera > b._distanceToCamera) {
  20674. return 1;
  20675. }
  20676. return 0;
  20677. };
  20678. /**
  20679. * Resets the different lists of submeshes to prepare a new frame.
  20680. */
  20681. RenderingGroup.prototype.prepare = function () {
  20682. this._opaqueSubMeshes.reset();
  20683. this._transparentSubMeshes.reset();
  20684. this._alphaTestSubMeshes.reset();
  20685. this._depthOnlySubMeshes.reset();
  20686. this._particleSystems.reset();
  20687. this._spriteManagers.reset();
  20688. this._edgesRenderers.reset();
  20689. };
  20690. RenderingGroup.prototype.dispose = function () {
  20691. this._opaqueSubMeshes.dispose();
  20692. this._transparentSubMeshes.dispose();
  20693. this._alphaTestSubMeshes.dispose();
  20694. this._depthOnlySubMeshes.dispose();
  20695. this._particleSystems.dispose();
  20696. this._spriteManagers.dispose();
  20697. this._edgesRenderers.dispose();
  20698. };
  20699. /**
  20700. * Inserts the submesh in its correct queue depending on its material.
  20701. * @param subMesh The submesh to dispatch
  20702. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  20703. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  20704. */
  20705. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  20706. // Get mesh and materials if not provided
  20707. if (mesh === undefined) {
  20708. mesh = subMesh.getMesh();
  20709. }
  20710. if (material === undefined) {
  20711. material = subMesh.getMaterial();
  20712. }
  20713. if (material === null || material === undefined) {
  20714. return;
  20715. }
  20716. if (material.needAlphaBlendingForMesh(mesh)) {
  20717. this._transparentSubMeshes.push(subMesh);
  20718. }
  20719. else if (material.needAlphaTesting()) {
  20720. if (material.needDepthPrePass) {
  20721. this._depthOnlySubMeshes.push(subMesh);
  20722. }
  20723. this._alphaTestSubMeshes.push(subMesh);
  20724. }
  20725. else {
  20726. if (material.needDepthPrePass) {
  20727. this._depthOnlySubMeshes.push(subMesh);
  20728. }
  20729. this._opaqueSubMeshes.push(subMesh); // Opaque
  20730. }
  20731. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  20732. this._edgesRenderers.push(mesh._edgesRenderer);
  20733. }
  20734. };
  20735. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  20736. this._spriteManagers.push(spriteManager);
  20737. };
  20738. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  20739. this._particleSystems.push(particleSystem);
  20740. };
  20741. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  20742. if (this._particleSystems.length === 0) {
  20743. return;
  20744. }
  20745. // Particles
  20746. var activeCamera = this._scene.activeCamera;
  20747. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  20748. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  20749. var particleSystem = this._particleSystems.data[particleIndex];
  20750. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  20751. continue;
  20752. }
  20753. var emitter = particleSystem.emitter;
  20754. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  20755. this._scene._activeParticles.addCount(particleSystem.render(), false);
  20756. }
  20757. }
  20758. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  20759. };
  20760. RenderingGroup.prototype._renderSprites = function () {
  20761. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  20762. return;
  20763. }
  20764. // Sprites
  20765. var activeCamera = this._scene.activeCamera;
  20766. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  20767. for (var id = 0; id < this._spriteManagers.length; id++) {
  20768. var spriteManager = this._spriteManagers.data[id];
  20769. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  20770. spriteManager.render();
  20771. }
  20772. }
  20773. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  20774. };
  20775. return RenderingGroup;
  20776. }());
  20777. BABYLON.RenderingGroup = RenderingGroup;
  20778. })(BABYLON || (BABYLON = {}));
  20779. //# sourceMappingURL=babylon.renderingGroup.js.map
  20780. var BABYLON;
  20781. (function (BABYLON) {
  20782. var ClickInfo = /** @class */ (function () {
  20783. function ClickInfo() {
  20784. this._singleClick = false;
  20785. this._doubleClick = false;
  20786. this._hasSwiped = false;
  20787. this._ignore = false;
  20788. }
  20789. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  20790. get: function () {
  20791. return this._singleClick;
  20792. },
  20793. set: function (b) {
  20794. this._singleClick = b;
  20795. },
  20796. enumerable: true,
  20797. configurable: true
  20798. });
  20799. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  20800. get: function () {
  20801. return this._doubleClick;
  20802. },
  20803. set: function (b) {
  20804. this._doubleClick = b;
  20805. },
  20806. enumerable: true,
  20807. configurable: true
  20808. });
  20809. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  20810. get: function () {
  20811. return this._hasSwiped;
  20812. },
  20813. set: function (b) {
  20814. this._hasSwiped = b;
  20815. },
  20816. enumerable: true,
  20817. configurable: true
  20818. });
  20819. Object.defineProperty(ClickInfo.prototype, "ignore", {
  20820. get: function () {
  20821. return this._ignore;
  20822. },
  20823. set: function (b) {
  20824. this._ignore = b;
  20825. },
  20826. enumerable: true,
  20827. configurable: true
  20828. });
  20829. return ClickInfo;
  20830. }());
  20831. /**
  20832. * This class is used by the onRenderingGroupObservable
  20833. */
  20834. var RenderingGroupInfo = /** @class */ (function () {
  20835. function RenderingGroupInfo() {
  20836. }
  20837. /**
  20838. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  20839. * This stage will be fired no matter what
  20840. */
  20841. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  20842. /**
  20843. * Called before opaque object are rendered.
  20844. * This stage will be fired only if there's 3D Opaque content to render
  20845. */
  20846. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  20847. /**
  20848. * Called after the opaque objects are rendered and before the transparent ones
  20849. * This stage will be fired only if there's 3D transparent content to render
  20850. */
  20851. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  20852. /**
  20853. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  20854. * This stage will be fired no matter what
  20855. */
  20856. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  20857. return RenderingGroupInfo;
  20858. }());
  20859. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  20860. /**
  20861. * Represents a scene to be rendered by the engine.
  20862. * @see http://doc.babylonjs.com/page.php?p=21911
  20863. */
  20864. var Scene = /** @class */ (function () {
  20865. /**
  20866. * @constructor
  20867. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  20868. */
  20869. function Scene(engine) {
  20870. // Members
  20871. this.autoClear = true;
  20872. this.autoClearDepthAndStencil = true;
  20873. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  20874. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  20875. this.forceWireframe = false;
  20876. this._forcePointsCloud = false;
  20877. this.forceShowBoundingBoxes = false;
  20878. this.animationsEnabled = true;
  20879. this.useConstantAnimationDeltaTime = false;
  20880. this.constantlyUpdateMeshUnderPointer = false;
  20881. this.hoverCursor = "pointer";
  20882. this.defaultCursor = "";
  20883. /**
  20884. * This is used to call preventDefault() on pointer down
  20885. * in order to block unwanted artifacts like system double clicks
  20886. */
  20887. this.preventDefaultOnPointerDown = true;
  20888. // Metadata
  20889. this.metadata = null;
  20890. /**
  20891. * An event triggered when the scene is disposed.
  20892. * @type {BABYLON.Observable}
  20893. */
  20894. this.onDisposeObservable = new BABYLON.Observable();
  20895. /**
  20896. * An event triggered before rendering the scene (right after animations and physics)
  20897. * @type {BABYLON.Observable}
  20898. */
  20899. this.onBeforeRenderObservable = new BABYLON.Observable();
  20900. /**
  20901. * An event triggered after rendering the scene
  20902. * @type {BABYLON.Observable}
  20903. */
  20904. this.onAfterRenderObservable = new BABYLON.Observable();
  20905. /**
  20906. * An event triggered before animating the scene
  20907. * @type {BABYLON.Observable}
  20908. */
  20909. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  20910. /**
  20911. * An event triggered after animations processing
  20912. * @type {BABYLON.Observable}
  20913. */
  20914. this.onAfterAnimationsObservable = new BABYLON.Observable();
  20915. /**
  20916. * An event triggered before draw calls are ready to be sent
  20917. * @type {BABYLON.Observable}
  20918. */
  20919. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  20920. /**
  20921. * An event triggered after draw calls have been sent
  20922. * @type {BABYLON.Observable}
  20923. */
  20924. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  20925. /**
  20926. * An event triggered when physic simulation is about to be run
  20927. * @type {BABYLON.Observable}
  20928. */
  20929. this.onBeforePhysicsObservable = new BABYLON.Observable();
  20930. /**
  20931. * An event triggered when physic simulation has been done
  20932. * @type {BABYLON.Observable}
  20933. */
  20934. this.onAfterPhysicsObservable = new BABYLON.Observable();
  20935. /**
  20936. * An event triggered when the scene is ready
  20937. * @type {BABYLON.Observable}
  20938. */
  20939. this.onReadyObservable = new BABYLON.Observable();
  20940. /**
  20941. * An event triggered before rendering a camera
  20942. * @type {BABYLON.Observable}
  20943. */
  20944. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  20945. /**
  20946. * An event triggered after rendering a camera
  20947. * @type {BABYLON.Observable}
  20948. */
  20949. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  20950. /**
  20951. * An event triggered when active meshes evaluation is about to start
  20952. * @type {BABYLON.Observable}
  20953. */
  20954. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20955. /**
  20956. * An event triggered when active meshes evaluation is done
  20957. * @type {BABYLON.Observable}
  20958. */
  20959. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  20960. /**
  20961. * An event triggered when particles rendering is about to start
  20962. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20963. * @type {BABYLON.Observable}
  20964. */
  20965. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  20966. /**
  20967. * An event triggered when particles rendering is done
  20968. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  20969. * @type {BABYLON.Observable}
  20970. */
  20971. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  20972. /**
  20973. * An event triggered when sprites rendering is about to start
  20974. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20975. * @type {BABYLON.Observable}
  20976. */
  20977. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  20978. /**
  20979. * An event triggered when sprites rendering is done
  20980. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  20981. * @type {BABYLON.Observable}
  20982. */
  20983. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  20984. /**
  20985. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  20986. * @type {BABYLON.Observable}
  20987. */
  20988. this.onDataLoadedObservable = new BABYLON.Observable();
  20989. /**
  20990. * An event triggered when a camera is created
  20991. * @type {BABYLON.Observable}
  20992. */
  20993. this.onNewCameraAddedObservable = new BABYLON.Observable();
  20994. /**
  20995. * An event triggered when a camera is removed
  20996. * @type {BABYLON.Observable}
  20997. */
  20998. this.onCameraRemovedObservable = new BABYLON.Observable();
  20999. /**
  21000. * An event triggered when a light is created
  21001. * @type {BABYLON.Observable}
  21002. */
  21003. this.onNewLightAddedObservable = new BABYLON.Observable();
  21004. /**
  21005. * An event triggered when a light is removed
  21006. * @type {BABYLON.Observable}
  21007. */
  21008. this.onLightRemovedObservable = new BABYLON.Observable();
  21009. /**
  21010. * An event triggered when a geometry is created
  21011. * @type {BABYLON.Observable}
  21012. */
  21013. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21014. /**
  21015. * An event triggered when a geometry is removed
  21016. * @type {BABYLON.Observable}
  21017. */
  21018. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21019. /**
  21020. * An event triggered when a transform node is created
  21021. * @type {BABYLON.Observable}
  21022. */
  21023. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21024. /**
  21025. * An event triggered when a transform node is removed
  21026. * @type {BABYLON.Observable}
  21027. */
  21028. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21029. /**
  21030. * An event triggered when a mesh is created
  21031. * @type {BABYLON.Observable}
  21032. */
  21033. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21034. /**
  21035. * An event triggered when a mesh is removed
  21036. * @type {BABYLON.Observable}
  21037. */
  21038. this.onMeshRemovedObservable = new BABYLON.Observable();
  21039. /**
  21040. * An event triggered when render targets are about to be rendered
  21041. * Can happen multiple times per frame.
  21042. * @type {BABYLON.Observable}
  21043. */
  21044. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21045. /**
  21046. * An event triggered when render targets were rendered.
  21047. * Can happen multiple times per frame.
  21048. * @type {BABYLON.Observable}
  21049. */
  21050. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21051. /**
  21052. * An event triggered before calculating deterministic simulation step
  21053. * @type {BABYLON.Observable}
  21054. */
  21055. this.onBeforeStepObservable = new BABYLON.Observable();
  21056. /**
  21057. * An event triggered after calculating deterministic simulation step
  21058. * @type {BABYLON.Observable}
  21059. */
  21060. this.onAfterStepObservable = new BABYLON.Observable();
  21061. /**
  21062. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21063. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21064. * 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)
  21065. */
  21066. this.onRenderingGroupObservable = new BABYLON.Observable();
  21067. // Animations
  21068. this.animations = [];
  21069. /**
  21070. * 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).
  21071. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21072. */
  21073. this.onPrePointerObservable = new BABYLON.Observable();
  21074. /**
  21075. * Observable event triggered each time an input event is received from the rendering canvas
  21076. */
  21077. this.onPointerObservable = new BABYLON.Observable();
  21078. this._meshPickProceed = false;
  21079. this._currentPickResult = null;
  21080. this._previousPickResult = null;
  21081. this._totalPointersPressed = 0;
  21082. this._doubleClickOccured = false;
  21083. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21084. this.cameraToUseForPointers = null;
  21085. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21086. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21087. this._startingPointerTime = 0;
  21088. this._previousStartingPointerTime = 0;
  21089. // Deterministic lockstep
  21090. this._timeAccumulator = 0;
  21091. this._currentStepId = 0;
  21092. this._currentInternalStep = 0;
  21093. // Keyboard
  21094. /**
  21095. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21096. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21097. */
  21098. this.onPreKeyboardObservable = new BABYLON.Observable();
  21099. /**
  21100. * Observable event triggered each time an keyboard event is received from the hosting window
  21101. */
  21102. this.onKeyboardObservable = new BABYLON.Observable();
  21103. // Coordinate system
  21104. /**
  21105. * use right-handed coordinate system on this scene.
  21106. * @type {boolean}
  21107. */
  21108. this._useRightHandedSystem = false;
  21109. // Fog
  21110. this._fogEnabled = true;
  21111. this._fogMode = Scene.FOGMODE_NONE;
  21112. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21113. this.fogDensity = 0.1;
  21114. this.fogStart = 0;
  21115. this.fogEnd = 1000.0;
  21116. // Lights
  21117. /**
  21118. * is shadow enabled on this scene.
  21119. * @type {boolean}
  21120. */
  21121. this._shadowsEnabled = true;
  21122. /**
  21123. * is light enabled on this scene.
  21124. * @type {boolean}
  21125. */
  21126. this._lightsEnabled = true;
  21127. /**
  21128. * All of the lights added to this scene.
  21129. * @see BABYLON.Light
  21130. * @type {BABYLON.Light[]}
  21131. */
  21132. this.lights = new Array();
  21133. // Cameras
  21134. /** All of the cameras added to this scene. */
  21135. this.cameras = new Array();
  21136. /** All of the active cameras added to this scene. */
  21137. this.activeCameras = new Array();
  21138. // Meshes
  21139. /**
  21140. * All of the tranform nodes added to this scene.
  21141. * @see BABYLON.TransformNode
  21142. * @type {BABYLON.TransformNode[]}
  21143. */
  21144. this.transformNodes = new Array();
  21145. /**
  21146. * All of the (abstract) meshes added to this scene.
  21147. * @see BABYLON.AbstractMesh
  21148. * @type {BABYLON.AbstractMesh[]}
  21149. */
  21150. this.meshes = new Array();
  21151. /**
  21152. * All of the animation groups added to this scene.
  21153. * @see BABYLON.AnimationGroup
  21154. * @type {BABYLON.AnimationGroup[]}
  21155. */
  21156. this.animationGroups = new Array();
  21157. // Geometries
  21158. this._geometries = new Array();
  21159. this.materials = new Array();
  21160. this.multiMaterials = new Array();
  21161. // Textures
  21162. this._texturesEnabled = true;
  21163. this.textures = new Array();
  21164. // Particles
  21165. this.particlesEnabled = true;
  21166. this.particleSystems = new Array();
  21167. // Sprites
  21168. this.spritesEnabled = true;
  21169. this.spriteManagers = new Array();
  21170. /**
  21171. * The list of layers (background and foreground) of the scene.
  21172. */
  21173. this.layers = new Array();
  21174. /**
  21175. * The list of effect layers (highlights/glow) contained in the scene.
  21176. */
  21177. this.effectLayers = new Array();
  21178. // Skeletons
  21179. this._skeletonsEnabled = true;
  21180. this.skeletons = new Array();
  21181. // Morph targets
  21182. this.morphTargetManagers = new Array();
  21183. // Lens flares
  21184. this.lensFlaresEnabled = true;
  21185. this.lensFlareSystems = new Array();
  21186. // Collisions
  21187. this.collisionsEnabled = true;
  21188. /** Defines the gravity applied to this scene */
  21189. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21190. // Postprocesses
  21191. this.postProcesses = new Array();
  21192. this.postProcessesEnabled = true;
  21193. // Customs render targets
  21194. this.renderTargetsEnabled = true;
  21195. this.dumpNextRenderTargets = false;
  21196. this.customRenderTargets = new Array();
  21197. // Imported meshes
  21198. this.importedMeshesFiles = new Array();
  21199. // Probes
  21200. this.probesEnabled = true;
  21201. this.reflectionProbes = new Array();
  21202. this._actionManagers = new Array();
  21203. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21204. // Procedural textures
  21205. this.proceduralTexturesEnabled = true;
  21206. this._proceduralTextures = new Array();
  21207. this.soundTracks = new Array();
  21208. this._audioEnabled = true;
  21209. this._headphone = false;
  21210. // Performance counters
  21211. this._totalVertices = new BABYLON.PerfCounter();
  21212. this._activeIndices = new BABYLON.PerfCounter();
  21213. this._activeParticles = new BABYLON.PerfCounter();
  21214. this._activeBones = new BABYLON.PerfCounter();
  21215. this._animationTime = 0;
  21216. this.animationTimeScale = 1;
  21217. this._renderId = 0;
  21218. this._executeWhenReadyTimeoutId = -1;
  21219. this._intermediateRendering = false;
  21220. this._viewUpdateFlag = -1;
  21221. this._projectionUpdateFlag = -1;
  21222. this._alternateViewUpdateFlag = -1;
  21223. this._alternateProjectionUpdateFlag = -1;
  21224. this._toBeDisposed = new BABYLON.SmartArray(256);
  21225. this._activeRequests = new Array();
  21226. this._pendingData = new Array();
  21227. this._isDisposed = false;
  21228. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21229. this._activeMeshes = new BABYLON.SmartArray(256);
  21230. this._processedMaterials = new BABYLON.SmartArray(256);
  21231. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21232. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21233. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21234. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21235. this._activeAnimatables = new Array();
  21236. this._transformMatrix = BABYLON.Matrix.Zero();
  21237. this._useAlternateCameraConfiguration = false;
  21238. this._alternateRendering = false;
  21239. this.requireLightSorting = false;
  21240. this._activeMeshesFrozen = false;
  21241. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21242. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21243. this._engine.scenes.push(this);
  21244. this._uid = null;
  21245. this._renderingManager = new BABYLON.RenderingManager(this);
  21246. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21247. if (BABYLON.OutlineRenderer) {
  21248. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21249. }
  21250. if (BABYLON.Tools.IsWindowObjectExist()) {
  21251. this.attachControl();
  21252. }
  21253. //simplification queue
  21254. if (BABYLON.SimplificationQueue) {
  21255. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21256. }
  21257. //collision coordinator initialization. For now legacy per default.
  21258. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21259. // Uniform Buffer
  21260. this._createUbo();
  21261. // Default Image processing definition.
  21262. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21263. }
  21264. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21265. /** The fog is deactivated */
  21266. get: function () {
  21267. return Scene._FOGMODE_NONE;
  21268. },
  21269. enumerable: true,
  21270. configurable: true
  21271. });
  21272. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21273. /** The fog density is following an exponential function */
  21274. get: function () {
  21275. return Scene._FOGMODE_EXP;
  21276. },
  21277. enumerable: true,
  21278. configurable: true
  21279. });
  21280. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21281. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21282. get: function () {
  21283. return Scene._FOGMODE_EXP2;
  21284. },
  21285. enumerable: true,
  21286. configurable: true
  21287. });
  21288. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21289. /** The fog density is following a linear function. */
  21290. get: function () {
  21291. return Scene._FOGMODE_LINEAR;
  21292. },
  21293. enumerable: true,
  21294. configurable: true
  21295. });
  21296. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21297. /**
  21298. * Texture used in all pbr material as the reflection texture.
  21299. * As in the majority of the scene they are the same (exception for multi room and so on),
  21300. * this is easier to reference from here than from all the materials.
  21301. */
  21302. get: function () {
  21303. return this._environmentTexture;
  21304. },
  21305. /**
  21306. * Texture used in all pbr material as the reflection texture.
  21307. * As in the majority of the scene they are the same (exception for multi room and so on),
  21308. * this is easier to set here than in all the materials.
  21309. */
  21310. set: function (value) {
  21311. if (this._environmentTexture === value) {
  21312. return;
  21313. }
  21314. this._environmentTexture = value;
  21315. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21316. },
  21317. enumerable: true,
  21318. configurable: true
  21319. });
  21320. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  21321. /**
  21322. * Default image processing configuration used either in the rendering
  21323. * Forward main pass or through the imageProcessingPostProcess if present.
  21324. * As in the majority of the scene they are the same (exception for multi camera),
  21325. * this is easier to reference from here than from all the materials and post process.
  21326. *
  21327. * No setter as we it is a shared configuration, you can set the values instead.
  21328. */
  21329. get: function () {
  21330. return this._imageProcessingConfiguration;
  21331. },
  21332. enumerable: true,
  21333. configurable: true
  21334. });
  21335. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  21336. get: function () {
  21337. return this._forcePointsCloud;
  21338. },
  21339. set: function (value) {
  21340. if (this._forcePointsCloud === value) {
  21341. return;
  21342. }
  21343. this._forcePointsCloud = value;
  21344. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21345. },
  21346. enumerable: true,
  21347. configurable: true
  21348. });
  21349. Object.defineProperty(Scene.prototype, "onDispose", {
  21350. /** A function to be executed when this scene is disposed. */
  21351. set: function (callback) {
  21352. if (this._onDisposeObserver) {
  21353. this.onDisposeObservable.remove(this._onDisposeObserver);
  21354. }
  21355. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  21356. },
  21357. enumerable: true,
  21358. configurable: true
  21359. });
  21360. Object.defineProperty(Scene.prototype, "beforeRender", {
  21361. /** A function to be executed before rendering this scene */
  21362. set: function (callback) {
  21363. if (this._onBeforeRenderObserver) {
  21364. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  21365. }
  21366. if (callback) {
  21367. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  21368. }
  21369. },
  21370. enumerable: true,
  21371. configurable: true
  21372. });
  21373. Object.defineProperty(Scene.prototype, "afterRender", {
  21374. /** A function to be executed after rendering this scene */
  21375. set: function (callback) {
  21376. if (this._onAfterRenderObserver) {
  21377. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  21378. }
  21379. if (callback) {
  21380. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  21381. }
  21382. },
  21383. enumerable: true,
  21384. configurable: true
  21385. });
  21386. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  21387. set: function (callback) {
  21388. if (this._onBeforeCameraRenderObserver) {
  21389. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  21390. }
  21391. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  21392. },
  21393. enumerable: true,
  21394. configurable: true
  21395. });
  21396. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  21397. set: function (callback) {
  21398. if (this._onAfterCameraRenderObserver) {
  21399. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  21400. }
  21401. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  21402. },
  21403. enumerable: true,
  21404. configurable: true
  21405. });
  21406. Object.defineProperty(Scene.prototype, "gamepadManager", {
  21407. get: function () {
  21408. if (!this._gamepadManager) {
  21409. this._gamepadManager = new BABYLON.GamepadManager(this);
  21410. }
  21411. return this._gamepadManager;
  21412. },
  21413. enumerable: true,
  21414. configurable: true
  21415. });
  21416. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  21417. get: function () {
  21418. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  21419. },
  21420. enumerable: true,
  21421. configurable: true
  21422. });
  21423. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  21424. get: function () {
  21425. return this._useRightHandedSystem;
  21426. },
  21427. set: function (value) {
  21428. if (this._useRightHandedSystem === value) {
  21429. return;
  21430. }
  21431. this._useRightHandedSystem = value;
  21432. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21433. },
  21434. enumerable: true,
  21435. configurable: true
  21436. });
  21437. Scene.prototype.setStepId = function (newStepId) {
  21438. this._currentStepId = newStepId;
  21439. };
  21440. ;
  21441. Scene.prototype.getStepId = function () {
  21442. return this._currentStepId;
  21443. };
  21444. ;
  21445. Scene.prototype.getInternalStep = function () {
  21446. return this._currentInternalStep;
  21447. };
  21448. ;
  21449. Object.defineProperty(Scene.prototype, "fogEnabled", {
  21450. get: function () {
  21451. return this._fogEnabled;
  21452. },
  21453. /**
  21454. * is fog enabled on this scene.
  21455. */
  21456. set: function (value) {
  21457. if (this._fogEnabled === value) {
  21458. return;
  21459. }
  21460. this._fogEnabled = value;
  21461. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21462. },
  21463. enumerable: true,
  21464. configurable: true
  21465. });
  21466. Object.defineProperty(Scene.prototype, "fogMode", {
  21467. get: function () {
  21468. return this._fogMode;
  21469. },
  21470. set: function (value) {
  21471. if (this._fogMode === value) {
  21472. return;
  21473. }
  21474. this._fogMode = value;
  21475. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  21476. },
  21477. enumerable: true,
  21478. configurable: true
  21479. });
  21480. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  21481. get: function () {
  21482. return this._shadowsEnabled;
  21483. },
  21484. set: function (value) {
  21485. if (this._shadowsEnabled === value) {
  21486. return;
  21487. }
  21488. this._shadowsEnabled = value;
  21489. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21490. },
  21491. enumerable: true,
  21492. configurable: true
  21493. });
  21494. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  21495. get: function () {
  21496. return this._lightsEnabled;
  21497. },
  21498. set: function (value) {
  21499. if (this._lightsEnabled === value) {
  21500. return;
  21501. }
  21502. this._lightsEnabled = value;
  21503. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  21504. },
  21505. enumerable: true,
  21506. configurable: true
  21507. });
  21508. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  21509. /** The default material used on meshes when no material is affected */
  21510. get: function () {
  21511. if (!this._defaultMaterial) {
  21512. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  21513. }
  21514. return this._defaultMaterial;
  21515. },
  21516. /** The default material used on meshes when no material is affected */
  21517. set: function (value) {
  21518. this._defaultMaterial = value;
  21519. },
  21520. enumerable: true,
  21521. configurable: true
  21522. });
  21523. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  21524. get: function () {
  21525. return this._texturesEnabled;
  21526. },
  21527. set: function (value) {
  21528. if (this._texturesEnabled === value) {
  21529. return;
  21530. }
  21531. this._texturesEnabled = value;
  21532. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  21533. },
  21534. enumerable: true,
  21535. configurable: true
  21536. });
  21537. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  21538. get: function () {
  21539. return this._skeletonsEnabled;
  21540. },
  21541. set: function (value) {
  21542. if (this._skeletonsEnabled === value) {
  21543. return;
  21544. }
  21545. this._skeletonsEnabled = value;
  21546. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  21547. },
  21548. enumerable: true,
  21549. configurable: true
  21550. });
  21551. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  21552. get: function () {
  21553. if (!this._postProcessRenderPipelineManager) {
  21554. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  21555. }
  21556. return this._postProcessRenderPipelineManager;
  21557. },
  21558. enumerable: true,
  21559. configurable: true
  21560. });
  21561. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  21562. get: function () {
  21563. if (!this._mainSoundTrack) {
  21564. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  21565. }
  21566. return this._mainSoundTrack;
  21567. },
  21568. enumerable: true,
  21569. configurable: true
  21570. });
  21571. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  21572. get: function () {
  21573. return this._alternateRendering;
  21574. },
  21575. enumerable: true,
  21576. configurable: true
  21577. });
  21578. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  21579. get: function () {
  21580. return this._frustumPlanes;
  21581. },
  21582. enumerable: true,
  21583. configurable: true
  21584. });
  21585. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  21586. /**
  21587. * Gets the current geometry buffer associated to the scene.
  21588. */
  21589. get: function () {
  21590. return this._geometryBufferRenderer;
  21591. },
  21592. /**
  21593. * Sets the current geometry buffer for the scene.
  21594. */
  21595. set: function (geometryBufferRenderer) {
  21596. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  21597. this._geometryBufferRenderer = geometryBufferRenderer;
  21598. }
  21599. },
  21600. enumerable: true,
  21601. configurable: true
  21602. });
  21603. Object.defineProperty(Scene.prototype, "debugLayer", {
  21604. // Properties
  21605. get: function () {
  21606. if (!this._debugLayer) {
  21607. this._debugLayer = new BABYLON.DebugLayer(this);
  21608. }
  21609. return this._debugLayer;
  21610. },
  21611. enumerable: true,
  21612. configurable: true
  21613. });
  21614. Object.defineProperty(Scene.prototype, "workerCollisions", {
  21615. get: function () {
  21616. return this._workerCollisions;
  21617. },
  21618. set: function (enabled) {
  21619. if (!BABYLON.CollisionCoordinatorLegacy) {
  21620. return;
  21621. }
  21622. enabled = (enabled && !!Worker);
  21623. this._workerCollisions = enabled;
  21624. if (this.collisionCoordinator) {
  21625. this.collisionCoordinator.destroy();
  21626. }
  21627. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  21628. this.collisionCoordinator.init(this);
  21629. },
  21630. enumerable: true,
  21631. configurable: true
  21632. });
  21633. Object.defineProperty(Scene.prototype, "selectionOctree", {
  21634. get: function () {
  21635. return this._selectionOctree;
  21636. },
  21637. enumerable: true,
  21638. configurable: true
  21639. });
  21640. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  21641. /**
  21642. * The mesh that is currently under the pointer.
  21643. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  21644. */
  21645. get: function () {
  21646. return this._pointerOverMesh;
  21647. },
  21648. enumerable: true,
  21649. configurable: true
  21650. });
  21651. Object.defineProperty(Scene.prototype, "pointerX", {
  21652. /**
  21653. * Current on-screen X position of the pointer
  21654. * @return {number} X position of the pointer
  21655. */
  21656. get: function () {
  21657. return this._pointerX;
  21658. },
  21659. enumerable: true,
  21660. configurable: true
  21661. });
  21662. Object.defineProperty(Scene.prototype, "pointerY", {
  21663. /**
  21664. * Current on-screen Y position of the pointer
  21665. * @return {number} Y position of the pointer
  21666. */
  21667. get: function () {
  21668. return this._pointerY;
  21669. },
  21670. enumerable: true,
  21671. configurable: true
  21672. });
  21673. Scene.prototype.getCachedMaterial = function () {
  21674. return this._cachedMaterial;
  21675. };
  21676. Scene.prototype.getCachedEffect = function () {
  21677. return this._cachedEffect;
  21678. };
  21679. Scene.prototype.getCachedVisibility = function () {
  21680. return this._cachedVisibility;
  21681. };
  21682. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  21683. if (visibility === void 0) { visibility = 1; }
  21684. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  21685. };
  21686. Scene.prototype.getBoundingBoxRenderer = function () {
  21687. if (!this._boundingBoxRenderer) {
  21688. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  21689. }
  21690. return this._boundingBoxRenderer;
  21691. };
  21692. Scene.prototype.getOutlineRenderer = function () {
  21693. return this._outlineRenderer;
  21694. };
  21695. Scene.prototype.getEngine = function () {
  21696. return this._engine;
  21697. };
  21698. Scene.prototype.getTotalVertices = function () {
  21699. return this._totalVertices.current;
  21700. };
  21701. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  21702. get: function () {
  21703. return this._totalVertices;
  21704. },
  21705. enumerable: true,
  21706. configurable: true
  21707. });
  21708. Scene.prototype.getActiveIndices = function () {
  21709. return this._activeIndices.current;
  21710. };
  21711. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  21712. get: function () {
  21713. return this._activeIndices;
  21714. },
  21715. enumerable: true,
  21716. configurable: true
  21717. });
  21718. Scene.prototype.getActiveParticles = function () {
  21719. return this._activeParticles.current;
  21720. };
  21721. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  21722. get: function () {
  21723. return this._activeParticles;
  21724. },
  21725. enumerable: true,
  21726. configurable: true
  21727. });
  21728. Scene.prototype.getActiveBones = function () {
  21729. return this._activeBones.current;
  21730. };
  21731. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  21732. get: function () {
  21733. return this._activeBones;
  21734. },
  21735. enumerable: true,
  21736. configurable: true
  21737. });
  21738. // Stats
  21739. Scene.prototype.getInterFramePerfCounter = function () {
  21740. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21741. return 0;
  21742. };
  21743. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  21744. get: function () {
  21745. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21746. return null;
  21747. },
  21748. enumerable: true,
  21749. configurable: true
  21750. });
  21751. Scene.prototype.getLastFrameDuration = function () {
  21752. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  21753. return 0;
  21754. };
  21755. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  21756. get: function () {
  21757. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  21758. return null;
  21759. },
  21760. enumerable: true,
  21761. configurable: true
  21762. });
  21763. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  21764. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  21765. return 0;
  21766. };
  21767. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  21768. get: function () {
  21769. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21770. return null;
  21771. },
  21772. enumerable: true,
  21773. configurable: true
  21774. });
  21775. Scene.prototype.getActiveMeshes = function () {
  21776. return this._activeMeshes;
  21777. };
  21778. Scene.prototype.getRenderTargetsDuration = function () {
  21779. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  21780. return 0;
  21781. };
  21782. Scene.prototype.getRenderDuration = function () {
  21783. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  21784. return 0;
  21785. };
  21786. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  21787. get: function () {
  21788. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21789. return null;
  21790. },
  21791. enumerable: true,
  21792. configurable: true
  21793. });
  21794. Scene.prototype.getParticlesDuration = function () {
  21795. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  21796. return 0;
  21797. };
  21798. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  21799. get: function () {
  21800. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  21801. return null;
  21802. },
  21803. enumerable: true,
  21804. configurable: true
  21805. });
  21806. Scene.prototype.getSpritesDuration = function () {
  21807. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  21808. return 0;
  21809. };
  21810. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  21811. get: function () {
  21812. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  21813. return null;
  21814. },
  21815. enumerable: true,
  21816. configurable: true
  21817. });
  21818. Scene.prototype.getAnimationRatio = function () {
  21819. return this._animationRatio;
  21820. };
  21821. Scene.prototype.getRenderId = function () {
  21822. return this._renderId;
  21823. };
  21824. Scene.prototype.incrementRenderId = function () {
  21825. this._renderId++;
  21826. };
  21827. Scene.prototype._updatePointerPosition = function (evt) {
  21828. var canvasRect = this._engine.getRenderingCanvasClientRect();
  21829. if (!canvasRect) {
  21830. return;
  21831. }
  21832. this._pointerX = evt.clientX - canvasRect.left;
  21833. this._pointerY = evt.clientY - canvasRect.top;
  21834. this._unTranslatedPointerX = this._pointerX;
  21835. this._unTranslatedPointerY = this._pointerY;
  21836. };
  21837. Scene.prototype._createUbo = function () {
  21838. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21839. this._sceneUbo.addUniform("viewProjection", 16);
  21840. this._sceneUbo.addUniform("view", 16);
  21841. };
  21842. Scene.prototype._createAlternateUbo = function () {
  21843. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  21844. this._alternateSceneUbo.addUniform("viewProjection", 16);
  21845. this._alternateSceneUbo.addUniform("view", 16);
  21846. };
  21847. // Pointers handling
  21848. /**
  21849. * Use this method to simulate a pointer move on a mesh
  21850. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21851. */
  21852. Scene.prototype.simulatePointerMove = function (pickResult) {
  21853. var evt = new PointerEvent("pointermove");
  21854. return this._processPointerMove(pickResult, evt);
  21855. };
  21856. Scene.prototype._processPointerMove = function (pickResult, evt) {
  21857. var canvas = this._engine.getRenderingCanvas();
  21858. if (!canvas) {
  21859. return this;
  21860. }
  21861. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21862. this.setPointerOverSprite(null);
  21863. this.setPointerOverMesh(pickResult.pickedMesh);
  21864. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  21865. if (this._pointerOverMesh.actionManager.hoverCursor) {
  21866. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  21867. }
  21868. else {
  21869. canvas.style.cursor = this.hoverCursor;
  21870. }
  21871. }
  21872. else {
  21873. canvas.style.cursor = this.defaultCursor;
  21874. }
  21875. }
  21876. else {
  21877. this.setPointerOverMesh(null);
  21878. // Sprites
  21879. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  21880. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  21881. this.setPointerOverSprite(pickResult.pickedSprite);
  21882. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  21883. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  21884. }
  21885. else {
  21886. canvas.style.cursor = this.hoverCursor;
  21887. }
  21888. }
  21889. else {
  21890. this.setPointerOverSprite(null);
  21891. // Restore pointer
  21892. canvas.style.cursor = this.defaultCursor;
  21893. }
  21894. }
  21895. if (pickResult) {
  21896. if (this.onPointerMove) {
  21897. this.onPointerMove(evt, pickResult);
  21898. }
  21899. if (this.onPointerObservable.hasObservers()) {
  21900. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  21901. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21902. this.onPointerObservable.notifyObservers(pi, type);
  21903. }
  21904. }
  21905. return this;
  21906. };
  21907. /**
  21908. * Use this method to simulate a pointer down on a mesh
  21909. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21910. */
  21911. Scene.prototype.simulatePointerDown = function (pickResult) {
  21912. var evt = new PointerEvent("pointerdown");
  21913. return this._processPointerDown(pickResult, evt);
  21914. };
  21915. Scene.prototype._processPointerDown = function (pickResult, evt) {
  21916. var _this = this;
  21917. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  21918. this._pickedDownMesh = pickResult.pickedMesh;
  21919. var actionManager = pickResult.pickedMesh.actionManager;
  21920. if (actionManager) {
  21921. if (actionManager.hasPickTriggers) {
  21922. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21923. switch (evt.button) {
  21924. case 0:
  21925. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21926. break;
  21927. case 1:
  21928. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21929. break;
  21930. case 2:
  21931. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21932. break;
  21933. }
  21934. }
  21935. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  21936. window.setTimeout(function () {
  21937. 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);
  21938. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  21939. if (_this._totalPointersPressed !== 0 &&
  21940. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  21941. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  21942. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  21943. _this._startingPointerTime = 0;
  21944. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21945. }
  21946. }
  21947. }, Scene.LongPressDelay);
  21948. }
  21949. }
  21950. }
  21951. if (pickResult) {
  21952. if (this.onPointerDown) {
  21953. this.onPointerDown(evt, pickResult);
  21954. }
  21955. if (this.onPointerObservable.hasObservers()) {
  21956. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  21957. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21958. this.onPointerObservable.notifyObservers(pi, type);
  21959. }
  21960. }
  21961. return this;
  21962. };
  21963. /**
  21964. * Use this method to simulate a pointer up on a mesh
  21965. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  21966. */
  21967. Scene.prototype.simulatePointerUp = function (pickResult) {
  21968. var evt = new PointerEvent("pointerup");
  21969. var clickInfo = new ClickInfo();
  21970. clickInfo.singleClick = true;
  21971. clickInfo.ignore = true;
  21972. return this._processPointerUp(pickResult, evt, clickInfo);
  21973. };
  21974. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  21975. if (pickResult && pickResult && pickResult.pickedMesh) {
  21976. this._pickedUpMesh = pickResult.pickedMesh;
  21977. if (this._pickedDownMesh === this._pickedUpMesh) {
  21978. if (this.onPointerPick) {
  21979. this.onPointerPick(evt, pickResult);
  21980. }
  21981. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  21982. var type = BABYLON.PointerEventTypes.POINTERPICK;
  21983. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  21984. this.onPointerObservable.notifyObservers(pi, type);
  21985. }
  21986. }
  21987. if (pickResult.pickedMesh.actionManager) {
  21988. if (clickInfo.ignore) {
  21989. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21990. }
  21991. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  21992. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21993. }
  21994. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  21995. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  21996. }
  21997. }
  21998. }
  21999. if (this._pickedDownMesh &&
  22000. this._pickedDownMesh.actionManager &&
  22001. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22002. this._pickedDownMesh !== this._pickedUpMesh) {
  22003. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22004. }
  22005. if (this.onPointerUp) {
  22006. this.onPointerUp(evt, pickResult);
  22007. }
  22008. if (this.onPointerObservable.hasObservers()) {
  22009. if (!clickInfo.ignore) {
  22010. if (!clickInfo.hasSwiped) {
  22011. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22012. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22013. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22014. this.onPointerObservable.notifyObservers(pi, type);
  22015. }
  22016. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22017. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22018. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22019. this.onPointerObservable.notifyObservers(pi, type);
  22020. }
  22021. }
  22022. }
  22023. else {
  22024. var type = BABYLON.PointerEventTypes.POINTERUP;
  22025. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22026. this.onPointerObservable.notifyObservers(pi, type);
  22027. }
  22028. }
  22029. return this;
  22030. };
  22031. /**
  22032. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22033. * @param attachUp defines if you want to attach events to pointerup
  22034. * @param attachDown defines if you want to attach events to pointerdown
  22035. * @param attachMove defines if you want to attach events to pointermove
  22036. */
  22037. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22038. var _this = this;
  22039. if (attachUp === void 0) { attachUp = true; }
  22040. if (attachDown === void 0) { attachDown = true; }
  22041. if (attachMove === void 0) { attachMove = true; }
  22042. this._initActionManager = function (act, clickInfo) {
  22043. if (!_this._meshPickProceed) {
  22044. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22045. _this._currentPickResult = pickResult;
  22046. if (pickResult) {
  22047. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22048. }
  22049. _this._meshPickProceed = true;
  22050. }
  22051. return act;
  22052. };
  22053. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22054. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22055. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22056. btn !== _this._previousButtonPressed) {
  22057. _this._doubleClickOccured = false;
  22058. clickInfo.singleClick = true;
  22059. clickInfo.ignore = false;
  22060. cb(clickInfo, _this._currentPickResult);
  22061. }
  22062. };
  22063. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22064. var clickInfo = new ClickInfo();
  22065. _this._currentPickResult = null;
  22066. var act = null;
  22067. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22068. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22069. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22070. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22071. act = _this._initActionManager(act, clickInfo);
  22072. if (act)
  22073. checkPicking = act.hasPickTriggers;
  22074. }
  22075. if (checkPicking) {
  22076. var btn = evt.button;
  22077. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22078. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22079. if (!clickInfo.hasSwiped) {
  22080. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22081. if (!checkSingleClickImmediately) {
  22082. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22083. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22084. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22085. act = _this._initActionManager(act, clickInfo);
  22086. if (act)
  22087. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22088. }
  22089. }
  22090. if (checkSingleClickImmediately) {
  22091. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22092. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22093. btn !== _this._previousButtonPressed) {
  22094. clickInfo.singleClick = true;
  22095. cb(clickInfo, _this._currentPickResult);
  22096. }
  22097. }
  22098. else {
  22099. // wait that no double click has been raised during the double click delay
  22100. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22101. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22102. }
  22103. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22104. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22105. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22106. act = _this._initActionManager(act, clickInfo);
  22107. if (act)
  22108. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22109. }
  22110. if (checkDoubleClick) {
  22111. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22112. if (btn === _this._previousButtonPressed &&
  22113. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22114. !_this._doubleClickOccured) {
  22115. // pointer has not moved for 2 clicks, it's a double click
  22116. if (!clickInfo.hasSwiped &&
  22117. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22118. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22119. _this._previousStartingPointerTime = 0;
  22120. _this._doubleClickOccured = true;
  22121. clickInfo.doubleClick = true;
  22122. clickInfo.ignore = false;
  22123. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22124. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22125. }
  22126. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22127. cb(clickInfo, _this._currentPickResult);
  22128. }
  22129. else {
  22130. _this._doubleClickOccured = false;
  22131. _this._previousStartingPointerTime = _this._startingPointerTime;
  22132. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22133. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22134. _this._previousButtonPressed = btn;
  22135. if (Scene.ExclusiveDoubleClickMode) {
  22136. if (_this._previousDelayedSimpleClickTimeout) {
  22137. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22138. }
  22139. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22140. cb(clickInfo, _this._previousPickResult);
  22141. }
  22142. else {
  22143. cb(clickInfo, _this._currentPickResult);
  22144. }
  22145. }
  22146. }
  22147. else {
  22148. _this._doubleClickOccured = false;
  22149. _this._previousStartingPointerTime = _this._startingPointerTime;
  22150. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22151. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22152. _this._previousButtonPressed = btn;
  22153. }
  22154. }
  22155. }
  22156. }
  22157. clickInfo.ignore = true;
  22158. cb(clickInfo, _this._currentPickResult);
  22159. };
  22160. this._spritePredicate = function (sprite) {
  22161. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22162. };
  22163. this._onPointerMove = function (evt) {
  22164. _this._updatePointerPosition(evt);
  22165. // PreObservable support
  22166. if (_this.onPrePointerObservable.hasObservers()) {
  22167. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22168. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22169. _this.onPrePointerObservable.notifyObservers(pi, type);
  22170. if (pi.skipOnPointerObservable) {
  22171. return;
  22172. }
  22173. }
  22174. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22175. return;
  22176. }
  22177. if (!_this.pointerMovePredicate) {
  22178. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22179. }
  22180. // Meshes
  22181. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22182. _this._processPointerMove(pickResult, evt);
  22183. };
  22184. this._onPointerDown = function (evt) {
  22185. _this._totalPointersPressed++;
  22186. _this._pickedDownMesh = null;
  22187. _this._meshPickProceed = false;
  22188. _this._updatePointerPosition(evt);
  22189. if (_this.preventDefaultOnPointerDown && canvas) {
  22190. evt.preventDefault();
  22191. canvas.focus();
  22192. }
  22193. // PreObservable support
  22194. if (_this.onPrePointerObservable.hasObservers()) {
  22195. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22196. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22197. _this.onPrePointerObservable.notifyObservers(pi, type);
  22198. if (pi.skipOnPointerObservable) {
  22199. return;
  22200. }
  22201. }
  22202. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22203. return;
  22204. }
  22205. _this._startingPointerPosition.x = _this._pointerX;
  22206. _this._startingPointerPosition.y = _this._pointerY;
  22207. _this._startingPointerTime = new Date().getTime();
  22208. if (!_this.pointerDownPredicate) {
  22209. _this.pointerDownPredicate = function (mesh) {
  22210. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22211. };
  22212. }
  22213. // Meshes
  22214. _this._pickedDownMesh = null;
  22215. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22216. _this._processPointerDown(pickResult, evt);
  22217. // Sprites
  22218. _this._pickedDownSprite = null;
  22219. if (_this.spriteManagers.length > 0) {
  22220. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22221. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22222. if (pickResult.pickedSprite.actionManager) {
  22223. _this._pickedDownSprite = pickResult.pickedSprite;
  22224. switch (evt.button) {
  22225. case 0:
  22226. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22227. break;
  22228. case 1:
  22229. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22230. break;
  22231. case 2:
  22232. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22233. break;
  22234. }
  22235. if (pickResult.pickedSprite.actionManager) {
  22236. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22237. }
  22238. }
  22239. }
  22240. }
  22241. };
  22242. this._onPointerUp = function (evt) {
  22243. if (_this._totalPointersPressed === 0) {
  22244. return; // So we need to test it the pointer down was pressed before.
  22245. }
  22246. _this._totalPointersPressed--;
  22247. _this._pickedUpMesh = null;
  22248. _this._meshPickProceed = false;
  22249. _this._updatePointerPosition(evt);
  22250. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22251. // PreObservable support
  22252. if (_this.onPrePointerObservable.hasObservers()) {
  22253. if (!clickInfo.ignore) {
  22254. if (!clickInfo.hasSwiped) {
  22255. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22256. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22257. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22258. _this.onPrePointerObservable.notifyObservers(pi, type);
  22259. if (pi.skipOnPointerObservable) {
  22260. return;
  22261. }
  22262. }
  22263. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22264. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22265. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22266. _this.onPrePointerObservable.notifyObservers(pi, type);
  22267. if (pi.skipOnPointerObservable) {
  22268. return;
  22269. }
  22270. }
  22271. }
  22272. }
  22273. else {
  22274. var type = BABYLON.PointerEventTypes.POINTERUP;
  22275. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22276. _this.onPrePointerObservable.notifyObservers(pi, type);
  22277. if (pi.skipOnPointerObservable) {
  22278. return;
  22279. }
  22280. }
  22281. }
  22282. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22283. return;
  22284. }
  22285. if (!_this.pointerUpPredicate) {
  22286. _this.pointerUpPredicate = function (mesh) {
  22287. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22288. };
  22289. }
  22290. // Meshes
  22291. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  22292. _this._initActionManager(null, clickInfo);
  22293. }
  22294. if (!pickResult) {
  22295. pickResult = _this._currentPickResult;
  22296. }
  22297. _this._processPointerUp(pickResult, evt, clickInfo);
  22298. // Sprites
  22299. if (_this.spriteManagers.length > 0) {
  22300. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22301. if (spritePickResult) {
  22302. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  22303. if (spritePickResult.pickedSprite.actionManager) {
  22304. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22305. if (spritePickResult.pickedSprite.actionManager) {
  22306. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  22307. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  22308. }
  22309. }
  22310. }
  22311. }
  22312. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  22313. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  22314. }
  22315. }
  22316. }
  22317. _this._previousPickResult = _this._currentPickResult;
  22318. });
  22319. };
  22320. this._onKeyDown = function (evt) {
  22321. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  22322. if (_this.onPreKeyboardObservable.hasObservers()) {
  22323. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22324. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22325. if (pi.skipOnPointerObservable) {
  22326. return;
  22327. }
  22328. }
  22329. if (_this.onKeyboardObservable.hasObservers()) {
  22330. var pi = new BABYLON.KeyboardInfo(type, evt);
  22331. _this.onKeyboardObservable.notifyObservers(pi, type);
  22332. }
  22333. if (_this.actionManager) {
  22334. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22335. }
  22336. };
  22337. this._onKeyUp = function (evt) {
  22338. var type = BABYLON.KeyboardEventTypes.KEYUP;
  22339. if (_this.onPreKeyboardObservable.hasObservers()) {
  22340. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  22341. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  22342. if (pi.skipOnPointerObservable) {
  22343. return;
  22344. }
  22345. }
  22346. if (_this.onKeyboardObservable.hasObservers()) {
  22347. var pi = new BABYLON.KeyboardInfo(type, evt);
  22348. _this.onKeyboardObservable.notifyObservers(pi, type);
  22349. }
  22350. if (_this.actionManager) {
  22351. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  22352. }
  22353. };
  22354. var engine = this.getEngine();
  22355. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  22356. if (!canvas) {
  22357. return;
  22358. }
  22359. canvas.addEventListener("keydown", _this._onKeyDown, false);
  22360. canvas.addEventListener("keyup", _this._onKeyUp, false);
  22361. });
  22362. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  22363. if (!canvas) {
  22364. return;
  22365. }
  22366. canvas.removeEventListener("keydown", _this._onKeyDown);
  22367. canvas.removeEventListener("keyup", _this._onKeyUp);
  22368. });
  22369. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22370. var canvas = this._engine.getRenderingCanvas();
  22371. if (!canvas) {
  22372. return;
  22373. }
  22374. if (attachMove) {
  22375. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  22376. // Wheel
  22377. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  22378. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  22379. }
  22380. if (attachDown) {
  22381. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  22382. }
  22383. if (attachUp) {
  22384. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  22385. }
  22386. canvas.tabIndex = 1;
  22387. };
  22388. Scene.prototype.detachControl = function () {
  22389. var engine = this.getEngine();
  22390. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  22391. var canvas = engine.getRenderingCanvas();
  22392. if (!canvas) {
  22393. return;
  22394. }
  22395. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  22396. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  22397. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  22398. if (this._onCanvasBlurObserver) {
  22399. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  22400. }
  22401. if (this._onCanvasFocusObserver) {
  22402. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  22403. }
  22404. // Wheel
  22405. canvas.removeEventListener('mousewheel', this._onPointerMove);
  22406. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  22407. // Keyboard
  22408. canvas.removeEventListener("keydown", this._onKeyDown);
  22409. canvas.removeEventListener("keyup", this._onKeyUp);
  22410. // Observables
  22411. this.onKeyboardObservable.clear();
  22412. this.onPreKeyboardObservable.clear();
  22413. this.onPointerObservable.clear();
  22414. this.onPrePointerObservable.clear();
  22415. };
  22416. /**
  22417. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  22418. * Delay loaded resources are not taking in account
  22419. * @return true if all required resources are ready
  22420. */
  22421. Scene.prototype.isReady = function () {
  22422. if (this._isDisposed) {
  22423. return false;
  22424. }
  22425. if (this._pendingData.length > 0) {
  22426. return false;
  22427. }
  22428. var index;
  22429. var engine = this.getEngine();
  22430. // Geometries
  22431. for (index = 0; index < this._geometries.length; index++) {
  22432. var geometry = this._geometries[index];
  22433. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22434. return false;
  22435. }
  22436. }
  22437. // Meshes
  22438. for (index = 0; index < this.meshes.length; index++) {
  22439. var mesh = this.meshes[index];
  22440. if (!mesh.isEnabled()) {
  22441. continue;
  22442. }
  22443. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  22444. continue;
  22445. }
  22446. if (!mesh.isReady(true)) {
  22447. return false;
  22448. }
  22449. // Effect layers
  22450. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  22451. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  22452. var layer = _a[_i];
  22453. if (!layer.hasMesh(mesh)) {
  22454. continue;
  22455. }
  22456. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  22457. var subMesh = _c[_b];
  22458. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  22459. return false;
  22460. }
  22461. }
  22462. }
  22463. }
  22464. return true;
  22465. };
  22466. Scene.prototype.resetCachedMaterial = function () {
  22467. this._cachedMaterial = null;
  22468. this._cachedEffect = null;
  22469. this._cachedVisibility = null;
  22470. };
  22471. Scene.prototype.registerBeforeRender = function (func) {
  22472. this.onBeforeRenderObservable.add(func);
  22473. };
  22474. Scene.prototype.unregisterBeforeRender = function (func) {
  22475. this.onBeforeRenderObservable.removeCallback(func);
  22476. };
  22477. Scene.prototype.registerAfterRender = function (func) {
  22478. this.onAfterRenderObservable.add(func);
  22479. };
  22480. Scene.prototype.unregisterAfterRender = function (func) {
  22481. this.onAfterRenderObservable.removeCallback(func);
  22482. };
  22483. Scene.prototype._executeOnceBeforeRender = function (func) {
  22484. var _this = this;
  22485. var execFunc = function () {
  22486. func();
  22487. setTimeout(function () {
  22488. _this.unregisterBeforeRender(execFunc);
  22489. });
  22490. };
  22491. this.registerBeforeRender(execFunc);
  22492. };
  22493. /**
  22494. * The provided function will run before render once and will be disposed afterwards.
  22495. * A timeout delay can be provided so that the function will be executed in N ms.
  22496. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  22497. * @param func The function to be executed.
  22498. * @param timeout optional delay in ms
  22499. */
  22500. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  22501. var _this = this;
  22502. if (timeout !== undefined) {
  22503. setTimeout(function () {
  22504. _this._executeOnceBeforeRender(func);
  22505. }, timeout);
  22506. }
  22507. else {
  22508. this._executeOnceBeforeRender(func);
  22509. }
  22510. };
  22511. Scene.prototype._addPendingData = function (data) {
  22512. this._pendingData.push(data);
  22513. };
  22514. Scene.prototype._removePendingData = function (data) {
  22515. var wasLoading = this.isLoading;
  22516. var index = this._pendingData.indexOf(data);
  22517. if (index !== -1) {
  22518. this._pendingData.splice(index, 1);
  22519. }
  22520. if (wasLoading && !this.isLoading) {
  22521. this.onDataLoadedObservable.notifyObservers(this);
  22522. }
  22523. };
  22524. Scene.prototype.getWaitingItemsCount = function () {
  22525. return this._pendingData.length;
  22526. };
  22527. Object.defineProperty(Scene.prototype, "isLoading", {
  22528. get: function () {
  22529. return this._pendingData.length > 0;
  22530. },
  22531. enumerable: true,
  22532. configurable: true
  22533. });
  22534. /**
  22535. * Registers a function to be executed when the scene is ready.
  22536. * @param {Function} func - the function to be executed.
  22537. */
  22538. Scene.prototype.executeWhenReady = function (func) {
  22539. var _this = this;
  22540. this.onReadyObservable.add(func);
  22541. if (this._executeWhenReadyTimeoutId !== -1) {
  22542. return;
  22543. }
  22544. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22545. _this._checkIsReady();
  22546. }, 150);
  22547. };
  22548. /**
  22549. * Returns a promise that resolves when the scene is ready.
  22550. * @returns A promise that resolves when the scene is ready.
  22551. */
  22552. Scene.prototype.whenReadyAsync = function () {
  22553. var _this = this;
  22554. return new Promise(function (resolve) {
  22555. _this.executeWhenReady(function () {
  22556. resolve();
  22557. });
  22558. });
  22559. };
  22560. Scene.prototype._checkIsReady = function () {
  22561. var _this = this;
  22562. if (this.isReady()) {
  22563. this.onReadyObservable.notifyObservers(this);
  22564. this.onReadyObservable.clear();
  22565. this._executeWhenReadyTimeoutId = -1;
  22566. return;
  22567. }
  22568. this._executeWhenReadyTimeoutId = setTimeout(function () {
  22569. _this._checkIsReady();
  22570. }, 150);
  22571. };
  22572. // Animations
  22573. /**
  22574. * Will start the animation sequence of a given target
  22575. * @param target - the target
  22576. * @param {number} from - from which frame should animation start
  22577. * @param {number} to - till which frame should animation run.
  22578. * @param {boolean} [loop] - should the animation loop
  22579. * @param {number} [speedRatio] - the speed in which to run the animation
  22580. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  22581. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  22582. * Returns {BABYLON.Animatable} the animatable object created for this animation
  22583. * See BABYLON.Animatable
  22584. */
  22585. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  22586. if (speedRatio === void 0) { speedRatio = 1.0; }
  22587. if (from > to && speedRatio > 0) {
  22588. speedRatio *= -1;
  22589. }
  22590. this.stopAnimation(target);
  22591. if (!animatable) {
  22592. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  22593. }
  22594. // Local animations
  22595. if (target.animations) {
  22596. animatable.appendAnimations(target, target.animations);
  22597. }
  22598. // Children animations
  22599. if (target.getAnimatables) {
  22600. var animatables = target.getAnimatables();
  22601. for (var index = 0; index < animatables.length; index++) {
  22602. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  22603. }
  22604. }
  22605. animatable.reset();
  22606. return animatable;
  22607. };
  22608. /**
  22609. * Begin a new animation on a given node
  22610. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22611. * @param {BABYLON.Animation[]} defines the list of animations to start
  22612. * @param {number} from defines the initial value
  22613. * @param {number} to defines the final value
  22614. * @param {boolean} loop defines if you want animation to loop (off by default)
  22615. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22616. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22617. * @returns the list of created animatables
  22618. */
  22619. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22620. if (speedRatio === undefined) {
  22621. speedRatio = 1.0;
  22622. }
  22623. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  22624. return animatable;
  22625. };
  22626. /**
  22627. * Begin a new animation on a given node and its hierarchy
  22628. * @param {BABYLON.Node} node defines the root node where the animation will take place
  22629. * @param {boolean} 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.
  22630. * @param {BABYLON.Animation[]} defines the list of animations to start
  22631. * @param {number} from defines the initial value
  22632. * @param {number} to defines the final value
  22633. * @param {boolean} loop defines if you want animation to loop (off by default)
  22634. * @param {number} speedRatio defines the speed ratio to apply to all animations
  22635. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  22636. * @returns the list of animatables created for all nodes
  22637. */
  22638. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  22639. var children = target.getDescendants(directDescendantsOnly);
  22640. var result = [];
  22641. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  22642. var child = children_1[_i];
  22643. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  22644. }
  22645. return result;
  22646. };
  22647. Scene.prototype.getAnimatableByTarget = function (target) {
  22648. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22649. if (this._activeAnimatables[index].target === target) {
  22650. return this._activeAnimatables[index];
  22651. }
  22652. }
  22653. return null;
  22654. };
  22655. Object.defineProperty(Scene.prototype, "animatables", {
  22656. get: function () {
  22657. return this._activeAnimatables;
  22658. },
  22659. enumerable: true,
  22660. configurable: true
  22661. });
  22662. /**
  22663. * Will stop the animation of the given target
  22664. * @param target - the target
  22665. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  22666. * @see beginAnimation
  22667. */
  22668. Scene.prototype.stopAnimation = function (target, animationName) {
  22669. var animatable = this.getAnimatableByTarget(target);
  22670. if (animatable) {
  22671. animatable.stop(animationName);
  22672. }
  22673. };
  22674. /**
  22675. * Stops and removes all animations that have been applied to the scene
  22676. */
  22677. Scene.prototype.stopAllAnimations = function () {
  22678. if (this._activeAnimatables) {
  22679. for (var i = 0; i < this._activeAnimatables.length; i++) {
  22680. this._activeAnimatables[i].stop();
  22681. }
  22682. this._activeAnimatables = [];
  22683. }
  22684. };
  22685. Scene.prototype._animate = function () {
  22686. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  22687. return;
  22688. }
  22689. // Getting time
  22690. var now = BABYLON.Tools.Now;
  22691. if (!this._animationTimeLast) {
  22692. if (this._pendingData.length > 0) {
  22693. return;
  22694. }
  22695. this._animationTimeLast = now;
  22696. }
  22697. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  22698. this._animationTime += deltaTime;
  22699. this._animationTimeLast = now;
  22700. for (var index = 0; index < this._activeAnimatables.length; index++) {
  22701. this._activeAnimatables[index]._animate(this._animationTime);
  22702. }
  22703. };
  22704. // Matrix
  22705. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  22706. this._useAlternateCameraConfiguration = active;
  22707. };
  22708. Scene.prototype.getViewMatrix = function () {
  22709. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  22710. };
  22711. Scene.prototype.getProjectionMatrix = function () {
  22712. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  22713. };
  22714. Scene.prototype.getTransformMatrix = function () {
  22715. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  22716. };
  22717. Scene.prototype.setTransformMatrix = function (view, projection) {
  22718. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  22719. return;
  22720. }
  22721. this._viewUpdateFlag = view.updateFlag;
  22722. this._projectionUpdateFlag = projection.updateFlag;
  22723. this._viewMatrix = view;
  22724. this._projectionMatrix = projection;
  22725. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22726. // Update frustum
  22727. if (!this._frustumPlanes) {
  22728. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22729. }
  22730. else {
  22731. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22732. }
  22733. if (this.activeCamera && this.activeCamera._alternateCamera) {
  22734. var otherCamera = this.activeCamera._alternateCamera;
  22735. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  22736. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  22737. }
  22738. if (this._sceneUbo.useUbo) {
  22739. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  22740. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  22741. this._sceneUbo.update();
  22742. }
  22743. };
  22744. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  22745. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  22746. return;
  22747. }
  22748. this._alternateViewUpdateFlag = view.updateFlag;
  22749. this._alternateProjectionUpdateFlag = projection.updateFlag;
  22750. this._alternateViewMatrix = view;
  22751. this._alternateProjectionMatrix = projection;
  22752. if (!this._alternateTransformMatrix) {
  22753. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  22754. }
  22755. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  22756. if (!this._alternateSceneUbo) {
  22757. this._createAlternateUbo();
  22758. }
  22759. if (this._alternateSceneUbo.useUbo) {
  22760. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  22761. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  22762. this._alternateSceneUbo.update();
  22763. }
  22764. };
  22765. Scene.prototype.getSceneUniformBuffer = function () {
  22766. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  22767. };
  22768. // Methods
  22769. Scene.prototype.getUniqueId = function () {
  22770. var result = Scene._uniqueIdCounter;
  22771. Scene._uniqueIdCounter++;
  22772. return result;
  22773. };
  22774. Scene.prototype.addMesh = function (newMesh) {
  22775. this.meshes.push(newMesh);
  22776. //notify the collision coordinator
  22777. if (this.collisionCoordinator) {
  22778. this.collisionCoordinator.onMeshAdded(newMesh);
  22779. }
  22780. newMesh._resyncLightSources();
  22781. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  22782. };
  22783. Scene.prototype.removeMesh = function (toRemove) {
  22784. var index = this.meshes.indexOf(toRemove);
  22785. if (index !== -1) {
  22786. // Remove from the scene if mesh found
  22787. this.meshes.splice(index, 1);
  22788. }
  22789. this.onMeshRemovedObservable.notifyObservers(toRemove);
  22790. return index;
  22791. };
  22792. Scene.prototype.addTransformNode = function (newTransformNode) {
  22793. this.transformNodes.push(newTransformNode);
  22794. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  22795. };
  22796. Scene.prototype.removeTransformNode = function (toRemove) {
  22797. var index = this.transformNodes.indexOf(toRemove);
  22798. if (index !== -1) {
  22799. // Remove from the scene if found
  22800. this.transformNodes.splice(index, 1);
  22801. }
  22802. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  22803. return index;
  22804. };
  22805. Scene.prototype.removeSkeleton = function (toRemove) {
  22806. var index = this.skeletons.indexOf(toRemove);
  22807. if (index !== -1) {
  22808. // Remove from the scene if found
  22809. this.skeletons.splice(index, 1);
  22810. }
  22811. return index;
  22812. };
  22813. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  22814. var index = this.morphTargetManagers.indexOf(toRemove);
  22815. if (index !== -1) {
  22816. // Remove from the scene if found
  22817. this.morphTargetManagers.splice(index, 1);
  22818. }
  22819. return index;
  22820. };
  22821. Scene.prototype.removeLight = function (toRemove) {
  22822. var index = this.lights.indexOf(toRemove);
  22823. if (index !== -1) {
  22824. // Remove from meshes
  22825. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22826. var mesh = _a[_i];
  22827. mesh._removeLightSource(toRemove);
  22828. }
  22829. // Remove from the scene if mesh found
  22830. this.lights.splice(index, 1);
  22831. this.sortLightsByPriority();
  22832. }
  22833. this.onLightRemovedObservable.notifyObservers(toRemove);
  22834. return index;
  22835. };
  22836. Scene.prototype.removeCamera = function (toRemove) {
  22837. var index = this.cameras.indexOf(toRemove);
  22838. if (index !== -1) {
  22839. // Remove from the scene if mesh found
  22840. this.cameras.splice(index, 1);
  22841. }
  22842. // Remove from activeCameras
  22843. var index2 = this.activeCameras.indexOf(toRemove);
  22844. if (index2 !== -1) {
  22845. // Remove from the scene if mesh found
  22846. this.activeCameras.splice(index2, 1);
  22847. }
  22848. // Reset the activeCamera
  22849. if (this.activeCamera === toRemove) {
  22850. if (this.cameras.length > 0) {
  22851. this.activeCamera = this.cameras[0];
  22852. }
  22853. else {
  22854. this.activeCamera = null;
  22855. }
  22856. }
  22857. this.onCameraRemovedObservable.notifyObservers(toRemove);
  22858. return index;
  22859. };
  22860. Scene.prototype.removeParticleSystem = function (toRemove) {
  22861. var index = this.particleSystems.indexOf(toRemove);
  22862. if (index !== -1) {
  22863. this.particleSystems.splice(index, 1);
  22864. }
  22865. return index;
  22866. };
  22867. ;
  22868. Scene.prototype.removeAnimation = function (toRemove) {
  22869. var index = this.animations.indexOf(toRemove);
  22870. if (index !== -1) {
  22871. this.animations.splice(index, 1);
  22872. }
  22873. return index;
  22874. };
  22875. ;
  22876. Scene.prototype.removeMultiMaterial = function (toRemove) {
  22877. var index = this.multiMaterials.indexOf(toRemove);
  22878. if (index !== -1) {
  22879. this.multiMaterials.splice(index, 1);
  22880. }
  22881. return index;
  22882. };
  22883. ;
  22884. Scene.prototype.removeMaterial = function (toRemove) {
  22885. var index = this.materials.indexOf(toRemove);
  22886. if (index !== -1) {
  22887. this.materials.splice(index, 1);
  22888. }
  22889. return index;
  22890. };
  22891. ;
  22892. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  22893. var index = this.lensFlareSystems.indexOf(toRemove);
  22894. if (index !== -1) {
  22895. this.lensFlareSystems.splice(index, 1);
  22896. }
  22897. return index;
  22898. };
  22899. ;
  22900. Scene.prototype.removeActionManager = function (toRemove) {
  22901. var index = this._actionManagers.indexOf(toRemove);
  22902. if (index !== -1) {
  22903. this._actionManagers.splice(index, 1);
  22904. }
  22905. return index;
  22906. };
  22907. ;
  22908. Scene.prototype.addLight = function (newLight) {
  22909. this.lights.push(newLight);
  22910. this.sortLightsByPriority();
  22911. // Add light to all meshes (To support if the light is removed and then readded)
  22912. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  22913. var mesh = _a[_i];
  22914. if (mesh._lightSources.indexOf(newLight) === -1) {
  22915. mesh._lightSources.push(newLight);
  22916. mesh._resyncLightSources();
  22917. }
  22918. }
  22919. this.onNewLightAddedObservable.notifyObservers(newLight);
  22920. };
  22921. Scene.prototype.sortLightsByPriority = function () {
  22922. if (this.requireLightSorting) {
  22923. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  22924. }
  22925. };
  22926. Scene.prototype.addCamera = function (newCamera) {
  22927. this.cameras.push(newCamera);
  22928. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  22929. };
  22930. Scene.prototype.addSkeleton = function (newSkeleton) {
  22931. this.skeletons.push(newSkeleton);
  22932. };
  22933. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  22934. this.particleSystems.push(newParticleSystem);
  22935. };
  22936. Scene.prototype.addAnimation = function (newAnimation) {
  22937. this.animations.push(newAnimation);
  22938. };
  22939. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  22940. this.multiMaterials.push(newMultiMaterial);
  22941. };
  22942. Scene.prototype.addMaterial = function (newMaterial) {
  22943. this.materials.push(newMaterial);
  22944. };
  22945. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  22946. this.morphTargetManagers.push(newMorphTargetManager);
  22947. };
  22948. Scene.prototype.addGeometry = function (newGeometrie) {
  22949. this._geometries.push(newGeometrie);
  22950. };
  22951. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  22952. this.lensFlareSystems.push(newLensFlareSystem);
  22953. };
  22954. Scene.prototype.addActionManager = function (newActionManager) {
  22955. this._actionManagers.push(newActionManager);
  22956. };
  22957. /**
  22958. * Switch active camera
  22959. * @param {Camera} newCamera - new active camera
  22960. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  22961. */
  22962. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  22963. if (attachControl === void 0) { attachControl = true; }
  22964. var canvas = this._engine.getRenderingCanvas();
  22965. if (!canvas) {
  22966. return;
  22967. }
  22968. if (this.activeCamera) {
  22969. this.activeCamera.detachControl(canvas);
  22970. }
  22971. this.activeCamera = newCamera;
  22972. if (attachControl) {
  22973. newCamera.attachControl(canvas);
  22974. }
  22975. };
  22976. /**
  22977. * sets the active camera of the scene using its ID
  22978. * @param {string} id - the camera's ID
  22979. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22980. * @see activeCamera
  22981. */
  22982. Scene.prototype.setActiveCameraByID = function (id) {
  22983. var camera = this.getCameraByID(id);
  22984. if (camera) {
  22985. this.activeCamera = camera;
  22986. return camera;
  22987. }
  22988. return null;
  22989. };
  22990. /**
  22991. * sets the active camera of the scene using its name
  22992. * @param {string} name - the camera's name
  22993. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  22994. * @see activeCamera
  22995. */
  22996. Scene.prototype.setActiveCameraByName = function (name) {
  22997. var camera = this.getCameraByName(name);
  22998. if (camera) {
  22999. this.activeCamera = camera;
  23000. return camera;
  23001. }
  23002. return null;
  23003. };
  23004. /**
  23005. * get an animation group using its name
  23006. * @param {string} the material's name
  23007. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23008. */
  23009. Scene.prototype.getAnimationGroupByName = function (name) {
  23010. for (var index = 0; index < this.animationGroups.length; index++) {
  23011. if (this.animationGroups[index].name === name) {
  23012. return this.animationGroups[index];
  23013. }
  23014. }
  23015. return null;
  23016. };
  23017. /**
  23018. * get a material using its id
  23019. * @param {string} the material's ID
  23020. * @return {BABYLON.Material|null} the material or null if none found.
  23021. */
  23022. Scene.prototype.getMaterialByID = function (id) {
  23023. for (var index = 0; index < this.materials.length; index++) {
  23024. if (this.materials[index].id === id) {
  23025. return this.materials[index];
  23026. }
  23027. }
  23028. return null;
  23029. };
  23030. /**
  23031. * get a material using its name
  23032. * @param {string} the material's name
  23033. * @return {BABYLON.Material|null} the material or null if none found.
  23034. */
  23035. Scene.prototype.getMaterialByName = function (name) {
  23036. for (var index = 0; index < this.materials.length; index++) {
  23037. if (this.materials[index].name === name) {
  23038. return this.materials[index];
  23039. }
  23040. }
  23041. return null;
  23042. };
  23043. Scene.prototype.getLensFlareSystemByName = function (name) {
  23044. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23045. if (this.lensFlareSystems[index].name === name) {
  23046. return this.lensFlareSystems[index];
  23047. }
  23048. }
  23049. return null;
  23050. };
  23051. Scene.prototype.getLensFlareSystemByID = function (id) {
  23052. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23053. if (this.lensFlareSystems[index].id === id) {
  23054. return this.lensFlareSystems[index];
  23055. }
  23056. }
  23057. return null;
  23058. };
  23059. Scene.prototype.getCameraByID = function (id) {
  23060. for (var index = 0; index < this.cameras.length; index++) {
  23061. if (this.cameras[index].id === id) {
  23062. return this.cameras[index];
  23063. }
  23064. }
  23065. return null;
  23066. };
  23067. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23068. for (var index = 0; index < this.cameras.length; index++) {
  23069. if (this.cameras[index].uniqueId === uniqueId) {
  23070. return this.cameras[index];
  23071. }
  23072. }
  23073. return null;
  23074. };
  23075. /**
  23076. * get a camera using its name
  23077. * @param {string} the camera's name
  23078. * @return {BABYLON.Camera|null} the camera or null if none found.
  23079. */
  23080. Scene.prototype.getCameraByName = function (name) {
  23081. for (var index = 0; index < this.cameras.length; index++) {
  23082. if (this.cameras[index].name === name) {
  23083. return this.cameras[index];
  23084. }
  23085. }
  23086. return null;
  23087. };
  23088. /**
  23089. * get a bone using its id
  23090. * @param {string} the bone's id
  23091. * @return {BABYLON.Bone|null} the bone or null if not found
  23092. */
  23093. Scene.prototype.getBoneByID = function (id) {
  23094. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23095. var skeleton = this.skeletons[skeletonIndex];
  23096. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23097. if (skeleton.bones[boneIndex].id === id) {
  23098. return skeleton.bones[boneIndex];
  23099. }
  23100. }
  23101. }
  23102. return null;
  23103. };
  23104. /**
  23105. * get a bone using its id
  23106. * @param {string} the bone's name
  23107. * @return {BABYLON.Bone|null} the bone or null if not found
  23108. */
  23109. Scene.prototype.getBoneByName = function (name) {
  23110. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23111. var skeleton = this.skeletons[skeletonIndex];
  23112. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23113. if (skeleton.bones[boneIndex].name === name) {
  23114. return skeleton.bones[boneIndex];
  23115. }
  23116. }
  23117. }
  23118. return null;
  23119. };
  23120. /**
  23121. * get a light node using its name
  23122. * @param {string} the light's name
  23123. * @return {BABYLON.Light|null} the light or null if none found.
  23124. */
  23125. Scene.prototype.getLightByName = function (name) {
  23126. for (var index = 0; index < this.lights.length; index++) {
  23127. if (this.lights[index].name === name) {
  23128. return this.lights[index];
  23129. }
  23130. }
  23131. return null;
  23132. };
  23133. /**
  23134. * get a light node using its ID
  23135. * @param {string} the light's id
  23136. * @return {BABYLON.Light|null} the light or null if none found.
  23137. */
  23138. Scene.prototype.getLightByID = function (id) {
  23139. for (var index = 0; index < this.lights.length; index++) {
  23140. if (this.lights[index].id === id) {
  23141. return this.lights[index];
  23142. }
  23143. }
  23144. return null;
  23145. };
  23146. /**
  23147. * get a light node using its scene-generated unique ID
  23148. * @param {number} the light's unique id
  23149. * @return {BABYLON.Light|null} the light or null if none found.
  23150. */
  23151. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23152. for (var index = 0; index < this.lights.length; index++) {
  23153. if (this.lights[index].uniqueId === uniqueId) {
  23154. return this.lights[index];
  23155. }
  23156. }
  23157. return null;
  23158. };
  23159. /**
  23160. * get a particle system by id
  23161. * @param id {number} the particle system id
  23162. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23163. */
  23164. Scene.prototype.getParticleSystemByID = function (id) {
  23165. for (var index = 0; index < this.particleSystems.length; index++) {
  23166. if (this.particleSystems[index].id === id) {
  23167. return this.particleSystems[index];
  23168. }
  23169. }
  23170. return null;
  23171. };
  23172. /**
  23173. * get a geometry using its ID
  23174. * @param {string} the geometry's id
  23175. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23176. */
  23177. Scene.prototype.getGeometryByID = function (id) {
  23178. for (var index = 0; index < this._geometries.length; index++) {
  23179. if (this._geometries[index].id === id) {
  23180. return this._geometries[index];
  23181. }
  23182. }
  23183. return null;
  23184. };
  23185. /**
  23186. * add a new geometry to this scene.
  23187. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23188. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23189. * @return {boolean} was the geometry added or not
  23190. */
  23191. Scene.prototype.pushGeometry = function (geometry, force) {
  23192. if (!force && this.getGeometryByID(geometry.id)) {
  23193. return false;
  23194. }
  23195. this._geometries.push(geometry);
  23196. //notify the collision coordinator
  23197. if (this.collisionCoordinator) {
  23198. this.collisionCoordinator.onGeometryAdded(geometry);
  23199. }
  23200. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  23201. return true;
  23202. };
  23203. /**
  23204. * Removes an existing geometry
  23205. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  23206. * @return {boolean} was the geometry removed or not
  23207. */
  23208. Scene.prototype.removeGeometry = function (geometry) {
  23209. var index = this._geometries.indexOf(geometry);
  23210. if (index > -1) {
  23211. this._geometries.splice(index, 1);
  23212. //notify the collision coordinator
  23213. if (this.collisionCoordinator) {
  23214. this.collisionCoordinator.onGeometryDeleted(geometry);
  23215. }
  23216. this.onGeometryRemovedObservable.notifyObservers(geometry);
  23217. return true;
  23218. }
  23219. return false;
  23220. };
  23221. Scene.prototype.getGeometries = function () {
  23222. return this._geometries;
  23223. };
  23224. /**
  23225. * Get the first added mesh found of a given ID
  23226. * @param {string} id - the id to search for
  23227. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23228. */
  23229. Scene.prototype.getMeshByID = function (id) {
  23230. for (var index = 0; index < this.meshes.length; index++) {
  23231. if (this.meshes[index].id === id) {
  23232. return this.meshes[index];
  23233. }
  23234. }
  23235. return null;
  23236. };
  23237. Scene.prototype.getMeshesByID = function (id) {
  23238. return this.meshes.filter(function (m) {
  23239. return m.id === id;
  23240. });
  23241. };
  23242. /**
  23243. * Get the first added transform node found of a given ID
  23244. * @param {string} id - the id to search for
  23245. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  23246. */
  23247. Scene.prototype.getTransformNodeByID = function (id) {
  23248. for (var index = 0; index < this.transformNodes.length; index++) {
  23249. if (this.transformNodes[index].id === id) {
  23250. return this.transformNodes[index];
  23251. }
  23252. }
  23253. return null;
  23254. };
  23255. Scene.prototype.getTransformNodesByID = function (id) {
  23256. return this.transformNodes.filter(function (m) {
  23257. return m.id === id;
  23258. });
  23259. };
  23260. /**
  23261. * Get a mesh with its auto-generated unique id
  23262. * @param {number} uniqueId - the unique id to search for
  23263. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23264. */
  23265. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  23266. for (var index = 0; index < this.meshes.length; index++) {
  23267. if (this.meshes[index].uniqueId === uniqueId) {
  23268. return this.meshes[index];
  23269. }
  23270. }
  23271. return null;
  23272. };
  23273. /**
  23274. * Get a the last added mesh found of a given ID
  23275. * @param {string} id - the id to search for
  23276. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  23277. */
  23278. Scene.prototype.getLastMeshByID = function (id) {
  23279. for (var index = this.meshes.length - 1; index >= 0; index--) {
  23280. if (this.meshes[index].id === id) {
  23281. return this.meshes[index];
  23282. }
  23283. }
  23284. return null;
  23285. };
  23286. /**
  23287. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  23288. * @param {string} id - the id to search for
  23289. * @return {BABYLON.Node|null} the node found or null if not found at all.
  23290. */
  23291. Scene.prototype.getLastEntryByID = function (id) {
  23292. var index;
  23293. for (index = this.meshes.length - 1; index >= 0; index--) {
  23294. if (this.meshes[index].id === id) {
  23295. return this.meshes[index];
  23296. }
  23297. }
  23298. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  23299. if (this.transformNodes[index].id === id) {
  23300. return this.transformNodes[index];
  23301. }
  23302. }
  23303. for (index = this.cameras.length - 1; index >= 0; index--) {
  23304. if (this.cameras[index].id === id) {
  23305. return this.cameras[index];
  23306. }
  23307. }
  23308. for (index = this.lights.length - 1; index >= 0; index--) {
  23309. if (this.lights[index].id === id) {
  23310. return this.lights[index];
  23311. }
  23312. }
  23313. return null;
  23314. };
  23315. Scene.prototype.getNodeByID = function (id) {
  23316. var mesh = this.getMeshByID(id);
  23317. if (mesh) {
  23318. return mesh;
  23319. }
  23320. var light = this.getLightByID(id);
  23321. if (light) {
  23322. return light;
  23323. }
  23324. var camera = this.getCameraByID(id);
  23325. if (camera) {
  23326. return camera;
  23327. }
  23328. var bone = this.getBoneByID(id);
  23329. return bone;
  23330. };
  23331. Scene.prototype.getNodeByName = function (name) {
  23332. var mesh = this.getMeshByName(name);
  23333. if (mesh) {
  23334. return mesh;
  23335. }
  23336. var light = this.getLightByName(name);
  23337. if (light) {
  23338. return light;
  23339. }
  23340. var camera = this.getCameraByName(name);
  23341. if (camera) {
  23342. return camera;
  23343. }
  23344. var bone = this.getBoneByName(name);
  23345. return bone;
  23346. };
  23347. Scene.prototype.getMeshByName = function (name) {
  23348. for (var index = 0; index < this.meshes.length; index++) {
  23349. if (this.meshes[index].name === name) {
  23350. return this.meshes[index];
  23351. }
  23352. }
  23353. return null;
  23354. };
  23355. Scene.prototype.getTransformNodeByName = function (name) {
  23356. for (var index = 0; index < this.transformNodes.length; index++) {
  23357. if (this.transformNodes[index].name === name) {
  23358. return this.transformNodes[index];
  23359. }
  23360. }
  23361. return null;
  23362. };
  23363. Scene.prototype.getSoundByName = function (name) {
  23364. var index;
  23365. if (BABYLON.AudioEngine) {
  23366. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  23367. if (this.mainSoundTrack.soundCollection[index].name === name) {
  23368. return this.mainSoundTrack.soundCollection[index];
  23369. }
  23370. }
  23371. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  23372. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  23373. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  23374. return this.soundTracks[sdIndex].soundCollection[index];
  23375. }
  23376. }
  23377. }
  23378. }
  23379. return null;
  23380. };
  23381. Scene.prototype.getLastSkeletonByID = function (id) {
  23382. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  23383. if (this.skeletons[index].id === id) {
  23384. return this.skeletons[index];
  23385. }
  23386. }
  23387. return null;
  23388. };
  23389. Scene.prototype.getSkeletonById = function (id) {
  23390. for (var index = 0; index < this.skeletons.length; index++) {
  23391. if (this.skeletons[index].id === id) {
  23392. return this.skeletons[index];
  23393. }
  23394. }
  23395. return null;
  23396. };
  23397. Scene.prototype.getSkeletonByName = function (name) {
  23398. for (var index = 0; index < this.skeletons.length; index++) {
  23399. if (this.skeletons[index].name === name) {
  23400. return this.skeletons[index];
  23401. }
  23402. }
  23403. return null;
  23404. };
  23405. Scene.prototype.getMorphTargetManagerById = function (id) {
  23406. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  23407. if (this.morphTargetManagers[index].uniqueId === id) {
  23408. return this.morphTargetManagers[index];
  23409. }
  23410. }
  23411. return null;
  23412. };
  23413. Scene.prototype.isActiveMesh = function (mesh) {
  23414. return (this._activeMeshes.indexOf(mesh) !== -1);
  23415. };
  23416. /**
  23417. * Return a the first highlight layer of the scene with a given name.
  23418. * @param name The name of the highlight layer to look for.
  23419. * @return The highlight layer if found otherwise null.
  23420. */
  23421. Scene.prototype.getHighlightLayerByName = function (name) {
  23422. for (var index = 0; index < this.effectLayers.length; index++) {
  23423. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  23424. return this.effectLayers[index];
  23425. }
  23426. }
  23427. return null;
  23428. };
  23429. /**
  23430. * Return a the first highlight layer of the scene with a given name.
  23431. * @param name The name of the highlight layer to look for.
  23432. * @return The highlight layer if found otherwise null.
  23433. */
  23434. Scene.prototype.getGlowLayerByName = function (name) {
  23435. for (var index = 0; index < this.effectLayers.length; index++) {
  23436. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  23437. return this.effectLayers[index];
  23438. }
  23439. }
  23440. return null;
  23441. };
  23442. Object.defineProperty(Scene.prototype, "uid", {
  23443. /**
  23444. * Return a unique id as a string which can serve as an identifier for the scene
  23445. */
  23446. get: function () {
  23447. if (!this._uid) {
  23448. this._uid = BABYLON.Tools.RandomId();
  23449. }
  23450. return this._uid;
  23451. },
  23452. enumerable: true,
  23453. configurable: true
  23454. });
  23455. /**
  23456. * Add an externaly attached data from its key.
  23457. * This method call will fail and return false, if such key already exists.
  23458. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  23459. * @param key the unique key that identifies the data
  23460. * @param data the data object to associate to the key for this Engine instance
  23461. * @return true if no such key were already present and the data was added successfully, false otherwise
  23462. */
  23463. Scene.prototype.addExternalData = function (key, data) {
  23464. if (!this._externalData) {
  23465. this._externalData = new BABYLON.StringDictionary();
  23466. }
  23467. return this._externalData.add(key, data);
  23468. };
  23469. /**
  23470. * Get an externaly attached data from its key
  23471. * @param key the unique key that identifies the data
  23472. * @return the associated data, if present (can be null), or undefined if not present
  23473. */
  23474. Scene.prototype.getExternalData = function (key) {
  23475. if (!this._externalData) {
  23476. return null;
  23477. }
  23478. return this._externalData.get(key);
  23479. };
  23480. /**
  23481. * Get an externaly attached data from its key, create it using a factory if it's not already present
  23482. * @param key the unique key that identifies the data
  23483. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  23484. * @return the associated data, can be null if the factory returned null.
  23485. */
  23486. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  23487. if (!this._externalData) {
  23488. this._externalData = new BABYLON.StringDictionary();
  23489. }
  23490. return this._externalData.getOrAddWithFactory(key, factory);
  23491. };
  23492. /**
  23493. * Remove an externaly attached data from the Engine instance
  23494. * @param key the unique key that identifies the data
  23495. * @return true if the data was successfully removed, false if it doesn't exist
  23496. */
  23497. Scene.prototype.removeExternalData = function (key) {
  23498. return this._externalData.remove(key);
  23499. };
  23500. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  23501. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  23502. if (mesh.showSubMeshesBoundingBox) {
  23503. var boundingInfo = subMesh.getBoundingInfo();
  23504. if (boundingInfo !== null && boundingInfo !== undefined) {
  23505. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23506. }
  23507. }
  23508. var material = subMesh.getMaterial();
  23509. if (material !== null && material !== undefined) {
  23510. // Render targets
  23511. if (material.getRenderTargetTextures !== undefined) {
  23512. if (this._processedMaterials.indexOf(material) === -1) {
  23513. this._processedMaterials.push(material);
  23514. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  23515. }
  23516. }
  23517. // Dispatch
  23518. this._activeIndices.addCount(subMesh.indexCount, false);
  23519. this._renderingManager.dispatch(subMesh, mesh, material);
  23520. }
  23521. }
  23522. };
  23523. Scene.prototype._isInIntermediateRendering = function () {
  23524. return this._intermediateRendering;
  23525. };
  23526. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  23527. this._activeMeshCandidateProvider = provider;
  23528. };
  23529. Scene.prototype.getActiveMeshCandidateProvider = function () {
  23530. return this._activeMeshCandidateProvider;
  23531. };
  23532. /**
  23533. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  23534. */
  23535. Scene.prototype.freezeActiveMeshes = function () {
  23536. this._evaluateActiveMeshes();
  23537. this._activeMeshesFrozen = true;
  23538. return this;
  23539. };
  23540. /**
  23541. * Use this function to restart evaluating active meshes on every frame
  23542. */
  23543. Scene.prototype.unfreezeActiveMeshes = function () {
  23544. this._activeMeshesFrozen = false;
  23545. return this;
  23546. };
  23547. Scene.prototype._evaluateActiveMeshes = function () {
  23548. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  23549. return;
  23550. }
  23551. if (!this.activeCamera) {
  23552. return;
  23553. }
  23554. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  23555. this.activeCamera._activeMeshes.reset();
  23556. this._activeMeshes.reset();
  23557. this._renderingManager.reset();
  23558. this._processedMaterials.reset();
  23559. this._activeParticleSystems.reset();
  23560. this._activeSkeletons.reset();
  23561. this._softwareSkinnedMeshes.reset();
  23562. if (this._boundingBoxRenderer) {
  23563. this._boundingBoxRenderer.reset();
  23564. }
  23565. // Meshes
  23566. var meshes;
  23567. var len;
  23568. var checkIsEnabled = true;
  23569. // Determine mesh candidates
  23570. if (this._activeMeshCandidateProvider !== undefined) {
  23571. // Use _activeMeshCandidateProvider
  23572. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  23573. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  23574. if (meshes !== undefined) {
  23575. len = meshes.length;
  23576. }
  23577. else {
  23578. len = 0;
  23579. }
  23580. }
  23581. else if (this._selectionOctree !== undefined) {
  23582. // Octree
  23583. var selection = this._selectionOctree.select(this._frustumPlanes);
  23584. meshes = selection.data;
  23585. len = selection.length;
  23586. }
  23587. else {
  23588. // Full scene traversal
  23589. len = this.meshes.length;
  23590. meshes = this.meshes;
  23591. }
  23592. // Check each mesh
  23593. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  23594. mesh = meshes[meshIndex];
  23595. if (mesh.isBlocked) {
  23596. continue;
  23597. }
  23598. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  23599. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  23600. continue;
  23601. }
  23602. mesh.computeWorldMatrix();
  23603. // Intersections
  23604. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  23605. this._meshesForIntersections.pushNoDuplicate(mesh);
  23606. }
  23607. // Switch to current LOD
  23608. meshLOD = mesh.getLOD(this.activeCamera);
  23609. if (meshLOD === undefined || meshLOD === null) {
  23610. continue;
  23611. }
  23612. mesh._preActivate();
  23613. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  23614. this._activeMeshes.push(mesh);
  23615. this.activeCamera._activeMeshes.push(mesh);
  23616. mesh._activate(this._renderId);
  23617. if (meshLOD !== mesh) {
  23618. meshLOD._activate(this._renderId);
  23619. }
  23620. this._activeMesh(mesh, meshLOD);
  23621. }
  23622. }
  23623. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  23624. // Particle systems
  23625. if (this.particlesEnabled) {
  23626. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  23627. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  23628. var particleSystem = this.particleSystems[particleIndex];
  23629. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  23630. continue;
  23631. }
  23632. var emitter = particleSystem.emitter;
  23633. if (!emitter.position || emitter.isEnabled()) {
  23634. this._activeParticleSystems.push(particleSystem);
  23635. particleSystem.animate();
  23636. this._renderingManager.dispatchParticles(particleSystem);
  23637. }
  23638. }
  23639. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  23640. }
  23641. };
  23642. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  23643. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  23644. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  23645. mesh.skeleton.prepare();
  23646. }
  23647. if (!mesh.computeBonesUsingShaders) {
  23648. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  23649. }
  23650. }
  23651. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  23652. var boundingInfo = sourceMesh.getBoundingInfo();
  23653. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  23654. }
  23655. if (mesh !== undefined && mesh !== null
  23656. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  23657. // Submeshes Octrees
  23658. var len;
  23659. var subMeshes;
  23660. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  23661. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  23662. len = intersections.length;
  23663. subMeshes = intersections.data;
  23664. }
  23665. else {
  23666. subMeshes = mesh.subMeshes;
  23667. len = subMeshes.length;
  23668. }
  23669. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  23670. subMesh = subMeshes[subIndex];
  23671. this._evaluateSubMesh(subMesh, mesh);
  23672. }
  23673. }
  23674. };
  23675. Scene.prototype.updateTransformMatrix = function (force) {
  23676. if (!this.activeCamera) {
  23677. return;
  23678. }
  23679. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  23680. };
  23681. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  23682. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  23683. };
  23684. Scene.prototype._renderForCamera = function (camera, rigParent) {
  23685. if (camera && camera._skipRendering) {
  23686. return;
  23687. }
  23688. var engine = this._engine;
  23689. this.activeCamera = camera;
  23690. if (!this.activeCamera)
  23691. throw new Error("Active camera not set");
  23692. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23693. // Viewport
  23694. engine.setViewport(this.activeCamera.viewport);
  23695. // Camera
  23696. this.resetCachedMaterial();
  23697. this._renderId++;
  23698. this.activeCamera.update();
  23699. this.updateTransformMatrix();
  23700. if (camera._alternateCamera) {
  23701. this.updateAlternateTransformMatrix(camera._alternateCamera);
  23702. this._alternateRendering = true;
  23703. }
  23704. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  23705. // Meshes
  23706. this._evaluateActiveMeshes();
  23707. // Software skinning
  23708. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  23709. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  23710. mesh.applySkeleton(mesh.skeleton);
  23711. }
  23712. // Render targets
  23713. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23714. var needsRestoreFrameBuffer = false;
  23715. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  23716. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  23717. }
  23718. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  23719. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  23720. }
  23721. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  23722. this._intermediateRendering = true;
  23723. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23724. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  23725. var renderTarget = this._renderTargets.data[renderIndex];
  23726. if (renderTarget._shouldRender()) {
  23727. this._renderId++;
  23728. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  23729. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  23730. }
  23731. }
  23732. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  23733. this._intermediateRendering = false;
  23734. this._renderId++;
  23735. needsRestoreFrameBuffer = true; // Restore back buffer
  23736. }
  23737. // Render EffecttLayer Texture
  23738. var stencilState = this._engine.getStencilBuffer();
  23739. var renderEffects = false;
  23740. var needStencil = false;
  23741. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  23742. this._intermediateRendering = true;
  23743. for (var i = 0; i < this.effectLayers.length; i++) {
  23744. var effectLayer = this.effectLayers[i];
  23745. if (effectLayer.shouldRender() &&
  23746. (!effectLayer.camera ||
  23747. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  23748. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  23749. renderEffects = true;
  23750. needStencil = needStencil || effectLayer.needStencil();
  23751. var renderTarget = effectLayer._mainTexture;
  23752. if (renderTarget._shouldRender()) {
  23753. this._renderId++;
  23754. renderTarget.render(false, false);
  23755. needsRestoreFrameBuffer = true;
  23756. }
  23757. }
  23758. }
  23759. this._intermediateRendering = false;
  23760. this._renderId++;
  23761. }
  23762. if (needsRestoreFrameBuffer) {
  23763. engine.restoreDefaultFramebuffer(); // Restore back buffer
  23764. }
  23765. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23766. // Prepare Frame
  23767. this.postProcessManager._prepareFrame();
  23768. // Backgrounds
  23769. var layerIndex;
  23770. var layer;
  23771. if (this.layers.length) {
  23772. engine.setDepthBuffer(false);
  23773. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23774. layer = this.layers[layerIndex];
  23775. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23776. layer.render();
  23777. }
  23778. }
  23779. engine.setDepthBuffer(true);
  23780. }
  23781. // Activate effect Layer stencil
  23782. if (needStencil) {
  23783. this._engine.setStencilBuffer(true);
  23784. }
  23785. // Render
  23786. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  23787. this._renderingManager.render(null, null, true, true);
  23788. this.onAfterDrawPhaseObservable.notifyObservers(this);
  23789. // Restore effect Layer stencil
  23790. if (needStencil) {
  23791. this._engine.setStencilBuffer(stencilState);
  23792. }
  23793. // Bounding boxes
  23794. if (this._boundingBoxRenderer) {
  23795. this._boundingBoxRenderer.render();
  23796. }
  23797. // Lens flares
  23798. if (this.lensFlaresEnabled) {
  23799. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23800. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  23801. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  23802. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  23803. lensFlareSystem.render();
  23804. }
  23805. }
  23806. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  23807. }
  23808. // Foregrounds
  23809. if (this.layers.length) {
  23810. engine.setDepthBuffer(false);
  23811. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  23812. layer = this.layers[layerIndex];
  23813. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  23814. layer.render();
  23815. }
  23816. }
  23817. engine.setDepthBuffer(true);
  23818. }
  23819. // Effect Layer
  23820. if (renderEffects) {
  23821. engine.setDepthBuffer(false);
  23822. for (var i = 0; i < this.effectLayers.length; i++) {
  23823. if (this.effectLayers[i].shouldRender()) {
  23824. this.effectLayers[i].render();
  23825. }
  23826. }
  23827. engine.setDepthBuffer(true);
  23828. }
  23829. // Finalize frame
  23830. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  23831. // Reset some special arrays
  23832. this._renderTargets.reset();
  23833. this._alternateRendering = false;
  23834. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  23835. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  23836. };
  23837. Scene.prototype._processSubCameras = function (camera) {
  23838. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  23839. this._renderForCamera(camera);
  23840. return;
  23841. }
  23842. // Update camera
  23843. if (this.activeCamera) {
  23844. this.activeCamera.update();
  23845. }
  23846. // rig cameras
  23847. for (var index = 0; index < camera._rigCameras.length; index++) {
  23848. this._renderForCamera(camera._rigCameras[index], camera);
  23849. }
  23850. this.activeCamera = camera;
  23851. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  23852. };
  23853. Scene.prototype._checkIntersections = function () {
  23854. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  23855. var sourceMesh = this._meshesForIntersections.data[index];
  23856. if (!sourceMesh.actionManager) {
  23857. continue;
  23858. }
  23859. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  23860. var action = sourceMesh.actionManager.actions[actionIndex];
  23861. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23862. var parameters = action.getTriggerParameter();
  23863. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  23864. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  23865. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  23866. if (areIntersecting && currentIntersectionInProgress === -1) {
  23867. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  23868. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23869. sourceMesh._intersectionsInProgress.push(otherMesh);
  23870. }
  23871. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23872. sourceMesh._intersectionsInProgress.push(otherMesh);
  23873. }
  23874. }
  23875. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  23876. //They intersected, and now they don't.
  23877. //is this trigger an exit trigger? execute an event.
  23878. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23879. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  23880. }
  23881. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  23882. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  23883. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  23884. }
  23885. }
  23886. }
  23887. }
  23888. }
  23889. };
  23890. Scene.prototype.render = function () {
  23891. if (this.isDisposed) {
  23892. return;
  23893. }
  23894. this._activeParticles.fetchNewFrame();
  23895. this._totalVertices.fetchNewFrame();
  23896. this._activeIndices.fetchNewFrame();
  23897. this._activeBones.fetchNewFrame();
  23898. this._meshesForIntersections.reset();
  23899. this.resetCachedMaterial();
  23900. this.onBeforeAnimationsObservable.notifyObservers(this);
  23901. // Actions
  23902. if (this.actionManager) {
  23903. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  23904. }
  23905. //Simplification Queue
  23906. if (this.simplificationQueue && !this.simplificationQueue.running) {
  23907. this.simplificationQueue.executeNext();
  23908. }
  23909. if (this._engine.isDeterministicLockStep()) {
  23910. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  23911. var defaultFPS = (60.0 / 1000.0);
  23912. var defaultFrameTime = 1000 / 60; // frame time in MS
  23913. if (this._physicsEngine) {
  23914. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  23915. }
  23916. var stepsTaken = 0;
  23917. var maxSubSteps = this._engine.getLockstepMaxSteps();
  23918. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  23919. internalSteps = Math.min(internalSteps, maxSubSteps);
  23920. do {
  23921. this.onBeforeStepObservable.notifyObservers(this);
  23922. // Animations
  23923. this._animationRatio = defaultFrameTime * defaultFPS;
  23924. this._animate();
  23925. this.onAfterAnimationsObservable.notifyObservers(this);
  23926. // Physics
  23927. if (this._physicsEngine) {
  23928. this.onBeforePhysicsObservable.notifyObservers(this);
  23929. this._physicsEngine._step(defaultFrameTime / 1000);
  23930. this.onAfterPhysicsObservable.notifyObservers(this);
  23931. }
  23932. this.onAfterStepObservable.notifyObservers(this);
  23933. this._currentStepId++;
  23934. stepsTaken++;
  23935. deltaTime -= defaultFrameTime;
  23936. } while (deltaTime > 0 && stepsTaken < internalSteps);
  23937. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  23938. }
  23939. else {
  23940. // Animations
  23941. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  23942. this._animationRatio = deltaTime * (60.0 / 1000.0);
  23943. this._animate();
  23944. this.onAfterAnimationsObservable.notifyObservers(this);
  23945. // Physics
  23946. if (this._physicsEngine) {
  23947. this.onBeforePhysicsObservable.notifyObservers(this);
  23948. this._physicsEngine._step(deltaTime / 1000.0);
  23949. this.onAfterPhysicsObservable.notifyObservers(this);
  23950. }
  23951. }
  23952. // update gamepad manager
  23953. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  23954. this._gamepadManager._checkGamepadsStatus();
  23955. }
  23956. // Before render
  23957. this.onBeforeRenderObservable.notifyObservers(this);
  23958. // Customs render targets
  23959. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  23960. var engine = this.getEngine();
  23961. var currentActiveCamera = this.activeCamera;
  23962. if (this.renderTargetsEnabled) {
  23963. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23964. this._intermediateRendering = true;
  23965. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  23966. var renderTarget = this.customRenderTargets[customIndex];
  23967. if (renderTarget._shouldRender()) {
  23968. this._renderId++;
  23969. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  23970. if (!this.activeCamera)
  23971. throw new Error("Active camera not set");
  23972. // Viewport
  23973. engine.setViewport(this.activeCamera.viewport);
  23974. // Camera
  23975. this.updateTransformMatrix();
  23976. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  23977. }
  23978. }
  23979. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  23980. this._intermediateRendering = false;
  23981. this._renderId++;
  23982. }
  23983. // Restore back buffer
  23984. if (this.customRenderTargets.length > 0) {
  23985. engine.restoreDefaultFramebuffer();
  23986. }
  23987. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  23988. this.activeCamera = currentActiveCamera;
  23989. // Procedural textures
  23990. if (this.proceduralTexturesEnabled) {
  23991. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23992. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  23993. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  23994. if (proceduralTexture._shouldRender()) {
  23995. proceduralTexture.render();
  23996. }
  23997. }
  23998. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  23999. }
  24000. // Clear
  24001. if (this.autoClearDepthAndStencil || this.autoClear) {
  24002. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24003. }
  24004. // Shadows
  24005. if (this.shadowsEnabled) {
  24006. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24007. var light = this.lights[lightIndex];
  24008. var shadowGenerator = light.getShadowGenerator();
  24009. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24010. var shadowMap = (shadowGenerator.getShadowMap());
  24011. if (this.textures.indexOf(shadowMap) !== -1) {
  24012. this._renderTargets.push(shadowMap);
  24013. }
  24014. }
  24015. }
  24016. }
  24017. // Depth renderer
  24018. if (this._depthRenderer) {
  24019. this._renderTargets.push(this._depthRenderer.getDepthMap());
  24020. }
  24021. // Geometry renderer
  24022. if (this._geometryBufferRenderer) {
  24023. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24024. }
  24025. // RenderPipeline
  24026. if (this._postProcessRenderPipelineManager) {
  24027. this._postProcessRenderPipelineManager.update();
  24028. }
  24029. // Multi-cameras?
  24030. if (this.activeCameras.length > 0) {
  24031. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24032. if (cameraIndex > 0) {
  24033. this._engine.clear(null, false, true, true);
  24034. }
  24035. this._processSubCameras(this.activeCameras[cameraIndex]);
  24036. }
  24037. }
  24038. else {
  24039. if (!this.activeCamera) {
  24040. throw new Error("No camera defined");
  24041. }
  24042. this._processSubCameras(this.activeCamera);
  24043. }
  24044. // Intersection checks
  24045. this._checkIntersections();
  24046. // Update the audio listener attached to the camera
  24047. if (BABYLON.AudioEngine) {
  24048. this._updateAudioParameters();
  24049. }
  24050. // After render
  24051. if (this.afterRender) {
  24052. this.afterRender();
  24053. }
  24054. this.onAfterRenderObservable.notifyObservers(this);
  24055. // Cleaning
  24056. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24057. var data = this._toBeDisposed.data[index];
  24058. if (data) {
  24059. data.dispose();
  24060. }
  24061. this._toBeDisposed[index] = null;
  24062. }
  24063. this._toBeDisposed.reset();
  24064. if (this.dumpNextRenderTargets) {
  24065. this.dumpNextRenderTargets = false;
  24066. }
  24067. this._activeBones.addCount(0, true);
  24068. this._activeIndices.addCount(0, true);
  24069. this._activeParticles.addCount(0, true);
  24070. };
  24071. Scene.prototype._updateAudioParameters = function () {
  24072. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24073. return;
  24074. }
  24075. var listeningCamera;
  24076. var audioEngine = BABYLON.Engine.audioEngine;
  24077. if (this.activeCameras.length > 0) {
  24078. listeningCamera = this.activeCameras[0];
  24079. }
  24080. else {
  24081. listeningCamera = this.activeCamera;
  24082. }
  24083. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24084. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24085. // for VR cameras
  24086. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24087. listeningCamera = listeningCamera.rigCameras[0];
  24088. }
  24089. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24090. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24091. cameraDirection.normalize();
  24092. // To avoid some errors on GearVR
  24093. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24094. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24095. }
  24096. var i;
  24097. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24098. var sound = this.mainSoundTrack.soundCollection[i];
  24099. if (sound.useCustomAttenuation) {
  24100. sound.updateDistanceFromListener();
  24101. }
  24102. }
  24103. for (i = 0; i < this.soundTracks.length; i++) {
  24104. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24105. sound = this.soundTracks[i].soundCollection[j];
  24106. if (sound.useCustomAttenuation) {
  24107. sound.updateDistanceFromListener();
  24108. }
  24109. }
  24110. }
  24111. }
  24112. };
  24113. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24114. // Audio
  24115. get: function () {
  24116. return this._audioEnabled;
  24117. },
  24118. set: function (value) {
  24119. this._audioEnabled = value;
  24120. if (BABYLON.AudioEngine) {
  24121. if (this._audioEnabled) {
  24122. this._enableAudio();
  24123. }
  24124. else {
  24125. this._disableAudio();
  24126. }
  24127. }
  24128. },
  24129. enumerable: true,
  24130. configurable: true
  24131. });
  24132. Scene.prototype._disableAudio = function () {
  24133. var i;
  24134. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24135. this.mainSoundTrack.soundCollection[i].pause();
  24136. }
  24137. for (i = 0; i < this.soundTracks.length; i++) {
  24138. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24139. this.soundTracks[i].soundCollection[j].pause();
  24140. }
  24141. }
  24142. };
  24143. Scene.prototype._enableAudio = function () {
  24144. var i;
  24145. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24146. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  24147. this.mainSoundTrack.soundCollection[i].play();
  24148. }
  24149. }
  24150. for (i = 0; i < this.soundTracks.length; i++) {
  24151. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24152. if (this.soundTracks[i].soundCollection[j].isPaused) {
  24153. this.soundTracks[i].soundCollection[j].play();
  24154. }
  24155. }
  24156. }
  24157. };
  24158. Object.defineProperty(Scene.prototype, "headphone", {
  24159. get: function () {
  24160. return this._headphone;
  24161. },
  24162. set: function (value) {
  24163. this._headphone = value;
  24164. if (BABYLON.AudioEngine) {
  24165. if (this._headphone) {
  24166. this._switchAudioModeForHeadphones();
  24167. }
  24168. else {
  24169. this._switchAudioModeForNormalSpeakers();
  24170. }
  24171. }
  24172. },
  24173. enumerable: true,
  24174. configurable: true
  24175. });
  24176. Scene.prototype._switchAudioModeForHeadphones = function () {
  24177. this.mainSoundTrack.switchPanningModelToHRTF();
  24178. for (var i = 0; i < this.soundTracks.length; i++) {
  24179. this.soundTracks[i].switchPanningModelToHRTF();
  24180. }
  24181. };
  24182. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  24183. this.mainSoundTrack.switchPanningModelToEqualPower();
  24184. for (var i = 0; i < this.soundTracks.length; i++) {
  24185. this.soundTracks[i].switchPanningModelToEqualPower();
  24186. }
  24187. };
  24188. Scene.prototype.enableDepthRenderer = function () {
  24189. if (this._depthRenderer) {
  24190. return this._depthRenderer;
  24191. }
  24192. this._depthRenderer = new BABYLON.DepthRenderer(this);
  24193. return this._depthRenderer;
  24194. };
  24195. Scene.prototype.disableDepthRenderer = function () {
  24196. if (!this._depthRenderer) {
  24197. return;
  24198. }
  24199. this._depthRenderer.dispose();
  24200. this._depthRenderer = null;
  24201. };
  24202. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  24203. if (ratio === void 0) { ratio = 1; }
  24204. if (this._geometryBufferRenderer) {
  24205. return this._geometryBufferRenderer;
  24206. }
  24207. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  24208. if (!this._geometryBufferRenderer.isSupported) {
  24209. this._geometryBufferRenderer = null;
  24210. }
  24211. return this._geometryBufferRenderer;
  24212. };
  24213. Scene.prototype.disableGeometryBufferRenderer = function () {
  24214. if (!this._geometryBufferRenderer) {
  24215. return;
  24216. }
  24217. this._geometryBufferRenderer.dispose();
  24218. this._geometryBufferRenderer = null;
  24219. };
  24220. Scene.prototype.freezeMaterials = function () {
  24221. for (var i = 0; i < this.materials.length; i++) {
  24222. this.materials[i].freeze();
  24223. }
  24224. };
  24225. Scene.prototype.unfreezeMaterials = function () {
  24226. for (var i = 0; i < this.materials.length; i++) {
  24227. this.materials[i].unfreeze();
  24228. }
  24229. };
  24230. Scene.prototype.dispose = function () {
  24231. this.beforeRender = null;
  24232. this.afterRender = null;
  24233. this.skeletons = [];
  24234. this.morphTargetManagers = [];
  24235. this.importedMeshesFiles = new Array();
  24236. this.stopAllAnimations();
  24237. this.resetCachedMaterial();
  24238. if (this._depthRenderer) {
  24239. this._depthRenderer.dispose();
  24240. }
  24241. if (this._gamepadManager) {
  24242. this._gamepadManager.dispose();
  24243. this._gamepadManager = null;
  24244. }
  24245. // Smart arrays
  24246. if (this.activeCamera) {
  24247. this.activeCamera._activeMeshes.dispose();
  24248. this.activeCamera = null;
  24249. }
  24250. this._activeMeshes.dispose();
  24251. this._renderingManager.dispose();
  24252. this._processedMaterials.dispose();
  24253. this._activeParticleSystems.dispose();
  24254. this._activeSkeletons.dispose();
  24255. this._softwareSkinnedMeshes.dispose();
  24256. this._renderTargets.dispose();
  24257. if (this._boundingBoxRenderer) {
  24258. this._boundingBoxRenderer.dispose();
  24259. }
  24260. this._meshesForIntersections.dispose();
  24261. this._toBeDisposed.dispose();
  24262. // Abort active requests
  24263. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  24264. var request = _a[_i];
  24265. request.abort();
  24266. }
  24267. // Debug layer
  24268. if (this._debugLayer) {
  24269. this._debugLayer.hide();
  24270. }
  24271. // Events
  24272. this.onDisposeObservable.notifyObservers(this);
  24273. this.onDisposeObservable.clear();
  24274. this.onBeforeRenderObservable.clear();
  24275. this.onAfterRenderObservable.clear();
  24276. this.OnBeforeRenderTargetsRenderObservable.clear();
  24277. this.OnAfterRenderTargetsRenderObservable.clear();
  24278. this.onAfterStepObservable.clear();
  24279. this.onBeforeStepObservable.clear();
  24280. this.onBeforeActiveMeshesEvaluationObservable.clear();
  24281. this.onAfterActiveMeshesEvaluationObservable.clear();
  24282. this.onBeforeParticlesRenderingObservable.clear();
  24283. this.onAfterParticlesRenderingObservable.clear();
  24284. this.onBeforeSpritesRenderingObservable.clear();
  24285. this.onAfterSpritesRenderingObservable.clear();
  24286. this.onBeforeDrawPhaseObservable.clear();
  24287. this.onAfterDrawPhaseObservable.clear();
  24288. this.onBeforePhysicsObservable.clear();
  24289. this.onAfterPhysicsObservable.clear();
  24290. this.onBeforeAnimationsObservable.clear();
  24291. this.onAfterAnimationsObservable.clear();
  24292. this.onDataLoadedObservable.clear();
  24293. this.detachControl();
  24294. // Release sounds & sounds tracks
  24295. if (BABYLON.AudioEngine) {
  24296. this.disposeSounds();
  24297. }
  24298. // VR Helper
  24299. if (this.VRHelper) {
  24300. this.VRHelper.dispose();
  24301. }
  24302. // Detach cameras
  24303. var canvas = this._engine.getRenderingCanvas();
  24304. if (canvas) {
  24305. var index;
  24306. for (index = 0; index < this.cameras.length; index++) {
  24307. this.cameras[index].detachControl(canvas);
  24308. }
  24309. }
  24310. // Release animation groups
  24311. while (this.animationGroups.length) {
  24312. this.animationGroups[0].dispose();
  24313. }
  24314. // Release lights
  24315. while (this.lights.length) {
  24316. this.lights[0].dispose();
  24317. }
  24318. // Release meshes
  24319. while (this.meshes.length) {
  24320. this.meshes[0].dispose(true);
  24321. }
  24322. while (this.transformNodes.length) {
  24323. this.removeTransformNode(this.transformNodes[0]);
  24324. }
  24325. // Release cameras
  24326. while (this.cameras.length) {
  24327. this.cameras[0].dispose();
  24328. }
  24329. // Release materials
  24330. if (this.defaultMaterial) {
  24331. this.defaultMaterial.dispose();
  24332. }
  24333. while (this.multiMaterials.length) {
  24334. this.multiMaterials[0].dispose();
  24335. }
  24336. while (this.materials.length) {
  24337. this.materials[0].dispose();
  24338. }
  24339. // Release particles
  24340. while (this.particleSystems.length) {
  24341. this.particleSystems[0].dispose();
  24342. }
  24343. // Release sprites
  24344. while (this.spriteManagers.length) {
  24345. this.spriteManagers[0].dispose();
  24346. }
  24347. // Release postProcesses
  24348. while (this.postProcesses.length) {
  24349. this.postProcesses[0].dispose();
  24350. }
  24351. // Release layers
  24352. while (this.layers.length) {
  24353. this.layers[0].dispose();
  24354. }
  24355. while (this.effectLayers.length) {
  24356. this.effectLayers[0].dispose();
  24357. }
  24358. // Release textures
  24359. while (this.textures.length) {
  24360. this.textures[0].dispose();
  24361. }
  24362. // Release UBO
  24363. this._sceneUbo.dispose();
  24364. if (this._alternateSceneUbo) {
  24365. this._alternateSceneUbo.dispose();
  24366. }
  24367. // Post-processes
  24368. this.postProcessManager.dispose();
  24369. if (this._postProcessRenderPipelineManager) {
  24370. this._postProcessRenderPipelineManager.dispose();
  24371. }
  24372. // Physics
  24373. if (this._physicsEngine) {
  24374. this.disablePhysicsEngine();
  24375. }
  24376. // Remove from engine
  24377. index = this._engine.scenes.indexOf(this);
  24378. if (index > -1) {
  24379. this._engine.scenes.splice(index, 1);
  24380. }
  24381. this._engine.wipeCaches(true);
  24382. this._isDisposed = true;
  24383. };
  24384. Object.defineProperty(Scene.prototype, "isDisposed", {
  24385. get: function () {
  24386. return this._isDisposed;
  24387. },
  24388. enumerable: true,
  24389. configurable: true
  24390. });
  24391. // Release sounds & sounds tracks
  24392. Scene.prototype.disposeSounds = function () {
  24393. if (!this._mainSoundTrack) {
  24394. return;
  24395. }
  24396. this.mainSoundTrack.dispose();
  24397. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  24398. this.soundTracks[scIndex].dispose();
  24399. }
  24400. };
  24401. // Octrees
  24402. /**
  24403. * Get the world extend vectors with an optional filter
  24404. *
  24405. * @param {(mesh: AbstractMesh) => boolean} [filterPredicate] the predicate - which meshes should be included when calculating the world size
  24406. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  24407. */
  24408. Scene.prototype.getWorldExtends = function (filterPredicate) {
  24409. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  24410. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  24411. filterPredicate = filterPredicate || (function () { return true; });
  24412. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  24413. mesh.computeWorldMatrix(true);
  24414. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  24415. return;
  24416. }
  24417. var boundingInfo = mesh.getBoundingInfo();
  24418. var minBox = boundingInfo.boundingBox.minimumWorld;
  24419. var maxBox = boundingInfo.boundingBox.maximumWorld;
  24420. BABYLON.Tools.CheckExtends(minBox, min, max);
  24421. BABYLON.Tools.CheckExtends(maxBox, min, max);
  24422. });
  24423. return {
  24424. min: min,
  24425. max: max
  24426. };
  24427. };
  24428. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  24429. if (maxCapacity === void 0) { maxCapacity = 64; }
  24430. if (maxDepth === void 0) { maxDepth = 2; }
  24431. if (!this._selectionOctree) {
  24432. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  24433. }
  24434. var worldExtends = this.getWorldExtends();
  24435. // Update octree
  24436. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  24437. return this._selectionOctree;
  24438. };
  24439. // Picking
  24440. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  24441. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24442. var result = BABYLON.Ray.Zero();
  24443. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  24444. return result;
  24445. };
  24446. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  24447. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  24448. var engine = this._engine;
  24449. if (!camera) {
  24450. if (!this.activeCamera)
  24451. throw new Error("Active camera not set");
  24452. camera = this.activeCamera;
  24453. }
  24454. var cameraViewport = camera.viewport;
  24455. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24456. // Moving coordinates to local viewport world
  24457. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24458. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24459. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  24460. return this;
  24461. };
  24462. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  24463. var result = BABYLON.Ray.Zero();
  24464. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  24465. return result;
  24466. };
  24467. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  24468. if (!BABYLON.PickingInfo) {
  24469. return this;
  24470. }
  24471. var engine = this._engine;
  24472. if (!camera) {
  24473. if (!this.activeCamera)
  24474. throw new Error("Active camera not set");
  24475. camera = this.activeCamera;
  24476. }
  24477. var cameraViewport = camera.viewport;
  24478. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  24479. var identity = BABYLON.Matrix.Identity();
  24480. // Moving coordinates to local viewport world
  24481. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  24482. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  24483. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  24484. return this;
  24485. };
  24486. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  24487. if (!BABYLON.PickingInfo) {
  24488. return null;
  24489. }
  24490. var pickingInfo = null;
  24491. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24492. var mesh = this.meshes[meshIndex];
  24493. if (predicate) {
  24494. if (!predicate(mesh)) {
  24495. continue;
  24496. }
  24497. }
  24498. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24499. continue;
  24500. }
  24501. var world = mesh.getWorldMatrix();
  24502. var ray = rayFunction(world);
  24503. var result = mesh.intersects(ray, fastCheck);
  24504. if (!result || !result.hit)
  24505. continue;
  24506. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24507. continue;
  24508. pickingInfo = result;
  24509. if (fastCheck) {
  24510. break;
  24511. }
  24512. }
  24513. return pickingInfo || new BABYLON.PickingInfo();
  24514. };
  24515. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  24516. if (!BABYLON.PickingInfo) {
  24517. return null;
  24518. }
  24519. var pickingInfos = new Array();
  24520. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  24521. var mesh = this.meshes[meshIndex];
  24522. if (predicate) {
  24523. if (!predicate(mesh)) {
  24524. continue;
  24525. }
  24526. }
  24527. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  24528. continue;
  24529. }
  24530. var world = mesh.getWorldMatrix();
  24531. var ray = rayFunction(world);
  24532. var result = mesh.intersects(ray, false);
  24533. if (!result || !result.hit)
  24534. continue;
  24535. pickingInfos.push(result);
  24536. }
  24537. return pickingInfos;
  24538. };
  24539. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  24540. if (!BABYLON.PickingInfo) {
  24541. return null;
  24542. }
  24543. var pickingInfo = null;
  24544. if (!camera) {
  24545. if (!this.activeCamera) {
  24546. return null;
  24547. }
  24548. camera = this.activeCamera;
  24549. }
  24550. if (this.spriteManagers.length > 0) {
  24551. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  24552. var spriteManager = this.spriteManagers[spriteIndex];
  24553. if (!spriteManager.isPickable) {
  24554. continue;
  24555. }
  24556. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  24557. if (!result || !result.hit)
  24558. continue;
  24559. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  24560. continue;
  24561. pickingInfo = result;
  24562. if (fastCheck) {
  24563. break;
  24564. }
  24565. }
  24566. }
  24567. return pickingInfo || new BABYLON.PickingInfo();
  24568. };
  24569. /** Launch a ray to try to pick a mesh in the scene
  24570. * @param x position on screen
  24571. * @param y position on screen
  24572. * @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
  24573. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24574. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24575. */
  24576. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  24577. var _this = this;
  24578. if (!BABYLON.PickingInfo) {
  24579. return null;
  24580. }
  24581. return this._internalPick(function (world) {
  24582. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  24583. return _this._tempPickingRay;
  24584. }, predicate, fastCheck);
  24585. };
  24586. /** Launch a ray to try to pick a sprite in the scene
  24587. * @param x position on screen
  24588. * @param y position on screen
  24589. * @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
  24590. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24591. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24592. */
  24593. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  24594. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  24595. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  24596. };
  24597. /** Use the given ray to pick a mesh in the scene
  24598. * @param ray The ray to use to pick meshes
  24599. * @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
  24600. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  24601. */
  24602. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  24603. var _this = this;
  24604. return this._internalPick(function (world) {
  24605. if (!_this._pickWithRayInverseMatrix) {
  24606. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24607. }
  24608. world.invertToRef(_this._pickWithRayInverseMatrix);
  24609. if (!_this._cachedRayForTransform) {
  24610. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24611. }
  24612. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24613. return _this._cachedRayForTransform;
  24614. }, predicate, fastCheck);
  24615. };
  24616. /**
  24617. * Launch a ray to try to pick a mesh in the scene
  24618. * @param x X position on screen
  24619. * @param y Y position on screen
  24620. * @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
  24621. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  24622. */
  24623. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  24624. var _this = this;
  24625. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  24626. };
  24627. /**
  24628. * Launch a ray to try to pick a mesh in the scene
  24629. * @param ray Ray to use
  24630. * @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
  24631. */
  24632. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  24633. var _this = this;
  24634. return this._internalMultiPick(function (world) {
  24635. if (!_this._pickWithRayInverseMatrix) {
  24636. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  24637. }
  24638. world.invertToRef(_this._pickWithRayInverseMatrix);
  24639. if (!_this._cachedRayForTransform) {
  24640. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  24641. }
  24642. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  24643. return _this._cachedRayForTransform;
  24644. }, predicate);
  24645. };
  24646. Scene.prototype.setPointerOverMesh = function (mesh) {
  24647. if (this._pointerOverMesh === mesh) {
  24648. return;
  24649. }
  24650. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24651. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24652. }
  24653. this._pointerOverMesh = mesh;
  24654. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  24655. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  24656. }
  24657. };
  24658. Scene.prototype.getPointerOverMesh = function () {
  24659. return this._pointerOverMesh;
  24660. };
  24661. Scene.prototype.setPointerOverSprite = function (sprite) {
  24662. if (this._pointerOverSprite === sprite) {
  24663. return;
  24664. }
  24665. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24666. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24667. }
  24668. this._pointerOverSprite = sprite;
  24669. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  24670. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  24671. }
  24672. };
  24673. Scene.prototype.getPointerOverSprite = function () {
  24674. return this._pointerOverSprite;
  24675. };
  24676. // Physics
  24677. Scene.prototype.getPhysicsEngine = function () {
  24678. return this._physicsEngine;
  24679. };
  24680. /**
  24681. * Enables physics to the current scene
  24682. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  24683. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  24684. * @return {boolean} was the physics engine initialized
  24685. */
  24686. Scene.prototype.enablePhysics = function (gravity, plugin) {
  24687. if (gravity === void 0) { gravity = null; }
  24688. if (this._physicsEngine) {
  24689. return true;
  24690. }
  24691. try {
  24692. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  24693. return true;
  24694. }
  24695. catch (e) {
  24696. BABYLON.Tools.Error(e.message);
  24697. return false;
  24698. }
  24699. };
  24700. Scene.prototype.disablePhysicsEngine = function () {
  24701. if (!this._physicsEngine) {
  24702. return;
  24703. }
  24704. this._physicsEngine.dispose();
  24705. this._physicsEngine = null;
  24706. };
  24707. Scene.prototype.isPhysicsEnabled = function () {
  24708. return this._physicsEngine !== undefined;
  24709. };
  24710. Scene.prototype.deleteCompoundImpostor = function (compound) {
  24711. var mesh = compound.parts[0].mesh;
  24712. if (mesh.physicsImpostor) {
  24713. mesh.physicsImpostor.dispose();
  24714. mesh.physicsImpostor = null;
  24715. }
  24716. };
  24717. // Misc.
  24718. Scene.prototype._rebuildGeometries = function () {
  24719. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  24720. var geometry = _a[_i];
  24721. geometry._rebuild();
  24722. }
  24723. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  24724. var mesh = _c[_b];
  24725. mesh._rebuild();
  24726. }
  24727. if (this.postProcessManager) {
  24728. this.postProcessManager._rebuild();
  24729. }
  24730. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  24731. var layer = _e[_d];
  24732. layer._rebuild();
  24733. }
  24734. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  24735. var effectLayer = _g[_f];
  24736. effectLayer._rebuild();
  24737. }
  24738. if (this._boundingBoxRenderer) {
  24739. this._boundingBoxRenderer._rebuild();
  24740. }
  24741. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  24742. var system = _j[_h];
  24743. system.rebuild();
  24744. }
  24745. if (this._postProcessRenderPipelineManager) {
  24746. this._postProcessRenderPipelineManager._rebuild();
  24747. }
  24748. };
  24749. Scene.prototype._rebuildTextures = function () {
  24750. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  24751. var texture = _a[_i];
  24752. texture._rebuild();
  24753. }
  24754. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24755. };
  24756. /**
  24757. * Creates a default light for the scene.
  24758. * @param replace Whether to replace the existing lights in the scene.
  24759. */
  24760. Scene.prototype.createDefaultLight = function (replace) {
  24761. if (replace === void 0) { replace = false; }
  24762. // Dispose existing light in replace mode.
  24763. if (replace) {
  24764. if (this.lights) {
  24765. for (var i = 0; i < this.lights.length; i++) {
  24766. this.lights[i].dispose();
  24767. }
  24768. }
  24769. }
  24770. // Light
  24771. if (this.lights.length === 0) {
  24772. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  24773. }
  24774. };
  24775. /**
  24776. * Creates a default camera for the scene.
  24777. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  24778. * @param replace Whether to replace the existing active camera in the scene.
  24779. * @param attachCameraControls Whether to attach camera controls to the canvas.
  24780. */
  24781. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  24782. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24783. if (replace === void 0) { replace = false; }
  24784. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24785. // Dispose existing camera in replace mode.
  24786. if (replace) {
  24787. if (this.activeCamera) {
  24788. this.activeCamera.dispose();
  24789. this.activeCamera = null;
  24790. }
  24791. }
  24792. // Camera
  24793. if (!this.activeCamera) {
  24794. var worldExtends = this.getWorldExtends();
  24795. var worldSize = worldExtends.max.subtract(worldExtends.min);
  24796. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  24797. var camera;
  24798. var radius = worldSize.length() * 1.5;
  24799. // empty scene scenario!
  24800. if (!isFinite(radius)) {
  24801. radius = 1;
  24802. worldCenter.copyFromFloats(0, 0, 0);
  24803. }
  24804. if (createArcRotateCamera) {
  24805. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  24806. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  24807. arcRotateCamera.wheelPrecision = 100 / radius;
  24808. camera = arcRotateCamera;
  24809. }
  24810. else {
  24811. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  24812. freeCamera.setTarget(worldCenter);
  24813. camera = freeCamera;
  24814. }
  24815. camera.minZ = radius * 0.01;
  24816. camera.maxZ = radius * 1000;
  24817. camera.speed = radius * 0.2;
  24818. this.activeCamera = camera;
  24819. var canvas = this.getEngine().getRenderingCanvas();
  24820. if (attachCameraControls && canvas) {
  24821. camera.attachControl(canvas);
  24822. }
  24823. }
  24824. };
  24825. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  24826. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  24827. if (replace === void 0) { replace = false; }
  24828. if (attachCameraControls === void 0) { attachCameraControls = false; }
  24829. this.createDefaultLight(replace);
  24830. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  24831. };
  24832. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  24833. if (pbr === void 0) { pbr = false; }
  24834. if (scale === void 0) { scale = 1000; }
  24835. if (blur === void 0) { blur = 0; }
  24836. if (environmentTexture) {
  24837. this.environmentTexture = environmentTexture;
  24838. }
  24839. if (!this.environmentTexture) {
  24840. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  24841. return null;
  24842. }
  24843. // Skybox
  24844. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  24845. if (pbr) {
  24846. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  24847. hdrSkyboxMaterial.backFaceCulling = false;
  24848. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24849. if (hdrSkyboxMaterial.reflectionTexture) {
  24850. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24851. }
  24852. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  24853. hdrSkyboxMaterial.disableLighting = true;
  24854. hdrSkyboxMaterial.twoSidedLighting = true;
  24855. hdrSkybox.infiniteDistance = true;
  24856. hdrSkybox.material = hdrSkyboxMaterial;
  24857. }
  24858. else {
  24859. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  24860. skyboxMaterial.backFaceCulling = false;
  24861. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  24862. if (skyboxMaterial.reflectionTexture) {
  24863. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  24864. }
  24865. skyboxMaterial.disableLighting = true;
  24866. hdrSkybox.infiniteDistance = true;
  24867. hdrSkybox.material = skyboxMaterial;
  24868. }
  24869. return hdrSkybox;
  24870. };
  24871. Scene.prototype.createDefaultEnvironment = function (options) {
  24872. if (BABYLON.EnvironmentHelper) {
  24873. return new BABYLON.EnvironmentHelper(options, this);
  24874. }
  24875. return null;
  24876. };
  24877. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  24878. if (webVROptions === void 0) { webVROptions = {}; }
  24879. return new BABYLON.VRExperienceHelper(this, webVROptions);
  24880. };
  24881. // Tags
  24882. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  24883. if (tagsQuery === undefined) {
  24884. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  24885. return list;
  24886. }
  24887. var listByTags = [];
  24888. forEach = forEach || (function (item) { return; });
  24889. for (var i in list) {
  24890. var item = list[i];
  24891. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  24892. listByTags.push(item);
  24893. forEach(item);
  24894. }
  24895. }
  24896. return listByTags;
  24897. };
  24898. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  24899. return this._getByTags(this.meshes, tagsQuery, forEach);
  24900. };
  24901. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  24902. return this._getByTags(this.cameras, tagsQuery, forEach);
  24903. };
  24904. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  24905. return this._getByTags(this.lights, tagsQuery, forEach);
  24906. };
  24907. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  24908. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  24909. };
  24910. /**
  24911. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24912. * This allowed control for front to back rendering or reversly depending of the special needs.
  24913. *
  24914. * @param renderingGroupId The rendering group id corresponding to its index
  24915. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24916. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24917. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24918. */
  24919. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24920. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24921. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24922. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24923. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24924. };
  24925. /**
  24926. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24927. *
  24928. * @param renderingGroupId The rendering group id corresponding to its index
  24929. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24930. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24931. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24932. */
  24933. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24934. if (depth === void 0) { depth = true; }
  24935. if (stencil === void 0) { stencil = true; }
  24936. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  24937. };
  24938. /**
  24939. * Will flag all materials as dirty to trigger new shader compilation
  24940. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  24941. */
  24942. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  24943. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  24944. var material = _a[_i];
  24945. if (predicate && !predicate(material)) {
  24946. continue;
  24947. }
  24948. material.markAsDirty(flag);
  24949. }
  24950. };
  24951. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  24952. var _this = this;
  24953. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  24954. this._activeRequests.push(request);
  24955. request.onCompleteObservable.add(function (request) {
  24956. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  24957. });
  24958. return request;
  24959. };
  24960. /** @ignore */
  24961. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  24962. var _this = this;
  24963. return new Promise(function (resolve, reject) {
  24964. _this._loadFile(url, function (data) {
  24965. resolve(data);
  24966. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  24967. reject(exception);
  24968. });
  24969. });
  24970. };
  24971. // Statics
  24972. Scene._FOGMODE_NONE = 0;
  24973. Scene._FOGMODE_EXP = 1;
  24974. Scene._FOGMODE_EXP2 = 2;
  24975. Scene._FOGMODE_LINEAR = 3;
  24976. Scene._uniqueIdCounter = 0;
  24977. Scene.MinDeltaTime = 1.0;
  24978. Scene.MaxDeltaTime = 1000.0;
  24979. /** The distance in pixel that you have to move to prevent some events */
  24980. Scene.DragMovementThreshold = 10; // in pixels
  24981. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  24982. Scene.LongPressDelay = 500; // in milliseconds
  24983. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  24984. Scene.DoubleClickDelay = 300; // in milliseconds
  24985. /** If you need to check double click without raising a single click at first click, enable this flag */
  24986. Scene.ExclusiveDoubleClickMode = false;
  24987. return Scene;
  24988. }());
  24989. BABYLON.Scene = Scene;
  24990. })(BABYLON || (BABYLON = {}));
  24991. //# sourceMappingURL=babylon.scene.js.map
  24992. var BABYLON;
  24993. (function (BABYLON) {
  24994. /**
  24995. * Set of assets to keep when moving a scene into an asset container.
  24996. */
  24997. var KeepAssets = /** @class */ (function () {
  24998. function KeepAssets() {
  24999. /**
  25000. * Cameras to keep.
  25001. */
  25002. this.cameras = new Array();
  25003. /**
  25004. * Lights to keep.
  25005. */
  25006. this.lights = new Array();
  25007. /**
  25008. * Meshes to keep.
  25009. */
  25010. this.meshes = new Array();
  25011. /**
  25012. * Skeletons to keep.
  25013. */
  25014. this.skeletons = new Array();
  25015. /**
  25016. * ParticleSystems to keep.
  25017. */
  25018. this.particleSystems = new Array();
  25019. /**
  25020. * Animations to keep.
  25021. */
  25022. this.animations = new Array();
  25023. /**
  25024. * MultiMaterials to keep.
  25025. */
  25026. this.multiMaterials = new Array();
  25027. /**
  25028. * Materials to keep.
  25029. */
  25030. this.materials = new Array();
  25031. /**
  25032. * MorphTargetManagers to keep.
  25033. */
  25034. this.morphTargetManagers = new Array();
  25035. /**
  25036. * Geometries to keep.
  25037. */
  25038. this.geometries = new Array();
  25039. /**
  25040. * TransformNodes to keep.
  25041. */
  25042. this.transformNodes = new Array();
  25043. /**
  25044. * LensFlareSystems to keep.
  25045. */
  25046. this.lensFlareSystems = new Array();
  25047. /**
  25048. * ShadowGenerators to keep.
  25049. */
  25050. this.shadowGenerators = new Array();
  25051. /**
  25052. * ActionManagers to keep.
  25053. */
  25054. this.actionManagers = new Array();
  25055. /**
  25056. * Sounds to keep.
  25057. */
  25058. this.sounds = new Array();
  25059. }
  25060. return KeepAssets;
  25061. }());
  25062. BABYLON.KeepAssets = KeepAssets;
  25063. /**
  25064. * Container with a set of assets that can be added or removed from a scene.
  25065. */
  25066. var AssetContainer = /** @class */ (function () {
  25067. /**
  25068. * Instantiates an AssetContainer.
  25069. * @param scene The scene the AssetContainer belongs to.
  25070. */
  25071. function AssetContainer(scene) {
  25072. // Objects
  25073. /**
  25074. * Cameras populated in the container.
  25075. */
  25076. this.cameras = new Array();
  25077. /**
  25078. * Lights populated in the container.
  25079. */
  25080. this.lights = new Array();
  25081. /**
  25082. * Meshes populated in the container.
  25083. */
  25084. this.meshes = new Array();
  25085. /**
  25086. * Skeletons populated in the container.
  25087. */
  25088. this.skeletons = new Array();
  25089. /**
  25090. * ParticleSystems populated in the container.
  25091. */
  25092. this.particleSystems = new Array();
  25093. /**
  25094. * Animations populated in the container.
  25095. */
  25096. this.animations = new Array();
  25097. /**
  25098. * MultiMaterials populated in the container.
  25099. */
  25100. this.multiMaterials = new Array();
  25101. /**
  25102. * Materials populated in the container.
  25103. */
  25104. this.materials = new Array();
  25105. /**
  25106. * MorphTargetManagers populated in the container.
  25107. */
  25108. this.morphTargetManagers = new Array();
  25109. /**
  25110. * Geometries populated in the container.
  25111. */
  25112. this.geometries = new Array();
  25113. /**
  25114. * TransformNodes populated in the container.
  25115. */
  25116. this.transformNodes = new Array();
  25117. /**
  25118. * LensFlareSystems populated in the container.
  25119. */
  25120. this.lensFlareSystems = new Array();
  25121. /**
  25122. * ShadowGenerators populated in the container.
  25123. */
  25124. this.shadowGenerators = new Array();
  25125. /**
  25126. * ActionManagers populated in the container.
  25127. */
  25128. this.actionManagers = new Array();
  25129. /**
  25130. * Sounds populated in the container.
  25131. */
  25132. this.sounds = new Array();
  25133. this.scene = scene;
  25134. }
  25135. /**
  25136. * Adds all the assets from the container to the scene.
  25137. */
  25138. AssetContainer.prototype.addAllToScene = function () {
  25139. var _this = this;
  25140. this.cameras.forEach(function (o) {
  25141. _this.scene.addCamera(o);
  25142. });
  25143. this.lights.forEach(function (o) {
  25144. _this.scene.addLight(o);
  25145. });
  25146. this.meshes.forEach(function (o) {
  25147. _this.scene.addMesh(o);
  25148. });
  25149. this.skeletons.forEach(function (o) {
  25150. _this.scene.addSkeleton(o);
  25151. });
  25152. this.particleSystems.forEach(function (o) {
  25153. _this.scene.addParticleSystem(o);
  25154. });
  25155. this.animations.forEach(function (o) {
  25156. _this.scene.addAnimation(o);
  25157. });
  25158. this.multiMaterials.forEach(function (o) {
  25159. _this.scene.addMultiMaterial(o);
  25160. });
  25161. this.materials.forEach(function (o) {
  25162. _this.scene.addMaterial(o);
  25163. });
  25164. this.morphTargetManagers.forEach(function (o) {
  25165. _this.scene.addMorphTargetManager(o);
  25166. });
  25167. this.geometries.forEach(function (o) {
  25168. _this.scene.addGeometry(o);
  25169. });
  25170. this.transformNodes.forEach(function (o) {
  25171. _this.scene.addTransformNode(o);
  25172. });
  25173. this.lensFlareSystems.forEach(function (o) {
  25174. _this.scene.addLensFlareSystem(o);
  25175. });
  25176. this.actionManagers.forEach(function (o) {
  25177. _this.scene.addActionManager(o);
  25178. });
  25179. this.sounds.forEach(function (o) {
  25180. o.play();
  25181. o.autoplay = true;
  25182. _this.scene.mainSoundTrack.AddSound(o);
  25183. });
  25184. };
  25185. /**
  25186. * Removes all the assets in the container from the scene
  25187. */
  25188. AssetContainer.prototype.removeAllFromScene = function () {
  25189. var _this = this;
  25190. this.cameras.forEach(function (o) {
  25191. _this.scene.removeCamera(o);
  25192. });
  25193. this.lights.forEach(function (o) {
  25194. _this.scene.removeLight(o);
  25195. });
  25196. this.meshes.forEach(function (o) {
  25197. _this.scene.removeMesh(o);
  25198. });
  25199. this.skeletons.forEach(function (o) {
  25200. _this.scene.removeSkeleton(o);
  25201. });
  25202. this.particleSystems.forEach(function (o) {
  25203. _this.scene.removeParticleSystem(o);
  25204. });
  25205. this.animations.forEach(function (o) {
  25206. _this.scene.removeAnimation(o);
  25207. });
  25208. this.multiMaterials.forEach(function (o) {
  25209. _this.scene.removeMultiMaterial(o);
  25210. });
  25211. this.materials.forEach(function (o) {
  25212. _this.scene.removeMaterial(o);
  25213. });
  25214. this.morphTargetManagers.forEach(function (o) {
  25215. _this.scene.removeMorphTargetManager(o);
  25216. });
  25217. this.geometries.forEach(function (o) {
  25218. _this.scene.removeGeometry(o);
  25219. });
  25220. this.transformNodes.forEach(function (o) {
  25221. _this.scene.removeTransformNode(o);
  25222. });
  25223. this.lensFlareSystems.forEach(function (o) {
  25224. _this.scene.removeLensFlareSystem(o);
  25225. });
  25226. this.actionManagers.forEach(function (o) {
  25227. _this.scene.removeActionManager(o);
  25228. });
  25229. this.sounds.forEach(function (o) {
  25230. o.stop();
  25231. o.autoplay = false;
  25232. _this.scene.mainSoundTrack.RemoveSound(o);
  25233. });
  25234. };
  25235. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  25236. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  25237. var asset = sourceAssets_1[_i];
  25238. var move = true;
  25239. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  25240. var keepAsset = keepAssets_1[_a];
  25241. if (asset === keepAsset) {
  25242. move = false;
  25243. break;
  25244. }
  25245. }
  25246. if (move) {
  25247. targetAssets.push(asset);
  25248. }
  25249. }
  25250. };
  25251. /**
  25252. * Removes all the assets contained in the scene and adds them to the container.
  25253. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  25254. */
  25255. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  25256. if (keepAssets === undefined) {
  25257. keepAssets = new KeepAssets();
  25258. }
  25259. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  25260. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  25261. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  25262. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  25263. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  25264. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  25265. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  25266. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  25267. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  25268. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  25269. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  25270. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  25271. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  25272. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  25273. this.removeAllFromScene();
  25274. };
  25275. return AssetContainer;
  25276. }());
  25277. BABYLON.AssetContainer = AssetContainer;
  25278. })(BABYLON || (BABYLON = {}));
  25279. //# sourceMappingURL=babylon.assetContainer.js.map
  25280. var BABYLON;
  25281. (function (BABYLON) {
  25282. var Buffer = /** @class */ (function () {
  25283. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  25284. if (instanced === void 0) { instanced = false; }
  25285. if (engine instanceof BABYLON.Mesh) {
  25286. this._engine = engine.getScene().getEngine();
  25287. }
  25288. else {
  25289. this._engine = engine;
  25290. }
  25291. this._updatable = updatable;
  25292. this._instanced = instanced;
  25293. this._data = data;
  25294. this._strideSize = stride;
  25295. if (!postponeInternalCreation) {
  25296. this.create();
  25297. }
  25298. }
  25299. /**
  25300. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  25301. * @param kind defines the vertex buffer kind (position, normal, etc.)
  25302. * @param offset defines offset in the buffer (0 by default)
  25303. * @param size defines the size in floats of attributes (position is 3 for instance)
  25304. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  25305. * @param instanced defines if the vertex buffer contains indexed data
  25306. * @returns the new vertex buffer
  25307. */
  25308. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  25309. // a lot of these parameters are ignored as they are overriden by the buffer
  25310. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  25311. };
  25312. // Properties
  25313. Buffer.prototype.isUpdatable = function () {
  25314. return this._updatable;
  25315. };
  25316. Buffer.prototype.getData = function () {
  25317. return this._data;
  25318. };
  25319. Buffer.prototype.getBuffer = function () {
  25320. return this._buffer;
  25321. };
  25322. Buffer.prototype.getStrideSize = function () {
  25323. return this._strideSize;
  25324. };
  25325. // public getIsInstanced(): boolean {
  25326. // return this._instanced;
  25327. // }
  25328. // public get instanceDivisor(): number {
  25329. // return this._instanceDivisor;
  25330. // }
  25331. // public set instanceDivisor(value: number) {
  25332. // this._instanceDivisor = value;
  25333. // if (value == 0) {
  25334. // this._instanced = false;
  25335. // } else {
  25336. // this._instanced = true;
  25337. // }
  25338. // }
  25339. // Methods
  25340. Buffer.prototype.create = function (data) {
  25341. if (data === void 0) { data = null; }
  25342. if (!data && this._buffer) {
  25343. return; // nothing to do
  25344. }
  25345. data = data || this._data;
  25346. if (!data) {
  25347. return;
  25348. }
  25349. if (!this._buffer) {
  25350. if (this._updatable) {
  25351. this._buffer = this._engine.createDynamicVertexBuffer(data);
  25352. this._data = data;
  25353. }
  25354. else {
  25355. this._buffer = this._engine.createVertexBuffer(data);
  25356. }
  25357. }
  25358. else if (this._updatable) {
  25359. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  25360. this._data = data;
  25361. }
  25362. };
  25363. Buffer.prototype._rebuild = function () {
  25364. this._buffer = null;
  25365. this.create(this._data);
  25366. };
  25367. Buffer.prototype.update = function (data) {
  25368. this.create(data);
  25369. };
  25370. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  25371. if (!this._buffer) {
  25372. return;
  25373. }
  25374. if (this._updatable) {
  25375. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  25376. this._data = null;
  25377. }
  25378. };
  25379. Buffer.prototype.dispose = function () {
  25380. if (!this._buffer) {
  25381. return;
  25382. }
  25383. if (this._engine._releaseBuffer(this._buffer)) {
  25384. this._buffer = null;
  25385. }
  25386. };
  25387. return Buffer;
  25388. }());
  25389. BABYLON.Buffer = Buffer;
  25390. })(BABYLON || (BABYLON = {}));
  25391. //# sourceMappingURL=babylon.buffer.js.map
  25392. var BABYLON;
  25393. (function (BABYLON) {
  25394. var VertexBuffer = /** @class */ (function () {
  25395. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  25396. if (data instanceof BABYLON.Buffer) {
  25397. if (!stride) {
  25398. stride = data.getStrideSize();
  25399. }
  25400. this._buffer = data;
  25401. this._ownsBuffer = false;
  25402. }
  25403. else {
  25404. if (!stride) {
  25405. stride = VertexBuffer.DeduceStride(kind);
  25406. }
  25407. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  25408. this._ownsBuffer = true;
  25409. }
  25410. this._stride = stride;
  25411. this._instanced = instanced !== undefined ? instanced : false;
  25412. this._instanceDivisor = instanced ? 1 : 0;
  25413. this._offset = offset ? offset : 0;
  25414. this._size = size ? size : stride;
  25415. this._kind = kind;
  25416. }
  25417. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  25418. /**
  25419. * Gets or sets the instance divisor when in instanced mode
  25420. */
  25421. get: function () {
  25422. return this._instanceDivisor;
  25423. },
  25424. set: function (value) {
  25425. this._instanceDivisor = value;
  25426. if (value == 0) {
  25427. this._instanced = false;
  25428. }
  25429. else {
  25430. this._instanced = true;
  25431. }
  25432. },
  25433. enumerable: true,
  25434. configurable: true
  25435. });
  25436. VertexBuffer.prototype._rebuild = function () {
  25437. if (!this._buffer) {
  25438. return;
  25439. }
  25440. this._buffer._rebuild();
  25441. };
  25442. /**
  25443. * Returns the kind of the VertexBuffer (string).
  25444. */
  25445. VertexBuffer.prototype.getKind = function () {
  25446. return this._kind;
  25447. };
  25448. // Properties
  25449. /**
  25450. * Boolean : is the VertexBuffer updatable ?
  25451. */
  25452. VertexBuffer.prototype.isUpdatable = function () {
  25453. return this._buffer.isUpdatable();
  25454. };
  25455. /**
  25456. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  25457. */
  25458. VertexBuffer.prototype.getData = function () {
  25459. return this._buffer.getData();
  25460. };
  25461. /**
  25462. * Returns the WebGLBuffer associated to the VertexBuffer.
  25463. */
  25464. VertexBuffer.prototype.getBuffer = function () {
  25465. return this._buffer.getBuffer();
  25466. };
  25467. /**
  25468. * Returns the stride of the VertexBuffer (integer).
  25469. */
  25470. VertexBuffer.prototype.getStrideSize = function () {
  25471. return this._stride;
  25472. };
  25473. /**
  25474. * Returns the offset (integer).
  25475. */
  25476. VertexBuffer.prototype.getOffset = function () {
  25477. return this._offset;
  25478. };
  25479. /**
  25480. * Returns the VertexBuffer total size (integer).
  25481. */
  25482. VertexBuffer.prototype.getSize = function () {
  25483. return this._size;
  25484. };
  25485. /**
  25486. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  25487. */
  25488. VertexBuffer.prototype.getIsInstanced = function () {
  25489. return this._instanced;
  25490. };
  25491. /**
  25492. * Returns the instancing divisor, zero for non-instanced (integer).
  25493. */
  25494. VertexBuffer.prototype.getInstanceDivisor = function () {
  25495. return this._instanceDivisor;
  25496. };
  25497. // Methods
  25498. /**
  25499. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  25500. * Returns the created WebGLBuffer.
  25501. */
  25502. VertexBuffer.prototype.create = function (data) {
  25503. return this._buffer.create(data);
  25504. };
  25505. /**
  25506. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25507. * This function will create a new buffer if the current one is not updatable
  25508. * Returns the updated WebGLBuffer.
  25509. */
  25510. VertexBuffer.prototype.update = function (data) {
  25511. return this._buffer.update(data);
  25512. };
  25513. /**
  25514. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  25515. * Returns the directly updated WebGLBuffer.
  25516. */
  25517. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  25518. return this._buffer.updateDirectly(data, offset);
  25519. };
  25520. /**
  25521. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  25522. */
  25523. VertexBuffer.prototype.dispose = function () {
  25524. if (this._ownsBuffer) {
  25525. this._buffer.dispose();
  25526. }
  25527. };
  25528. Object.defineProperty(VertexBuffer, "PositionKind", {
  25529. get: function () {
  25530. return VertexBuffer._PositionKind;
  25531. },
  25532. enumerable: true,
  25533. configurable: true
  25534. });
  25535. Object.defineProperty(VertexBuffer, "NormalKind", {
  25536. get: function () {
  25537. return VertexBuffer._NormalKind;
  25538. },
  25539. enumerable: true,
  25540. configurable: true
  25541. });
  25542. Object.defineProperty(VertexBuffer, "TangentKind", {
  25543. get: function () {
  25544. return VertexBuffer._TangentKind;
  25545. },
  25546. enumerable: true,
  25547. configurable: true
  25548. });
  25549. Object.defineProperty(VertexBuffer, "UVKind", {
  25550. get: function () {
  25551. return VertexBuffer._UVKind;
  25552. },
  25553. enumerable: true,
  25554. configurable: true
  25555. });
  25556. Object.defineProperty(VertexBuffer, "UV2Kind", {
  25557. get: function () {
  25558. return VertexBuffer._UV2Kind;
  25559. },
  25560. enumerable: true,
  25561. configurable: true
  25562. });
  25563. Object.defineProperty(VertexBuffer, "UV3Kind", {
  25564. get: function () {
  25565. return VertexBuffer._UV3Kind;
  25566. },
  25567. enumerable: true,
  25568. configurable: true
  25569. });
  25570. Object.defineProperty(VertexBuffer, "UV4Kind", {
  25571. get: function () {
  25572. return VertexBuffer._UV4Kind;
  25573. },
  25574. enumerable: true,
  25575. configurable: true
  25576. });
  25577. Object.defineProperty(VertexBuffer, "UV5Kind", {
  25578. get: function () {
  25579. return VertexBuffer._UV5Kind;
  25580. },
  25581. enumerable: true,
  25582. configurable: true
  25583. });
  25584. Object.defineProperty(VertexBuffer, "UV6Kind", {
  25585. get: function () {
  25586. return VertexBuffer._UV6Kind;
  25587. },
  25588. enumerable: true,
  25589. configurable: true
  25590. });
  25591. Object.defineProperty(VertexBuffer, "ColorKind", {
  25592. get: function () {
  25593. return VertexBuffer._ColorKind;
  25594. },
  25595. enumerable: true,
  25596. configurable: true
  25597. });
  25598. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  25599. get: function () {
  25600. return VertexBuffer._MatricesIndicesKind;
  25601. },
  25602. enumerable: true,
  25603. configurable: true
  25604. });
  25605. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  25606. get: function () {
  25607. return VertexBuffer._MatricesWeightsKind;
  25608. },
  25609. enumerable: true,
  25610. configurable: true
  25611. });
  25612. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  25613. get: function () {
  25614. return VertexBuffer._MatricesIndicesExtraKind;
  25615. },
  25616. enumerable: true,
  25617. configurable: true
  25618. });
  25619. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  25620. get: function () {
  25621. return VertexBuffer._MatricesWeightsExtraKind;
  25622. },
  25623. enumerable: true,
  25624. configurable: true
  25625. });
  25626. /**
  25627. * Deduces the stride given a kind.
  25628. * @param kind The kind string to deduce
  25629. * @returns The deduced stride
  25630. */
  25631. VertexBuffer.DeduceStride = function (kind) {
  25632. switch (kind) {
  25633. case VertexBuffer.UVKind:
  25634. case VertexBuffer.UV2Kind:
  25635. case VertexBuffer.UV3Kind:
  25636. case VertexBuffer.UV4Kind:
  25637. case VertexBuffer.UV5Kind:
  25638. case VertexBuffer.UV6Kind:
  25639. return 2;
  25640. case VertexBuffer.NormalKind:
  25641. case VertexBuffer.PositionKind:
  25642. return 3;
  25643. case VertexBuffer.ColorKind:
  25644. case VertexBuffer.MatricesIndicesKind:
  25645. case VertexBuffer.MatricesIndicesExtraKind:
  25646. case VertexBuffer.MatricesWeightsKind:
  25647. case VertexBuffer.MatricesWeightsExtraKind:
  25648. case VertexBuffer.TangentKind:
  25649. return 4;
  25650. default:
  25651. throw new Error("Invalid kind '" + kind + "'");
  25652. }
  25653. };
  25654. // Enums
  25655. VertexBuffer._PositionKind = "position";
  25656. VertexBuffer._NormalKind = "normal";
  25657. VertexBuffer._TangentKind = "tangent";
  25658. VertexBuffer._UVKind = "uv";
  25659. VertexBuffer._UV2Kind = "uv2";
  25660. VertexBuffer._UV3Kind = "uv3";
  25661. VertexBuffer._UV4Kind = "uv4";
  25662. VertexBuffer._UV5Kind = "uv5";
  25663. VertexBuffer._UV6Kind = "uv6";
  25664. VertexBuffer._ColorKind = "color";
  25665. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  25666. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  25667. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  25668. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  25669. return VertexBuffer;
  25670. }());
  25671. BABYLON.VertexBuffer = VertexBuffer;
  25672. })(BABYLON || (BABYLON = {}));
  25673. //# sourceMappingURL=babylon.vertexBuffer.js.map
  25674. var BABYLON;
  25675. (function (BABYLON) {
  25676. /**
  25677. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  25678. */
  25679. var DummyInternalTextureTracker = /** @class */ (function () {
  25680. function DummyInternalTextureTracker() {
  25681. /**
  25682. * Gets or set the previous tracker in the list
  25683. */
  25684. this.previous = null;
  25685. /**
  25686. * Gets or set the next tracker in the list
  25687. */
  25688. this.next = null;
  25689. }
  25690. return DummyInternalTextureTracker;
  25691. }());
  25692. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  25693. })(BABYLON || (BABYLON = {}));
  25694. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  25695. var BABYLON;
  25696. (function (BABYLON) {
  25697. /**
  25698. * Class used to store data associated with WebGL texture data for the engine
  25699. * This class should not be used directly
  25700. */
  25701. var InternalTexture = /** @class */ (function () {
  25702. /**
  25703. * Creates a new InternalTexture
  25704. * @param engine defines the engine to use
  25705. * @param dataSource defines the type of data that will be used
  25706. */
  25707. function InternalTexture(engine, dataSource) {
  25708. /**
  25709. * Observable called when the texture is loaded
  25710. */
  25711. this.onLoadedObservable = new BABYLON.Observable();
  25712. /**
  25713. * Gets or set the previous tracker in the list
  25714. */
  25715. this.previous = null;
  25716. /**
  25717. * Gets or set the next tracker in the list
  25718. */
  25719. this.next = null;
  25720. // Private
  25721. /** @ignore */
  25722. this._initialSlot = -1;
  25723. /** @ignore */
  25724. this._designatedSlot = -1;
  25725. /** @ignore */
  25726. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  25727. /** @ignore */
  25728. this._references = 1;
  25729. this._engine = engine;
  25730. this._dataSource = dataSource;
  25731. this._webGLTexture = engine._createTexture();
  25732. }
  25733. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  25734. /**
  25735. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  25736. */
  25737. get: function () {
  25738. return this._dataSource;
  25739. },
  25740. enumerable: true,
  25741. configurable: true
  25742. });
  25743. /**
  25744. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  25745. */
  25746. InternalTexture.prototype.incrementReferences = function () {
  25747. this._references++;
  25748. };
  25749. /**
  25750. * Change the size of the texture (not the size of the content)
  25751. * @param width defines the new width
  25752. * @param height defines the new height
  25753. * @param depth defines the new depth (1 by default)
  25754. */
  25755. InternalTexture.prototype.updateSize = function (width, height, depth) {
  25756. if (depth === void 0) { depth = 1; }
  25757. this.width = width;
  25758. this.height = height;
  25759. this.depth = depth;
  25760. this.baseWidth = width;
  25761. this.baseHeight = height;
  25762. this.baseDepth = depth;
  25763. this._size = width * height * depth;
  25764. };
  25765. /** @ignore */
  25766. InternalTexture.prototype._rebuild = function () {
  25767. var _this = this;
  25768. var proxy;
  25769. this.isReady = false;
  25770. this._cachedCoordinatesMode = null;
  25771. this._cachedWrapU = null;
  25772. this._cachedWrapV = null;
  25773. this._cachedAnisotropicFilteringLevel = null;
  25774. switch (this._dataSource) {
  25775. case InternalTexture.DATASOURCE_TEMP:
  25776. return;
  25777. case InternalTexture.DATASOURCE_URL:
  25778. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  25779. _this.isReady = true;
  25780. }, null, this._buffer, undefined, this.format);
  25781. proxy._swapAndDie(this);
  25782. return;
  25783. case InternalTexture.DATASOURCE_RAW:
  25784. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25785. proxy._swapAndDie(this);
  25786. this.isReady = true;
  25787. return;
  25788. case InternalTexture.DATASOURCE_RAW3D:
  25789. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25790. proxy._swapAndDie(this);
  25791. this.isReady = true;
  25792. return;
  25793. case InternalTexture.DATASOURCE_DYNAMIC:
  25794. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  25795. proxy._swapAndDie(this);
  25796. // The engine will make sure to update content so no need to flag it as isReady = true
  25797. return;
  25798. case InternalTexture.DATASOURCE_RENDERTARGET:
  25799. var options = new BABYLON.RenderTargetCreationOptions();
  25800. options.generateDepthBuffer = this._generateDepthBuffer;
  25801. options.generateMipMaps = this.generateMipMaps;
  25802. options.generateStencilBuffer = this._generateStencilBuffer;
  25803. options.samplingMode = this.samplingMode;
  25804. options.type = this.type;
  25805. if (this.isCube) {
  25806. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  25807. }
  25808. else {
  25809. var size = {
  25810. width: this.width,
  25811. height: this.height
  25812. };
  25813. proxy = this._engine.createRenderTargetTexture(size, options);
  25814. }
  25815. proxy._swapAndDie(this);
  25816. this.isReady = true;
  25817. return;
  25818. case InternalTexture.DATASOURCE_CUBE:
  25819. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  25820. _this.isReady = true;
  25821. }, null, this.format, this._extension);
  25822. proxy._swapAndDie(this);
  25823. return;
  25824. case InternalTexture.DATASOURCE_CUBERAW:
  25825. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  25826. proxy._swapAndDie(this);
  25827. this.isReady = true;
  25828. return;
  25829. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  25830. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  25831. if (proxy) {
  25832. proxy._swapAndDie(_this);
  25833. }
  25834. _this.isReady = true;
  25835. }, null, this.format, this._extension);
  25836. return;
  25837. }
  25838. };
  25839. InternalTexture.prototype._swapAndDie = function (target) {
  25840. target._webGLTexture = this._webGLTexture;
  25841. if (this._framebuffer) {
  25842. target._framebuffer = this._framebuffer;
  25843. }
  25844. if (this._depthStencilBuffer) {
  25845. target._depthStencilBuffer = this._depthStencilBuffer;
  25846. }
  25847. if (this._lodTextureHigh) {
  25848. if (target._lodTextureHigh) {
  25849. target._lodTextureHigh.dispose();
  25850. }
  25851. target._lodTextureHigh = this._lodTextureHigh;
  25852. }
  25853. if (this._lodTextureMid) {
  25854. if (target._lodTextureMid) {
  25855. target._lodTextureMid.dispose();
  25856. }
  25857. target._lodTextureMid = this._lodTextureMid;
  25858. }
  25859. if (this._lodTextureLow) {
  25860. if (target._lodTextureLow) {
  25861. target._lodTextureLow.dispose();
  25862. }
  25863. target._lodTextureLow = this._lodTextureLow;
  25864. }
  25865. var cache = this._engine.getLoadedTexturesCache();
  25866. var index = cache.indexOf(this);
  25867. if (index !== -1) {
  25868. cache.splice(index, 1);
  25869. }
  25870. };
  25871. /**
  25872. * Dispose the current allocated resources
  25873. */
  25874. InternalTexture.prototype.dispose = function () {
  25875. if (!this._webGLTexture) {
  25876. return;
  25877. }
  25878. this._references--;
  25879. if (this._references === 0) {
  25880. this._engine._releaseTexture(this);
  25881. this._webGLTexture = null;
  25882. this.previous = null;
  25883. this.next = null;
  25884. }
  25885. };
  25886. /**
  25887. * The source of the texture data is unknown
  25888. */
  25889. InternalTexture.DATASOURCE_UNKNOWN = 0;
  25890. /**
  25891. * Texture data comes from an URL
  25892. */
  25893. InternalTexture.DATASOURCE_URL = 1;
  25894. /**
  25895. * Texture data is only used for temporary storage
  25896. */
  25897. InternalTexture.DATASOURCE_TEMP = 2;
  25898. /**
  25899. * Texture data comes from raw data (ArrayBuffer)
  25900. */
  25901. InternalTexture.DATASOURCE_RAW = 3;
  25902. /**
  25903. * Texture content is dynamic (video or dynamic texture)
  25904. */
  25905. InternalTexture.DATASOURCE_DYNAMIC = 4;
  25906. /**
  25907. * Texture content is generated by rendering to it
  25908. */
  25909. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  25910. /**
  25911. * Texture content is part of a multi render target process
  25912. */
  25913. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  25914. /**
  25915. * Texture data comes from a cube data file
  25916. */
  25917. InternalTexture.DATASOURCE_CUBE = 7;
  25918. /**
  25919. * Texture data comes from a raw cube data
  25920. */
  25921. InternalTexture.DATASOURCE_CUBERAW = 8;
  25922. /**
  25923. * Texture data come from a prefiltered cube data file
  25924. */
  25925. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  25926. /**
  25927. * Texture content is raw 3D data
  25928. */
  25929. InternalTexture.DATASOURCE_RAW3D = 10;
  25930. return InternalTexture;
  25931. }());
  25932. BABYLON.InternalTexture = InternalTexture;
  25933. })(BABYLON || (BABYLON = {}));
  25934. //# sourceMappingURL=babylon.internalTexture.js.map
  25935. var BABYLON;
  25936. (function (BABYLON) {
  25937. var BaseTexture = /** @class */ (function () {
  25938. function BaseTexture(scene) {
  25939. this._hasAlpha = false;
  25940. this.getAlphaFromRGB = false;
  25941. this.level = 1;
  25942. this.coordinatesIndex = 0;
  25943. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  25944. /**
  25945. * | Value | Type | Description |
  25946. * | ----- | ------------------ | ----------- |
  25947. * | 0 | CLAMP_ADDRESSMODE | |
  25948. * | 1 | WRAP_ADDRESSMODE | |
  25949. * | 2 | MIRROR_ADDRESSMODE | |
  25950. */
  25951. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  25952. /**
  25953. * | Value | Type | Description |
  25954. * | ----- | ------------------ | ----------- |
  25955. * | 0 | CLAMP_ADDRESSMODE | |
  25956. * | 1 | WRAP_ADDRESSMODE | |
  25957. * | 2 | MIRROR_ADDRESSMODE | |
  25958. */
  25959. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  25960. /**
  25961. * | Value | Type | Description |
  25962. * | ----- | ------------------ | ----------- |
  25963. * | 0 | CLAMP_ADDRESSMODE | |
  25964. * | 1 | WRAP_ADDRESSMODE | |
  25965. * | 2 | MIRROR_ADDRESSMODE | |
  25966. */
  25967. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  25968. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  25969. this.isCube = false;
  25970. this.is3D = false;
  25971. this.gammaSpace = true;
  25972. this.invertZ = false;
  25973. this.lodLevelInAlpha = false;
  25974. this.lodGenerationOffset = 0.0;
  25975. this.lodGenerationScale = 0.8;
  25976. this.isRenderTarget = false;
  25977. this.animations = new Array();
  25978. /**
  25979. * An event triggered when the texture is disposed.
  25980. * @type {BABYLON.Observable}
  25981. */
  25982. this.onDisposeObservable = new BABYLON.Observable();
  25983. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25984. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25985. if (this._scene) {
  25986. this._scene.textures.push(this);
  25987. }
  25988. this._uid = null;
  25989. }
  25990. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  25991. get: function () {
  25992. return this._hasAlpha;
  25993. },
  25994. set: function (value) {
  25995. if (this._hasAlpha === value) {
  25996. return;
  25997. }
  25998. this._hasAlpha = value;
  25999. if (this._scene) {
  26000. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26001. }
  26002. },
  26003. enumerable: true,
  26004. configurable: true
  26005. });
  26006. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26007. get: function () {
  26008. return this._coordinatesMode;
  26009. },
  26010. /**
  26011. * How a texture is mapped.
  26012. *
  26013. * | Value | Type | Description |
  26014. * | ----- | ----------------------------------- | ----------- |
  26015. * | 0 | EXPLICIT_MODE | |
  26016. * | 1 | SPHERICAL_MODE | |
  26017. * | 2 | PLANAR_MODE | |
  26018. * | 3 | CUBIC_MODE | |
  26019. * | 4 | PROJECTION_MODE | |
  26020. * | 5 | SKYBOX_MODE | |
  26021. * | 6 | INVCUBIC_MODE | |
  26022. * | 7 | EQUIRECTANGULAR_MODE | |
  26023. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26024. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26025. */
  26026. set: function (value) {
  26027. if (this._coordinatesMode === value) {
  26028. return;
  26029. }
  26030. this._coordinatesMode = value;
  26031. if (this._scene) {
  26032. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26033. }
  26034. },
  26035. enumerable: true,
  26036. configurable: true
  26037. });
  26038. Object.defineProperty(BaseTexture.prototype, "uid", {
  26039. get: function () {
  26040. if (!this._uid) {
  26041. this._uid = BABYLON.Tools.RandomId();
  26042. }
  26043. return this._uid;
  26044. },
  26045. enumerable: true,
  26046. configurable: true
  26047. });
  26048. BaseTexture.prototype.toString = function () {
  26049. return this.name;
  26050. };
  26051. BaseTexture.prototype.getClassName = function () {
  26052. return "BaseTexture";
  26053. };
  26054. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26055. set: function (callback) {
  26056. if (this._onDisposeObserver) {
  26057. this.onDisposeObservable.remove(this._onDisposeObserver);
  26058. }
  26059. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26060. },
  26061. enumerable: true,
  26062. configurable: true
  26063. });
  26064. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26065. get: function () {
  26066. return true;
  26067. },
  26068. enumerable: true,
  26069. configurable: true
  26070. });
  26071. BaseTexture.prototype.getScene = function () {
  26072. return this._scene;
  26073. };
  26074. BaseTexture.prototype.getTextureMatrix = function () {
  26075. return BABYLON.Matrix.IdentityReadOnly;
  26076. };
  26077. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26078. return BABYLON.Matrix.IdentityReadOnly;
  26079. };
  26080. BaseTexture.prototype.getInternalTexture = function () {
  26081. return this._texture;
  26082. };
  26083. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26084. return !this.isBlocking || this.isReady();
  26085. };
  26086. BaseTexture.prototype.isReady = function () {
  26087. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26088. this.delayLoad();
  26089. return false;
  26090. }
  26091. if (this._texture) {
  26092. return this._texture.isReady;
  26093. }
  26094. return false;
  26095. };
  26096. BaseTexture.prototype.getSize = function () {
  26097. if (this._texture && this._texture.width) {
  26098. return new BABYLON.Size(this._texture.width, this._texture.height);
  26099. }
  26100. if (this._texture && this._texture._size) {
  26101. return new BABYLON.Size(this._texture._size, this._texture._size);
  26102. }
  26103. return BABYLON.Size.Zero();
  26104. };
  26105. BaseTexture.prototype.getBaseSize = function () {
  26106. if (!this.isReady() || !this._texture)
  26107. return BABYLON.Size.Zero();
  26108. if (this._texture._size) {
  26109. return new BABYLON.Size(this._texture._size, this._texture._size);
  26110. }
  26111. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  26112. };
  26113. BaseTexture.prototype.scale = function (ratio) {
  26114. };
  26115. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  26116. get: function () {
  26117. return false;
  26118. },
  26119. enumerable: true,
  26120. configurable: true
  26121. });
  26122. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  26123. if (!this._scene) {
  26124. return null;
  26125. }
  26126. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  26127. for (var index = 0; index < texturesCache.length; index++) {
  26128. var texturesCacheEntry = texturesCache[index];
  26129. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  26130. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  26131. texturesCacheEntry.incrementReferences();
  26132. return texturesCacheEntry;
  26133. }
  26134. }
  26135. }
  26136. return null;
  26137. };
  26138. BaseTexture.prototype._rebuild = function () {
  26139. };
  26140. BaseTexture.prototype.delayLoad = function () {
  26141. };
  26142. BaseTexture.prototype.clone = function () {
  26143. return null;
  26144. };
  26145. Object.defineProperty(BaseTexture.prototype, "textureType", {
  26146. get: function () {
  26147. if (!this._texture) {
  26148. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26149. }
  26150. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  26151. },
  26152. enumerable: true,
  26153. configurable: true
  26154. });
  26155. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  26156. get: function () {
  26157. if (!this._texture) {
  26158. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26159. }
  26160. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  26161. },
  26162. enumerable: true,
  26163. configurable: true
  26164. });
  26165. BaseTexture.prototype.readPixels = function (faceIndex) {
  26166. if (faceIndex === void 0) { faceIndex = 0; }
  26167. if (!this._texture) {
  26168. return null;
  26169. }
  26170. var size = this.getSize();
  26171. var scene = this.getScene();
  26172. if (!scene) {
  26173. return null;
  26174. }
  26175. var engine = scene.getEngine();
  26176. if (this._texture.isCube) {
  26177. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  26178. }
  26179. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  26180. };
  26181. BaseTexture.prototype.releaseInternalTexture = function () {
  26182. if (this._texture) {
  26183. this._texture.dispose();
  26184. this._texture = null;
  26185. }
  26186. };
  26187. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  26188. get: function () {
  26189. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  26190. return null;
  26191. }
  26192. if (!this._texture._sphericalPolynomial) {
  26193. this._texture._sphericalPolynomial =
  26194. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  26195. }
  26196. return this._texture._sphericalPolynomial;
  26197. },
  26198. set: function (value) {
  26199. if (this._texture) {
  26200. this._texture._sphericalPolynomial = value;
  26201. }
  26202. },
  26203. enumerable: true,
  26204. configurable: true
  26205. });
  26206. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  26207. get: function () {
  26208. if (this._texture) {
  26209. return this._texture._lodTextureHigh;
  26210. }
  26211. return null;
  26212. },
  26213. enumerable: true,
  26214. configurable: true
  26215. });
  26216. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  26217. get: function () {
  26218. if (this._texture) {
  26219. return this._texture._lodTextureMid;
  26220. }
  26221. return null;
  26222. },
  26223. enumerable: true,
  26224. configurable: true
  26225. });
  26226. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  26227. get: function () {
  26228. if (this._texture) {
  26229. return this._texture._lodTextureLow;
  26230. }
  26231. return null;
  26232. },
  26233. enumerable: true,
  26234. configurable: true
  26235. });
  26236. BaseTexture.prototype.dispose = function () {
  26237. if (!this._scene) {
  26238. return;
  26239. }
  26240. // Animations
  26241. this._scene.stopAnimation(this);
  26242. // Remove from scene
  26243. this._scene._removePendingData(this);
  26244. var index = this._scene.textures.indexOf(this);
  26245. if (index >= 0) {
  26246. this._scene.textures.splice(index, 1);
  26247. }
  26248. if (this._texture === undefined) {
  26249. return;
  26250. }
  26251. // Release
  26252. this.releaseInternalTexture();
  26253. // Callback
  26254. this.onDisposeObservable.notifyObservers(this);
  26255. this.onDisposeObservable.clear();
  26256. };
  26257. BaseTexture.prototype.serialize = function () {
  26258. if (!this.name) {
  26259. return null;
  26260. }
  26261. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  26262. // Animations
  26263. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  26264. return serializationObject;
  26265. };
  26266. BaseTexture.WhenAllReady = function (textures, callback) {
  26267. var numRemaining = textures.length;
  26268. if (numRemaining === 0) {
  26269. callback();
  26270. return;
  26271. }
  26272. var _loop_1 = function () {
  26273. texture = textures[i];
  26274. if (texture.isReady()) {
  26275. if (--numRemaining === 0) {
  26276. callback();
  26277. }
  26278. }
  26279. else {
  26280. onLoadObservable = texture.onLoadObservable;
  26281. var onLoadCallback_1 = function () {
  26282. onLoadObservable.removeCallback(onLoadCallback_1);
  26283. if (--numRemaining === 0) {
  26284. callback();
  26285. }
  26286. };
  26287. onLoadObservable.add(onLoadCallback_1);
  26288. }
  26289. };
  26290. var texture, onLoadObservable;
  26291. for (var i = 0; i < textures.length; i++) {
  26292. _loop_1();
  26293. }
  26294. };
  26295. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  26296. __decorate([
  26297. BABYLON.serialize()
  26298. ], BaseTexture.prototype, "name", void 0);
  26299. __decorate([
  26300. BABYLON.serialize("hasAlpha")
  26301. ], BaseTexture.prototype, "_hasAlpha", void 0);
  26302. __decorate([
  26303. BABYLON.serialize()
  26304. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  26305. __decorate([
  26306. BABYLON.serialize()
  26307. ], BaseTexture.prototype, "level", void 0);
  26308. __decorate([
  26309. BABYLON.serialize()
  26310. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  26311. __decorate([
  26312. BABYLON.serialize("coordinatesMode")
  26313. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  26314. __decorate([
  26315. BABYLON.serialize()
  26316. ], BaseTexture.prototype, "wrapU", void 0);
  26317. __decorate([
  26318. BABYLON.serialize()
  26319. ], BaseTexture.prototype, "wrapV", void 0);
  26320. __decorate([
  26321. BABYLON.serialize()
  26322. ], BaseTexture.prototype, "wrapR", void 0);
  26323. __decorate([
  26324. BABYLON.serialize()
  26325. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  26326. __decorate([
  26327. BABYLON.serialize()
  26328. ], BaseTexture.prototype, "isCube", void 0);
  26329. __decorate([
  26330. BABYLON.serialize()
  26331. ], BaseTexture.prototype, "is3D", void 0);
  26332. __decorate([
  26333. BABYLON.serialize()
  26334. ], BaseTexture.prototype, "gammaSpace", void 0);
  26335. __decorate([
  26336. BABYLON.serialize()
  26337. ], BaseTexture.prototype, "invertZ", void 0);
  26338. __decorate([
  26339. BABYLON.serialize()
  26340. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  26341. __decorate([
  26342. BABYLON.serialize()
  26343. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  26344. __decorate([
  26345. BABYLON.serialize()
  26346. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  26347. __decorate([
  26348. BABYLON.serialize()
  26349. ], BaseTexture.prototype, "isRenderTarget", void 0);
  26350. return BaseTexture;
  26351. }());
  26352. BABYLON.BaseTexture = BaseTexture;
  26353. })(BABYLON || (BABYLON = {}));
  26354. //# sourceMappingURL=babylon.baseTexture.js.map
  26355. var BABYLON;
  26356. (function (BABYLON) {
  26357. var Texture = /** @class */ (function (_super) {
  26358. __extends(Texture, _super);
  26359. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  26360. if (noMipmap === void 0) { noMipmap = false; }
  26361. if (invertY === void 0) { invertY = true; }
  26362. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26363. if (onLoad === void 0) { onLoad = null; }
  26364. if (onError === void 0) { onError = null; }
  26365. if (buffer === void 0) { buffer = null; }
  26366. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26367. var _this = _super.call(this, scene) || this;
  26368. _this.uOffset = 0;
  26369. _this.vOffset = 0;
  26370. _this.uScale = 1.0;
  26371. _this.vScale = 1.0;
  26372. _this.uAng = 0;
  26373. _this.vAng = 0;
  26374. _this.wAng = 0;
  26375. _this._isBlocking = true;
  26376. _this.name = url || "";
  26377. _this.url = url;
  26378. _this._noMipmap = noMipmap;
  26379. _this._invertY = invertY;
  26380. _this._samplingMode = samplingMode;
  26381. _this._buffer = buffer;
  26382. _this._deleteBuffer = deleteBuffer;
  26383. if (format) {
  26384. _this._format = format;
  26385. }
  26386. scene = _this.getScene();
  26387. if (!scene) {
  26388. return _this;
  26389. }
  26390. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  26391. var load = function () {
  26392. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  26393. _this.onLoadObservable.notifyObservers(_this);
  26394. }
  26395. if (onLoad) {
  26396. onLoad();
  26397. }
  26398. if (!_this.isBlocking && scene) {
  26399. scene.resetCachedMaterial();
  26400. }
  26401. };
  26402. if (!_this.url) {
  26403. _this._delayedOnLoad = load;
  26404. _this._delayedOnError = onError;
  26405. return _this;
  26406. }
  26407. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  26408. if (!_this._texture) {
  26409. if (!scene.useDelayedTextureLoading) {
  26410. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  26411. if (deleteBuffer) {
  26412. delete _this._buffer;
  26413. }
  26414. }
  26415. else {
  26416. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26417. _this._delayedOnLoad = load;
  26418. _this._delayedOnError = onError;
  26419. }
  26420. }
  26421. else {
  26422. if (_this._texture.isReady) {
  26423. BABYLON.Tools.SetImmediate(function () { return load(); });
  26424. }
  26425. else {
  26426. _this._texture.onLoadedObservable.add(load);
  26427. }
  26428. }
  26429. return _this;
  26430. }
  26431. Object.defineProperty(Texture.prototype, "noMipmap", {
  26432. get: function () {
  26433. return this._noMipmap;
  26434. },
  26435. enumerable: true,
  26436. configurable: true
  26437. });
  26438. Object.defineProperty(Texture.prototype, "isBlocking", {
  26439. get: function () {
  26440. return this._isBlocking;
  26441. },
  26442. set: function (value) {
  26443. this._isBlocking = value;
  26444. },
  26445. enumerable: true,
  26446. configurable: true
  26447. });
  26448. Object.defineProperty(Texture.prototype, "samplingMode", {
  26449. get: function () {
  26450. return this._samplingMode;
  26451. },
  26452. enumerable: true,
  26453. configurable: true
  26454. });
  26455. Texture.prototype.updateURL = function (url) {
  26456. this.url = url;
  26457. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  26458. this.delayLoad();
  26459. };
  26460. Texture.prototype.delayLoad = function () {
  26461. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26462. return;
  26463. }
  26464. var scene = this.getScene();
  26465. if (!scene) {
  26466. return;
  26467. }
  26468. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  26469. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  26470. if (!this._texture) {
  26471. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  26472. if (this._deleteBuffer) {
  26473. delete this._buffer;
  26474. }
  26475. }
  26476. else {
  26477. if (this._delayedOnLoad) {
  26478. if (this._texture.isReady) {
  26479. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  26480. }
  26481. else {
  26482. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  26483. }
  26484. }
  26485. }
  26486. this._delayedOnLoad = null;
  26487. this._delayedOnError = null;
  26488. };
  26489. Texture.prototype.updateSamplingMode = function (samplingMode) {
  26490. if (!this._texture) {
  26491. return;
  26492. }
  26493. var scene = this.getScene();
  26494. if (!scene) {
  26495. return;
  26496. }
  26497. this._samplingMode = samplingMode;
  26498. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  26499. };
  26500. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  26501. x *= this.uScale;
  26502. y *= this.vScale;
  26503. x -= 0.5 * this.uScale;
  26504. y -= 0.5 * this.vScale;
  26505. z -= 0.5;
  26506. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  26507. t.x += 0.5 * this.uScale + this.uOffset;
  26508. t.y += 0.5 * this.vScale + this.vOffset;
  26509. t.z += 0.5;
  26510. };
  26511. Texture.prototype.getTextureMatrix = function () {
  26512. var _this = this;
  26513. if (this.uOffset === this._cachedUOffset &&
  26514. this.vOffset === this._cachedVOffset &&
  26515. this.uScale === this._cachedUScale &&
  26516. this.vScale === this._cachedVScale &&
  26517. this.uAng === this._cachedUAng &&
  26518. this.vAng === this._cachedVAng &&
  26519. this.wAng === this._cachedWAng) {
  26520. return this._cachedTextureMatrix;
  26521. }
  26522. this._cachedUOffset = this.uOffset;
  26523. this._cachedVOffset = this.vOffset;
  26524. this._cachedUScale = this.uScale;
  26525. this._cachedVScale = this.vScale;
  26526. this._cachedUAng = this.uAng;
  26527. this._cachedVAng = this.vAng;
  26528. this._cachedWAng = this.wAng;
  26529. if (!this._cachedTextureMatrix) {
  26530. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26531. this._rowGenerationMatrix = new BABYLON.Matrix();
  26532. this._t0 = BABYLON.Vector3.Zero();
  26533. this._t1 = BABYLON.Vector3.Zero();
  26534. this._t2 = BABYLON.Vector3.Zero();
  26535. }
  26536. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  26537. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  26538. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  26539. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  26540. this._t1.subtractInPlace(this._t0);
  26541. this._t2.subtractInPlace(this._t0);
  26542. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26543. this._cachedTextureMatrix.m[0] = this._t1.x;
  26544. this._cachedTextureMatrix.m[1] = this._t1.y;
  26545. this._cachedTextureMatrix.m[2] = this._t1.z;
  26546. this._cachedTextureMatrix.m[4] = this._t2.x;
  26547. this._cachedTextureMatrix.m[5] = this._t2.y;
  26548. this._cachedTextureMatrix.m[6] = this._t2.z;
  26549. this._cachedTextureMatrix.m[8] = this._t0.x;
  26550. this._cachedTextureMatrix.m[9] = this._t0.y;
  26551. this._cachedTextureMatrix.m[10] = this._t0.z;
  26552. var scene = this.getScene();
  26553. if (!scene) {
  26554. return this._cachedTextureMatrix;
  26555. }
  26556. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26557. return mat.hasTexture(_this);
  26558. });
  26559. return this._cachedTextureMatrix;
  26560. };
  26561. Texture.prototype.getReflectionTextureMatrix = function () {
  26562. var _this = this;
  26563. var scene = this.getScene();
  26564. if (!scene) {
  26565. return this._cachedTextureMatrix;
  26566. }
  26567. if (this.uOffset === this._cachedUOffset &&
  26568. this.vOffset === this._cachedVOffset &&
  26569. this.uScale === this._cachedUScale &&
  26570. this.vScale === this._cachedVScale &&
  26571. this.coordinatesMode === this._cachedCoordinatesMode) {
  26572. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  26573. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  26574. return this._cachedTextureMatrix;
  26575. }
  26576. }
  26577. else {
  26578. return this._cachedTextureMatrix;
  26579. }
  26580. }
  26581. if (!this._cachedTextureMatrix) {
  26582. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  26583. }
  26584. if (!this._projectionModeMatrix) {
  26585. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  26586. }
  26587. this._cachedUOffset = this.uOffset;
  26588. this._cachedVOffset = this.vOffset;
  26589. this._cachedUScale = this.uScale;
  26590. this._cachedVScale = this.vScale;
  26591. this._cachedCoordinatesMode = this.coordinatesMode;
  26592. switch (this.coordinatesMode) {
  26593. case Texture.PLANAR_MODE:
  26594. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26595. this._cachedTextureMatrix[0] = this.uScale;
  26596. this._cachedTextureMatrix[5] = this.vScale;
  26597. this._cachedTextureMatrix[12] = this.uOffset;
  26598. this._cachedTextureMatrix[13] = this.vOffset;
  26599. break;
  26600. case Texture.PROJECTION_MODE:
  26601. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  26602. this._projectionModeMatrix.m[0] = 0.5;
  26603. this._projectionModeMatrix.m[5] = -0.5;
  26604. this._projectionModeMatrix.m[10] = 0.0;
  26605. this._projectionModeMatrix.m[12] = 0.5;
  26606. this._projectionModeMatrix.m[13] = 0.5;
  26607. this._projectionModeMatrix.m[14] = 1.0;
  26608. this._projectionModeMatrix.m[15] = 1.0;
  26609. var projectionMatrix = scene.getProjectionMatrix();
  26610. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  26611. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  26612. break;
  26613. default:
  26614. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  26615. break;
  26616. }
  26617. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  26618. return (mat.getActiveTextures().indexOf(_this) !== -1);
  26619. });
  26620. return this._cachedTextureMatrix;
  26621. };
  26622. Texture.prototype.clone = function () {
  26623. var _this = this;
  26624. return BABYLON.SerializationHelper.Clone(function () {
  26625. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  26626. }, this);
  26627. };
  26628. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  26629. get: function () {
  26630. if (!this._onLoadObservable) {
  26631. this._onLoadObservable = new BABYLON.Observable();
  26632. }
  26633. return this._onLoadObservable;
  26634. },
  26635. enumerable: true,
  26636. configurable: true
  26637. });
  26638. Texture.prototype.serialize = function () {
  26639. var serializationObject = _super.prototype.serialize.call(this);
  26640. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  26641. serializationObject.base64String = this._buffer;
  26642. serializationObject.name = serializationObject.name.replace("data:", "");
  26643. }
  26644. return serializationObject;
  26645. };
  26646. Texture.prototype.getClassName = function () {
  26647. return "Texture";
  26648. };
  26649. Texture.prototype.dispose = function () {
  26650. _super.prototype.dispose.call(this);
  26651. if (this.onLoadObservable) {
  26652. this.onLoadObservable.clear();
  26653. this._onLoadObservable = null;
  26654. }
  26655. this._delayedOnLoad = null;
  26656. this._delayedOnError = null;
  26657. };
  26658. // Statics
  26659. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26660. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26661. if (onLoad === void 0) { onLoad = null; }
  26662. if (onError === void 0) { onError = null; }
  26663. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26664. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  26665. };
  26666. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  26667. if (parsedTexture.customType) {
  26668. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  26669. // Update Sampling Mode
  26670. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  26671. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  26672. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  26673. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  26674. }
  26675. }
  26676. return parsedCustomTexture;
  26677. }
  26678. if (parsedTexture.isCube) {
  26679. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  26680. }
  26681. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  26682. return null;
  26683. }
  26684. var texture = BABYLON.SerializationHelper.Parse(function () {
  26685. var generateMipMaps = true;
  26686. if (parsedTexture.noMipmap) {
  26687. generateMipMaps = false;
  26688. }
  26689. if (parsedTexture.mirrorPlane) {
  26690. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26691. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  26692. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  26693. return mirrorTexture;
  26694. }
  26695. else if (parsedTexture.isRenderTarget) {
  26696. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  26697. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  26698. return renderTargetTexture;
  26699. }
  26700. else {
  26701. var texture;
  26702. if (parsedTexture.base64String) {
  26703. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  26704. }
  26705. else {
  26706. texture = new Texture(rootUrl + parsedTexture.name, scene, !generateMipMaps);
  26707. }
  26708. return texture;
  26709. }
  26710. }, parsedTexture, scene);
  26711. // Update Sampling Mode
  26712. if (parsedTexture.samplingMode) {
  26713. var sampling = parsedTexture.samplingMode;
  26714. if (texture._samplingMode !== sampling) {
  26715. texture.updateSamplingMode(sampling);
  26716. }
  26717. }
  26718. // Animations
  26719. if (parsedTexture.animations) {
  26720. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  26721. var parsedAnimation = parsedTexture.animations[animationIndex];
  26722. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  26723. }
  26724. }
  26725. return texture;
  26726. };
  26727. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  26728. if (deleteBuffer === void 0) { deleteBuffer = false; }
  26729. if (noMipmap === void 0) { noMipmap = false; }
  26730. if (invertY === void 0) { invertY = true; }
  26731. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  26732. if (onLoad === void 0) { onLoad = null; }
  26733. if (onError === void 0) { onError = null; }
  26734. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  26735. if (name.substr(0, 5) !== "data:") {
  26736. name = "data:" + name;
  26737. }
  26738. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  26739. };
  26740. // Constants
  26741. Texture.NEAREST_SAMPLINGMODE = 1;
  26742. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  26743. Texture.BILINEAR_SAMPLINGMODE = 2;
  26744. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  26745. Texture.TRILINEAR_SAMPLINGMODE = 3;
  26746. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  26747. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  26748. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  26749. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  26750. Texture.NEAREST_LINEAR = 7;
  26751. Texture.NEAREST_NEAREST = 8;
  26752. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  26753. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  26754. Texture.LINEAR_LINEAR = 11;
  26755. Texture.LINEAR_NEAREST = 12;
  26756. Texture.EXPLICIT_MODE = 0;
  26757. Texture.SPHERICAL_MODE = 1;
  26758. Texture.PLANAR_MODE = 2;
  26759. Texture.CUBIC_MODE = 3;
  26760. Texture.PROJECTION_MODE = 4;
  26761. Texture.SKYBOX_MODE = 5;
  26762. Texture.INVCUBIC_MODE = 6;
  26763. Texture.EQUIRECTANGULAR_MODE = 7;
  26764. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  26765. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  26766. Texture.CLAMP_ADDRESSMODE = 0;
  26767. Texture.WRAP_ADDRESSMODE = 1;
  26768. Texture.MIRROR_ADDRESSMODE = 2;
  26769. __decorate([
  26770. BABYLON.serialize()
  26771. ], Texture.prototype, "url", void 0);
  26772. __decorate([
  26773. BABYLON.serialize()
  26774. ], Texture.prototype, "uOffset", void 0);
  26775. __decorate([
  26776. BABYLON.serialize()
  26777. ], Texture.prototype, "vOffset", void 0);
  26778. __decorate([
  26779. BABYLON.serialize()
  26780. ], Texture.prototype, "uScale", void 0);
  26781. __decorate([
  26782. BABYLON.serialize()
  26783. ], Texture.prototype, "vScale", void 0);
  26784. __decorate([
  26785. BABYLON.serialize()
  26786. ], Texture.prototype, "uAng", void 0);
  26787. __decorate([
  26788. BABYLON.serialize()
  26789. ], Texture.prototype, "vAng", void 0);
  26790. __decorate([
  26791. BABYLON.serialize()
  26792. ], Texture.prototype, "wAng", void 0);
  26793. __decorate([
  26794. BABYLON.serialize()
  26795. ], Texture.prototype, "isBlocking", null);
  26796. return Texture;
  26797. }(BABYLON.BaseTexture));
  26798. BABYLON.Texture = Texture;
  26799. })(BABYLON || (BABYLON = {}));
  26800. //# sourceMappingURL=babylon.texture.js.map
  26801. var BABYLON;
  26802. (function (BABYLON) {
  26803. var _InstancesBatch = /** @class */ (function () {
  26804. function _InstancesBatch() {
  26805. this.mustReturn = false;
  26806. this.visibleInstances = new Array();
  26807. this.renderSelf = new Array();
  26808. }
  26809. return _InstancesBatch;
  26810. }());
  26811. BABYLON._InstancesBatch = _InstancesBatch;
  26812. var Mesh = /** @class */ (function (_super) {
  26813. __extends(Mesh, _super);
  26814. /**
  26815. * @constructor
  26816. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  26817. * @param {Scene} scene The scene to add this mesh to.
  26818. * @param {Node} parent The parent of this mesh, if it has one
  26819. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  26820. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  26821. * When false, achieved by calling a clone(), also passing False.
  26822. * This will make creation of children, recursive.
  26823. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  26824. */
  26825. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  26826. if (scene === void 0) { scene = null; }
  26827. if (parent === void 0) { parent = null; }
  26828. if (source === void 0) { source = null; }
  26829. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  26830. var _this = _super.call(this, name, scene) || this;
  26831. // Events
  26832. /**
  26833. * An event triggered before rendering the mesh
  26834. * @type {BABYLON.Observable}
  26835. */
  26836. _this.onBeforeRenderObservable = new BABYLON.Observable();
  26837. /**
  26838. * An event triggered after rendering the mesh
  26839. * @type {BABYLON.Observable}
  26840. */
  26841. _this.onAfterRenderObservable = new BABYLON.Observable();
  26842. /**
  26843. * An event triggered before drawing the mesh
  26844. * @type {BABYLON.Observable}
  26845. */
  26846. _this.onBeforeDrawObservable = new BABYLON.Observable();
  26847. // Members
  26848. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26849. _this.instances = new Array();
  26850. _this._LODLevels = new Array();
  26851. _this._visibleInstances = {};
  26852. _this._renderIdForInstances = new Array();
  26853. _this._batchCache = new _InstancesBatch();
  26854. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  26855. // Use by builder only to know what orientation were the mesh build in.
  26856. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  26857. _this.overrideMaterialSideOrientation = null;
  26858. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  26859. // Will be used to save a source mesh reference, If any
  26860. _this._source = null;
  26861. scene = _this.getScene();
  26862. if (source) {
  26863. // Source mesh
  26864. _this._source = source;
  26865. // Geometry
  26866. if (source._geometry) {
  26867. source._geometry.applyToMesh(_this);
  26868. }
  26869. // Deep copy
  26870. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  26871. // Metadata
  26872. if (source.metadata && source.metadata.clone) {
  26873. _this.metadata = source.metadata.clone();
  26874. }
  26875. else {
  26876. _this.metadata = source.metadata;
  26877. }
  26878. // Tags
  26879. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  26880. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  26881. }
  26882. // Parent
  26883. _this.parent = source.parent;
  26884. // Pivot
  26885. _this.setPivotMatrix(source.getPivotMatrix());
  26886. _this.id = name + "." + source.id;
  26887. // Material
  26888. _this.material = source.material;
  26889. var index;
  26890. if (!doNotCloneChildren) {
  26891. // Children
  26892. var directDescendants = source.getDescendants(true);
  26893. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  26894. var child = directDescendants[index_1];
  26895. if (child.clone) {
  26896. child.clone(name + "." + child.name, _this);
  26897. }
  26898. }
  26899. }
  26900. // Physics clone
  26901. var physicsEngine = _this.getScene().getPhysicsEngine();
  26902. if (clonePhysicsImpostor && physicsEngine) {
  26903. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  26904. if (impostor) {
  26905. _this.physicsImpostor = impostor.clone(_this);
  26906. }
  26907. }
  26908. // Particles
  26909. for (index = 0; index < scene.particleSystems.length; index++) {
  26910. var system = scene.particleSystems[index];
  26911. if (system.emitter === source) {
  26912. system.clone(system.name, _this);
  26913. }
  26914. }
  26915. _this.computeWorldMatrix(true);
  26916. }
  26917. // Parent
  26918. if (parent !== null) {
  26919. _this.parent = parent;
  26920. }
  26921. return _this;
  26922. }
  26923. Object.defineProperty(Mesh, "FRONTSIDE", {
  26924. /**
  26925. * Mesh side orientation : usually the external or front surface
  26926. */
  26927. get: function () {
  26928. return Mesh._FRONTSIDE;
  26929. },
  26930. enumerable: true,
  26931. configurable: true
  26932. });
  26933. Object.defineProperty(Mesh, "BACKSIDE", {
  26934. /**
  26935. * Mesh side orientation : usually the internal or back surface
  26936. */
  26937. get: function () {
  26938. return Mesh._BACKSIDE;
  26939. },
  26940. enumerable: true,
  26941. configurable: true
  26942. });
  26943. Object.defineProperty(Mesh, "DOUBLESIDE", {
  26944. /**
  26945. * Mesh side orientation : both internal and external or front and back surfaces
  26946. */
  26947. get: function () {
  26948. return Mesh._DOUBLESIDE;
  26949. },
  26950. enumerable: true,
  26951. configurable: true
  26952. });
  26953. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  26954. /**
  26955. * Mesh side orientation : by default, `FRONTSIDE`
  26956. */
  26957. get: function () {
  26958. return Mesh._DEFAULTSIDE;
  26959. },
  26960. enumerable: true,
  26961. configurable: true
  26962. });
  26963. Object.defineProperty(Mesh, "NO_CAP", {
  26964. /**
  26965. * Mesh cap setting : no cap
  26966. */
  26967. get: function () {
  26968. return Mesh._NO_CAP;
  26969. },
  26970. enumerable: true,
  26971. configurable: true
  26972. });
  26973. Object.defineProperty(Mesh, "CAP_START", {
  26974. /**
  26975. * Mesh cap setting : one cap at the beginning of the mesh
  26976. */
  26977. get: function () {
  26978. return Mesh._CAP_START;
  26979. },
  26980. enumerable: true,
  26981. configurable: true
  26982. });
  26983. Object.defineProperty(Mesh, "CAP_END", {
  26984. /**
  26985. * Mesh cap setting : one cap at the end of the mesh
  26986. */
  26987. get: function () {
  26988. return Mesh._CAP_END;
  26989. },
  26990. enumerable: true,
  26991. configurable: true
  26992. });
  26993. Object.defineProperty(Mesh, "CAP_ALL", {
  26994. /**
  26995. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  26996. */
  26997. get: function () {
  26998. return Mesh._CAP_ALL;
  26999. },
  27000. enumerable: true,
  27001. configurable: true
  27002. });
  27003. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27004. set: function (callback) {
  27005. if (this._onBeforeDrawObserver) {
  27006. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27007. }
  27008. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27009. },
  27010. enumerable: true,
  27011. configurable: true
  27012. });
  27013. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27014. get: function () {
  27015. return this._morphTargetManager;
  27016. },
  27017. set: function (value) {
  27018. if (this._morphTargetManager === value) {
  27019. return;
  27020. }
  27021. this._morphTargetManager = value;
  27022. this._syncGeometryWithMorphTargetManager();
  27023. },
  27024. enumerable: true,
  27025. configurable: true
  27026. });
  27027. Object.defineProperty(Mesh.prototype, "source", {
  27028. get: function () {
  27029. return this._source;
  27030. },
  27031. enumerable: true,
  27032. configurable: true
  27033. });
  27034. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27035. get: function () {
  27036. return this._unIndexed;
  27037. },
  27038. set: function (value) {
  27039. if (this._unIndexed !== value) {
  27040. this._unIndexed = value;
  27041. this._markSubMeshesAsAttributesDirty();
  27042. }
  27043. },
  27044. enumerable: true,
  27045. configurable: true
  27046. });
  27047. // Methods
  27048. /**
  27049. * Returns the string "Mesh".
  27050. */
  27051. Mesh.prototype.getClassName = function () {
  27052. return "Mesh";
  27053. };
  27054. /**
  27055. * Returns a string.
  27056. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27057. */
  27058. Mesh.prototype.toString = function (fullDetails) {
  27059. var ret = _super.prototype.toString.call(this, fullDetails);
  27060. ret += ", n vertices: " + this.getTotalVertices();
  27061. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27062. if (this.animations) {
  27063. for (var i = 0; i < this.animations.length; i++) {
  27064. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27065. }
  27066. }
  27067. if (fullDetails) {
  27068. if (this._geometry) {
  27069. var ib = this.getIndices();
  27070. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27071. if (vb && ib) {
  27072. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27073. }
  27074. }
  27075. else {
  27076. ret += ", flat shading: UNKNOWN";
  27077. }
  27078. }
  27079. return ret;
  27080. };
  27081. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27082. /**
  27083. * True if the mesh has some Levels Of Details (LOD).
  27084. * Returns a boolean.
  27085. */
  27086. get: function () {
  27087. return this._LODLevels.length > 0;
  27088. },
  27089. enumerable: true,
  27090. configurable: true
  27091. });
  27092. /**
  27093. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  27094. * @returns an array of {BABYLON.MeshLODLevel}
  27095. */
  27096. Mesh.prototype.getLODLevels = function () {
  27097. return this._LODLevels;
  27098. };
  27099. Mesh.prototype._sortLODLevels = function () {
  27100. this._LODLevels.sort(function (a, b) {
  27101. if (a.distance < b.distance) {
  27102. return 1;
  27103. }
  27104. if (a.distance > b.distance) {
  27105. return -1;
  27106. }
  27107. return 0;
  27108. });
  27109. };
  27110. /**
  27111. * Add a mesh as LOD level triggered at the given distance.
  27112. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27113. * @param {number} distance The distance from the center of the object to show this level
  27114. * @param {Mesh} mesh The mesh to be added as LOD level
  27115. * @return {Mesh} This mesh (for chaining)
  27116. */
  27117. Mesh.prototype.addLODLevel = function (distance, mesh) {
  27118. if (mesh && mesh._masterMesh) {
  27119. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  27120. return this;
  27121. }
  27122. var level = new BABYLON.MeshLODLevel(distance, mesh);
  27123. this._LODLevels.push(level);
  27124. if (mesh) {
  27125. mesh._masterMesh = this;
  27126. }
  27127. this._sortLODLevels();
  27128. return this;
  27129. };
  27130. /**
  27131. * Returns the LOD level mesh at the passed distance or null if not found.
  27132. * It is related to the method `addLODLevel(distance, mesh)`.
  27133. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27134. * Returns an object Mesh or `null`.
  27135. */
  27136. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  27137. for (var index = 0; index < this._LODLevels.length; index++) {
  27138. var level = this._LODLevels[index];
  27139. if (level.distance === distance) {
  27140. return level.mesh;
  27141. }
  27142. }
  27143. return null;
  27144. };
  27145. /**
  27146. * Remove a mesh from the LOD array
  27147. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27148. * @param {Mesh} mesh The mesh to be removed.
  27149. * @return {Mesh} This mesh (for chaining)
  27150. */
  27151. Mesh.prototype.removeLODLevel = function (mesh) {
  27152. for (var index = 0; index < this._LODLevels.length; index++) {
  27153. if (this._LODLevels[index].mesh === mesh) {
  27154. this._LODLevels.splice(index, 1);
  27155. if (mesh) {
  27156. mesh._masterMesh = null;
  27157. }
  27158. }
  27159. }
  27160. this._sortLODLevels();
  27161. return this;
  27162. };
  27163. /**
  27164. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  27165. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  27166. */
  27167. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  27168. if (!this._LODLevels || this._LODLevels.length === 0) {
  27169. return this;
  27170. }
  27171. var bSphere;
  27172. if (boundingSphere) {
  27173. bSphere = boundingSphere;
  27174. }
  27175. else {
  27176. var boundingInfo = this.getBoundingInfo();
  27177. bSphere = boundingInfo.boundingSphere;
  27178. }
  27179. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  27180. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  27181. if (this.onLODLevelSelection) {
  27182. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  27183. }
  27184. return this;
  27185. }
  27186. for (var index = 0; index < this._LODLevels.length; index++) {
  27187. var level = this._LODLevels[index];
  27188. if (level.distance < distanceToCamera) {
  27189. if (level.mesh) {
  27190. level.mesh._preActivate();
  27191. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  27192. }
  27193. if (this.onLODLevelSelection) {
  27194. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  27195. }
  27196. return level.mesh;
  27197. }
  27198. }
  27199. if (this.onLODLevelSelection) {
  27200. this.onLODLevelSelection(distanceToCamera, this, this);
  27201. }
  27202. return this;
  27203. };
  27204. Object.defineProperty(Mesh.prototype, "geometry", {
  27205. /**
  27206. * Returns the mesh internal Geometry object.
  27207. */
  27208. get: function () {
  27209. return this._geometry;
  27210. },
  27211. enumerable: true,
  27212. configurable: true
  27213. });
  27214. /**
  27215. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  27216. */
  27217. Mesh.prototype.getTotalVertices = function () {
  27218. if (this._geometry === null || this._geometry === undefined) {
  27219. return 0;
  27220. }
  27221. return this._geometry.getTotalVertices();
  27222. };
  27223. /**
  27224. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  27225. * 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.
  27226. * You can force the copy with forceCopy === true
  27227. * Returns null if the mesh has no geometry or no vertex buffer.
  27228. * Possible `kind` values :
  27229. * - BABYLON.VertexBuffer.PositionKind
  27230. * - BABYLON.VertexBuffer.UVKind
  27231. * - BABYLON.VertexBuffer.UV2Kind
  27232. * - BABYLON.VertexBuffer.UV3Kind
  27233. * - BABYLON.VertexBuffer.UV4Kind
  27234. * - BABYLON.VertexBuffer.UV5Kind
  27235. * - BABYLON.VertexBuffer.UV6Kind
  27236. * - BABYLON.VertexBuffer.ColorKind
  27237. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27238. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27239. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27240. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27241. */
  27242. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  27243. if (!this._geometry) {
  27244. return null;
  27245. }
  27246. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  27247. };
  27248. /**
  27249. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  27250. * Returns `null` if the mesh has no geometry.
  27251. * Possible `kind` values :
  27252. * - BABYLON.VertexBuffer.PositionKind
  27253. * - BABYLON.VertexBuffer.UVKind
  27254. * - BABYLON.VertexBuffer.UV2Kind
  27255. * - BABYLON.VertexBuffer.UV3Kind
  27256. * - BABYLON.VertexBuffer.UV4Kind
  27257. * - BABYLON.VertexBuffer.UV5Kind
  27258. * - BABYLON.VertexBuffer.UV6Kind
  27259. * - BABYLON.VertexBuffer.ColorKind
  27260. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27261. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27262. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27263. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27264. */
  27265. Mesh.prototype.getVertexBuffer = function (kind) {
  27266. if (!this._geometry) {
  27267. return null;
  27268. }
  27269. return this._geometry.getVertexBuffer(kind);
  27270. };
  27271. /**
  27272. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  27273. * Possible `kind` values :
  27274. * - BABYLON.VertexBuffer.PositionKind
  27275. * - BABYLON.VertexBuffer.UVKind
  27276. * - BABYLON.VertexBuffer.UV2Kind
  27277. * - BABYLON.VertexBuffer.UV3Kind
  27278. * - BABYLON.VertexBuffer.UV4Kind
  27279. * - BABYLON.VertexBuffer.UV5Kind
  27280. * - BABYLON.VertexBuffer.UV6Kind
  27281. * - BABYLON.VertexBuffer.ColorKind
  27282. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27283. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27284. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27285. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27286. */
  27287. Mesh.prototype.isVerticesDataPresent = function (kind) {
  27288. if (!this._geometry) {
  27289. if (this._delayInfo) {
  27290. return this._delayInfo.indexOf(kind) !== -1;
  27291. }
  27292. return false;
  27293. }
  27294. return this._geometry.isVerticesDataPresent(kind);
  27295. };
  27296. /**
  27297. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  27298. * Possible `kind` values :
  27299. * - BABYLON.VertexBuffer.PositionKind
  27300. * - BABYLON.VertexBuffer.UVKind
  27301. * - BABYLON.VertexBuffer.UV2Kind
  27302. * - BABYLON.VertexBuffer.UV3Kind
  27303. * - BABYLON.VertexBuffer.UV4Kind
  27304. * - BABYLON.VertexBuffer.UV5Kind
  27305. * - BABYLON.VertexBuffer.UV6Kind
  27306. * - BABYLON.VertexBuffer.ColorKind
  27307. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27308. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27309. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27310. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27311. */
  27312. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  27313. if (!this._geometry) {
  27314. if (this._delayInfo) {
  27315. return this._delayInfo.indexOf(kind) !== -1;
  27316. }
  27317. return false;
  27318. }
  27319. return this._geometry.isVertexBufferUpdatable(kind);
  27320. };
  27321. /**
  27322. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  27323. * Possible `kind` values :
  27324. * - BABYLON.VertexBuffer.PositionKind
  27325. * - BABYLON.VertexBuffer.UVKind
  27326. * - BABYLON.VertexBuffer.UV2Kind
  27327. * - BABYLON.VertexBuffer.UV3Kind
  27328. * - BABYLON.VertexBuffer.UV4Kind
  27329. * - BABYLON.VertexBuffer.UV5Kind
  27330. * - BABYLON.VertexBuffer.UV6Kind
  27331. * - BABYLON.VertexBuffer.ColorKind
  27332. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27333. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27334. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27335. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27336. */
  27337. Mesh.prototype.getVerticesDataKinds = function () {
  27338. if (!this._geometry) {
  27339. var result = new Array();
  27340. if (this._delayInfo) {
  27341. this._delayInfo.forEach(function (kind, index, array) {
  27342. result.push(kind);
  27343. });
  27344. }
  27345. return result;
  27346. }
  27347. return this._geometry.getVerticesDataKinds();
  27348. };
  27349. /**
  27350. * Returns a positive integer : the total number of indices in this mesh geometry.
  27351. * Returns zero if the mesh has no geometry.
  27352. */
  27353. Mesh.prototype.getTotalIndices = function () {
  27354. if (!this._geometry) {
  27355. return 0;
  27356. }
  27357. return this._geometry.getTotalIndices();
  27358. };
  27359. /**
  27360. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  27361. * 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.
  27362. * Returns an empty array if the mesh has no geometry.
  27363. */
  27364. Mesh.prototype.getIndices = function (copyWhenShared) {
  27365. if (!this._geometry) {
  27366. return [];
  27367. }
  27368. return this._geometry.getIndices(copyWhenShared);
  27369. };
  27370. Object.defineProperty(Mesh.prototype, "isBlocked", {
  27371. get: function () {
  27372. return this._masterMesh !== null && this._masterMesh !== undefined;
  27373. },
  27374. enumerable: true,
  27375. configurable: true
  27376. });
  27377. /**
  27378. * Determine if the current mesh is ready to be rendered
  27379. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  27380. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  27381. * @returns true if all associated assets are ready (material, textures, shaders)
  27382. */
  27383. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  27384. if (completeCheck === void 0) { completeCheck = false; }
  27385. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  27386. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27387. return false;
  27388. }
  27389. if (!_super.prototype.isReady.call(this, completeCheck)) {
  27390. return false;
  27391. }
  27392. if (!this.subMeshes || this.subMeshes.length === 0) {
  27393. return true;
  27394. }
  27395. if (!completeCheck) {
  27396. return true;
  27397. }
  27398. var engine = this.getEngine();
  27399. var scene = this.getScene();
  27400. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  27401. this.computeWorldMatrix();
  27402. var mat = this.material || scene.defaultMaterial;
  27403. if (mat) {
  27404. if (mat.storeEffectOnSubMeshes) {
  27405. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27406. var subMesh = _a[_i];
  27407. var effectiveMaterial = subMesh.getMaterial();
  27408. if (effectiveMaterial) {
  27409. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  27410. return false;
  27411. }
  27412. }
  27413. }
  27414. }
  27415. else {
  27416. if (!mat.isReady(this, hardwareInstancedRendering)) {
  27417. return false;
  27418. }
  27419. }
  27420. }
  27421. // Shadows
  27422. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  27423. var light = _c[_b];
  27424. var generator = light.getShadowGenerator();
  27425. if (generator) {
  27426. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  27427. var subMesh = _e[_d];
  27428. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  27429. return false;
  27430. }
  27431. }
  27432. }
  27433. }
  27434. // LOD
  27435. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  27436. var lod = _g[_f];
  27437. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  27438. return false;
  27439. }
  27440. }
  27441. return true;
  27442. };
  27443. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  27444. /**
  27445. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  27446. * This property is pertinent only for updatable parametric shapes.
  27447. */
  27448. get: function () {
  27449. return this._areNormalsFrozen;
  27450. },
  27451. enumerable: true,
  27452. configurable: true
  27453. });
  27454. /**
  27455. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27456. * It has no effect at all on other shapes.
  27457. * It prevents the mesh normals from being recomputed on next `positions` array update.
  27458. * Returns the Mesh.
  27459. */
  27460. Mesh.prototype.freezeNormals = function () {
  27461. this._areNormalsFrozen = true;
  27462. return this;
  27463. };
  27464. /**
  27465. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  27466. * It has no effect at all on other shapes.
  27467. * It reactivates the mesh normals computation if it was previously frozen.
  27468. * Returns the Mesh.
  27469. */
  27470. Mesh.prototype.unfreezeNormals = function () {
  27471. this._areNormalsFrozen = false;
  27472. return this;
  27473. };
  27474. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  27475. /**
  27476. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  27477. */
  27478. set: function (count) {
  27479. this._overridenInstanceCount = count;
  27480. },
  27481. enumerable: true,
  27482. configurable: true
  27483. });
  27484. // Methods
  27485. Mesh.prototype._preActivate = function () {
  27486. var sceneRenderId = this.getScene().getRenderId();
  27487. if (this._preActivateId === sceneRenderId) {
  27488. return this;
  27489. }
  27490. this._preActivateId = sceneRenderId;
  27491. this._visibleInstances = null;
  27492. return this;
  27493. };
  27494. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  27495. if (this._visibleInstances) {
  27496. this._visibleInstances.intermediateDefaultRenderId = renderId;
  27497. }
  27498. return this;
  27499. };
  27500. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  27501. if (!this._visibleInstances) {
  27502. this._visibleInstances = {};
  27503. this._visibleInstances.defaultRenderId = renderId;
  27504. this._visibleInstances.selfDefaultRenderId = this._renderId;
  27505. }
  27506. if (!this._visibleInstances[renderId]) {
  27507. this._visibleInstances[renderId] = new Array();
  27508. }
  27509. this._visibleInstances[renderId].push(instance);
  27510. return this;
  27511. };
  27512. /**
  27513. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  27514. * This means the mesh underlying bounding box and sphere are recomputed.
  27515. * Returns the Mesh.
  27516. */
  27517. Mesh.prototype.refreshBoundingInfo = function () {
  27518. return this._refreshBoundingInfo(false);
  27519. };
  27520. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  27521. if (this._boundingInfo && this._boundingInfo.isLocked) {
  27522. return this;
  27523. }
  27524. var data = this._getPositionData(applySkeleton);
  27525. if (data) {
  27526. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  27527. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27528. }
  27529. if (this.subMeshes) {
  27530. for (var index = 0; index < this.subMeshes.length; index++) {
  27531. this.subMeshes[index].refreshBoundingInfo();
  27532. }
  27533. }
  27534. this._updateBoundingInfo();
  27535. return this;
  27536. };
  27537. Mesh.prototype._getPositionData = function (applySkeleton) {
  27538. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27539. if (data && applySkeleton && this.skeleton) {
  27540. data = BABYLON.Tools.Slice(data);
  27541. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  27542. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  27543. if (matricesWeightsData && matricesIndicesData) {
  27544. var needExtras = this.numBoneInfluencers > 4;
  27545. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  27546. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  27547. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  27548. var tempVector = BABYLON.Tmp.Vector3[0];
  27549. var finalMatrix = BABYLON.Tmp.Matrix[0];
  27550. var tempMatrix = BABYLON.Tmp.Matrix[1];
  27551. var matWeightIdx = 0;
  27552. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  27553. finalMatrix.reset();
  27554. var inf;
  27555. var weight;
  27556. for (inf = 0; inf < 4; inf++) {
  27557. weight = matricesWeightsData[matWeightIdx + inf];
  27558. if (weight <= 0)
  27559. break;
  27560. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27561. finalMatrix.addToSelf(tempMatrix);
  27562. }
  27563. if (needExtras) {
  27564. for (inf = 0; inf < 4; inf++) {
  27565. weight = matricesWeightsExtraData[matWeightIdx + inf];
  27566. if (weight <= 0)
  27567. break;
  27568. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  27569. finalMatrix.addToSelf(tempMatrix);
  27570. }
  27571. }
  27572. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  27573. tempVector.toArray(data, index);
  27574. }
  27575. }
  27576. }
  27577. return data;
  27578. };
  27579. Mesh.prototype._createGlobalSubMesh = function (force) {
  27580. var totalVertices = this.getTotalVertices();
  27581. if (!totalVertices || !this.getIndices()) {
  27582. return null;
  27583. }
  27584. // Check if we need to recreate the submeshes
  27585. if (this.subMeshes && this.subMeshes.length > 0) {
  27586. var ib = this.getIndices();
  27587. if (!ib) {
  27588. return null;
  27589. }
  27590. var totalIndices = ib.length;
  27591. var needToRecreate = false;
  27592. if (force) {
  27593. needToRecreate = true;
  27594. }
  27595. else {
  27596. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  27597. var submesh = _a[_i];
  27598. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  27599. needToRecreate = true;
  27600. break;
  27601. }
  27602. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  27603. needToRecreate = true;
  27604. break;
  27605. }
  27606. }
  27607. }
  27608. if (!needToRecreate) {
  27609. return this.subMeshes[0];
  27610. }
  27611. }
  27612. this.releaseSubMeshes();
  27613. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  27614. };
  27615. Mesh.prototype.subdivide = function (count) {
  27616. if (count < 1) {
  27617. return;
  27618. }
  27619. var totalIndices = this.getTotalIndices();
  27620. var subdivisionSize = (totalIndices / count) | 0;
  27621. var offset = 0;
  27622. // Ensure that subdivisionSize is a multiple of 3
  27623. while (subdivisionSize % 3 !== 0) {
  27624. subdivisionSize++;
  27625. }
  27626. this.releaseSubMeshes();
  27627. for (var index = 0; index < count; index++) {
  27628. if (offset >= totalIndices) {
  27629. break;
  27630. }
  27631. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  27632. offset += subdivisionSize;
  27633. }
  27634. this.synchronizeInstances();
  27635. };
  27636. /**
  27637. * Sets the vertex data of the mesh geometry for the requested `kind`.
  27638. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  27639. * The `data` are either a numeric array either a Float32Array.
  27640. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  27641. * 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).
  27642. * Note that a new underlying VertexBuffer object is created each call.
  27643. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  27644. *
  27645. * Possible `kind` values :
  27646. * - BABYLON.VertexBuffer.PositionKind
  27647. * - BABYLON.VertexBuffer.UVKind
  27648. * - BABYLON.VertexBuffer.UV2Kind
  27649. * - BABYLON.VertexBuffer.UV3Kind
  27650. * - BABYLON.VertexBuffer.UV4Kind
  27651. * - BABYLON.VertexBuffer.UV5Kind
  27652. * - BABYLON.VertexBuffer.UV6Kind
  27653. * - BABYLON.VertexBuffer.ColorKind
  27654. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27655. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27656. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27657. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27658. *
  27659. * Returns the Mesh.
  27660. */
  27661. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27662. if (updatable === void 0) { updatable = false; }
  27663. if (!this._geometry) {
  27664. var vertexData = new BABYLON.VertexData();
  27665. vertexData.set(data, kind);
  27666. var scene = this.getScene();
  27667. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27668. }
  27669. else {
  27670. this._geometry.setVerticesData(kind, data, updatable, stride);
  27671. }
  27672. return this;
  27673. };
  27674. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  27675. if (updatable === void 0) { updatable = true; }
  27676. var vb = this.getVertexBuffer(kind);
  27677. if (!vb || vb.isUpdatable() === updatable) {
  27678. return;
  27679. }
  27680. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  27681. };
  27682. /**
  27683. * Sets the mesh VertexBuffer.
  27684. * Returns the Mesh.
  27685. */
  27686. Mesh.prototype.setVerticesBuffer = function (buffer) {
  27687. if (!this._geometry) {
  27688. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  27689. }
  27690. this._geometry.setVerticesBuffer(buffer);
  27691. return this;
  27692. };
  27693. /**
  27694. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  27695. * If the mesh has no geometry, it is simply returned as it is.
  27696. * The `data` are either a numeric array either a Float32Array.
  27697. * No new underlying VertexBuffer object is created.
  27698. * 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.
  27699. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  27700. *
  27701. * Possible `kind` values :
  27702. * - BABYLON.VertexBuffer.PositionKind
  27703. * - BABYLON.VertexBuffer.UVKind
  27704. * - BABYLON.VertexBuffer.UV2Kind
  27705. * - BABYLON.VertexBuffer.UV3Kind
  27706. * - BABYLON.VertexBuffer.UV4Kind
  27707. * - BABYLON.VertexBuffer.UV5Kind
  27708. * - BABYLON.VertexBuffer.UV6Kind
  27709. * - BABYLON.VertexBuffer.ColorKind
  27710. * - BABYLON.VertexBuffer.MatricesIndicesKind
  27711. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  27712. * - BABYLON.VertexBuffer.MatricesWeightsKind
  27713. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  27714. *
  27715. * Returns the Mesh.
  27716. */
  27717. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  27718. if (!this._geometry) {
  27719. return this;
  27720. }
  27721. if (!makeItUnique) {
  27722. this._geometry.updateVerticesData(kind, data, updateExtends);
  27723. }
  27724. else {
  27725. this.makeGeometryUnique();
  27726. this.updateVerticesData(kind, data, updateExtends, false);
  27727. }
  27728. return this;
  27729. };
  27730. /**
  27731. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  27732. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  27733. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  27734. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  27735. * Returns the Mesh.
  27736. */
  27737. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  27738. if (computeNormals === void 0) { computeNormals = true; }
  27739. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27740. if (!positions) {
  27741. return this;
  27742. }
  27743. positionFunction(positions);
  27744. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  27745. if (computeNormals) {
  27746. var indices = this.getIndices();
  27747. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27748. if (!normals) {
  27749. return this;
  27750. }
  27751. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  27752. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  27753. }
  27754. return this;
  27755. };
  27756. /**
  27757. * Creates a un-shared specific occurence of the geometry for the mesh.
  27758. * Returns the Mesh.
  27759. */
  27760. Mesh.prototype.makeGeometryUnique = function () {
  27761. if (!this._geometry) {
  27762. return this;
  27763. }
  27764. var oldGeometry = this._geometry;
  27765. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  27766. oldGeometry.releaseForMesh(this, true);
  27767. geometry.applyToMesh(this);
  27768. return this;
  27769. };
  27770. /**
  27771. * Sets the mesh indices.
  27772. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  27773. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  27774. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  27775. * This method creates a new index buffer each call.
  27776. * Returns the Mesh.
  27777. */
  27778. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  27779. if (totalVertices === void 0) { totalVertices = null; }
  27780. if (updatable === void 0) { updatable = false; }
  27781. if (!this._geometry) {
  27782. var vertexData = new BABYLON.VertexData();
  27783. vertexData.indices = indices;
  27784. var scene = this.getScene();
  27785. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  27786. }
  27787. else {
  27788. this._geometry.setIndices(indices, totalVertices, updatable);
  27789. }
  27790. return this;
  27791. };
  27792. /**
  27793. * Update the current index buffer
  27794. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  27795. * Returns the Mesh.
  27796. */
  27797. Mesh.prototype.updateIndices = function (indices, offset) {
  27798. if (!this._geometry) {
  27799. return this;
  27800. }
  27801. this._geometry.updateIndices(indices, offset);
  27802. return this;
  27803. };
  27804. /**
  27805. * Invert the geometry to move from a right handed system to a left handed one.
  27806. * Returns the Mesh.
  27807. */
  27808. Mesh.prototype.toLeftHanded = function () {
  27809. if (!this._geometry) {
  27810. return this;
  27811. }
  27812. this._geometry.toLeftHanded();
  27813. return this;
  27814. };
  27815. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  27816. if (!this._geometry) {
  27817. return this;
  27818. }
  27819. var engine = this.getScene().getEngine();
  27820. // Wireframe
  27821. var indexToBind;
  27822. if (this._unIndexed) {
  27823. indexToBind = null;
  27824. }
  27825. else {
  27826. switch (fillMode) {
  27827. case BABYLON.Material.PointFillMode:
  27828. indexToBind = null;
  27829. break;
  27830. case BABYLON.Material.WireFrameFillMode:
  27831. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  27832. break;
  27833. default:
  27834. case BABYLON.Material.TriangleFillMode:
  27835. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  27836. break;
  27837. }
  27838. }
  27839. // VBOs
  27840. this._geometry._bind(effect, indexToBind);
  27841. return this;
  27842. };
  27843. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  27844. if (alternate === void 0) { alternate = false; }
  27845. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27846. return this;
  27847. }
  27848. this.onBeforeDrawObservable.notifyObservers(this);
  27849. var scene = this.getScene();
  27850. var engine = scene.getEngine();
  27851. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  27852. // or triangles as points
  27853. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  27854. }
  27855. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  27856. // Triangles as wireframe
  27857. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  27858. }
  27859. else {
  27860. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  27861. }
  27862. if (scene._isAlternateRenderingEnabled && !alternate) {
  27863. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  27864. if (!effect || !scene.activeCamera) {
  27865. return this;
  27866. }
  27867. scene._switchToAlternateCameraConfiguration(true);
  27868. this._effectiveMaterial.bindView(effect);
  27869. this._effectiveMaterial.bindViewProjection(effect);
  27870. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  27871. this._draw(subMesh, fillMode, instancesCount, true);
  27872. engine.setViewport(scene.activeCamera.viewport);
  27873. scene._switchToAlternateCameraConfiguration(false);
  27874. this._effectiveMaterial.bindView(effect);
  27875. this._effectiveMaterial.bindViewProjection(effect);
  27876. }
  27877. return this;
  27878. };
  27879. /**
  27880. * Registers for this mesh a javascript function called just before the rendering process.
  27881. * This function is passed the current mesh.
  27882. * Return the Mesh.
  27883. */
  27884. Mesh.prototype.registerBeforeRender = function (func) {
  27885. this.onBeforeRenderObservable.add(func);
  27886. return this;
  27887. };
  27888. /**
  27889. * Disposes a previously registered javascript function called before the rendering.
  27890. * This function is passed the current mesh.
  27891. * Returns the Mesh.
  27892. */
  27893. Mesh.prototype.unregisterBeforeRender = function (func) {
  27894. this.onBeforeRenderObservable.removeCallback(func);
  27895. return this;
  27896. };
  27897. /**
  27898. * Registers for this mesh a javascript function called just after the rendering is complete.
  27899. * This function is passed the current mesh.
  27900. * Returns the Mesh.
  27901. */
  27902. Mesh.prototype.registerAfterRender = function (func) {
  27903. this.onAfterRenderObservable.add(func);
  27904. return this;
  27905. };
  27906. /**
  27907. * Disposes a previously registered javascript function called after the rendering.
  27908. * This function is passed the current mesh.
  27909. * Return the Mesh.
  27910. */
  27911. Mesh.prototype.unregisterAfterRender = function (func) {
  27912. this.onAfterRenderObservable.removeCallback(func);
  27913. return this;
  27914. };
  27915. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  27916. var scene = this.getScene();
  27917. this._batchCache.mustReturn = false;
  27918. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  27919. this._batchCache.visibleInstances[subMeshId] = null;
  27920. if (this._visibleInstances) {
  27921. var currentRenderId = scene.getRenderId();
  27922. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  27923. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  27924. var selfRenderId = this._renderId;
  27925. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  27926. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  27927. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  27928. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  27929. }
  27930. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  27931. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  27932. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  27933. this._batchCache.mustReturn = true;
  27934. return this._batchCache;
  27935. }
  27936. if (currentRenderId !== selfRenderId) {
  27937. this._batchCache.renderSelf[subMeshId] = false;
  27938. }
  27939. }
  27940. this._renderIdForInstances[subMeshId] = currentRenderId;
  27941. }
  27942. return this._batchCache;
  27943. };
  27944. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  27945. var visibleInstances = batch.visibleInstances[subMesh._id];
  27946. if (!visibleInstances) {
  27947. return this;
  27948. }
  27949. var matricesCount = visibleInstances.length + 1;
  27950. var bufferSize = matricesCount * 16 * 4;
  27951. var currentInstancesBufferSize = this._instancesBufferSize;
  27952. var instancesBuffer = this._instancesBuffer;
  27953. while (this._instancesBufferSize < bufferSize) {
  27954. this._instancesBufferSize *= 2;
  27955. }
  27956. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  27957. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  27958. }
  27959. var offset = 0;
  27960. var instancesCount = 0;
  27961. var world = this.getWorldMatrix();
  27962. if (batch.renderSelf[subMesh._id]) {
  27963. world.copyToArray(this._instancesData, offset);
  27964. offset += 16;
  27965. instancesCount++;
  27966. }
  27967. if (visibleInstances) {
  27968. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  27969. var instance = visibleInstances[instanceIndex];
  27970. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  27971. offset += 16;
  27972. instancesCount++;
  27973. }
  27974. }
  27975. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  27976. if (instancesBuffer) {
  27977. instancesBuffer.dispose();
  27978. }
  27979. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  27980. this._instancesBuffer = instancesBuffer;
  27981. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  27982. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  27983. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  27984. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  27985. }
  27986. else {
  27987. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  27988. }
  27989. this._bind(subMesh, effect, fillMode);
  27990. this._draw(subMesh, fillMode, instancesCount);
  27991. engine.unbindInstanceAttributes();
  27992. return this;
  27993. };
  27994. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  27995. var scene = this.getScene();
  27996. var engine = scene.getEngine();
  27997. if (hardwareInstancedRendering) {
  27998. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  27999. }
  28000. else {
  28001. if (batch.renderSelf[subMesh._id]) {
  28002. // Draw
  28003. if (onBeforeDraw) {
  28004. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28005. }
  28006. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28007. }
  28008. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28009. if (visibleInstancesForSubMesh) {
  28010. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28011. var instance = visibleInstancesForSubMesh[instanceIndex];
  28012. // World
  28013. var world = instance.getWorldMatrix();
  28014. if (onBeforeDraw) {
  28015. onBeforeDraw(true, world, effectiveMaterial);
  28016. }
  28017. // Draw
  28018. this._draw(subMesh, fillMode);
  28019. }
  28020. }
  28021. }
  28022. return this;
  28023. };
  28024. /**
  28025. * Triggers the draw call for the mesh.
  28026. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28027. * Returns the Mesh.
  28028. */
  28029. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28030. this.checkOcclusionQuery();
  28031. if (this._isOccluded) {
  28032. return this;
  28033. }
  28034. var scene = this.getScene();
  28035. // Managing instances
  28036. var batch = this._getInstancesRenderList(subMesh._id);
  28037. if (batch.mustReturn) {
  28038. return this;
  28039. }
  28040. // Checking geometry state
  28041. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28042. return this;
  28043. }
  28044. this.onBeforeRenderObservable.notifyObservers(this);
  28045. var engine = scene.getEngine();
  28046. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28047. // Material
  28048. var material = subMesh.getMaterial();
  28049. if (!material) {
  28050. return this;
  28051. }
  28052. this._effectiveMaterial = material;
  28053. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28054. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28055. return this;
  28056. }
  28057. }
  28058. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28059. return this;
  28060. }
  28061. // Alpha mode
  28062. if (enableAlphaMode) {
  28063. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28064. }
  28065. // Outline - step 1
  28066. var savedDepthWrite = engine.getDepthWrite();
  28067. if (this.renderOutline) {
  28068. engine.setDepthWrite(false);
  28069. scene.getOutlineRenderer().render(subMesh, batch);
  28070. engine.setDepthWrite(savedDepthWrite);
  28071. }
  28072. var effect;
  28073. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28074. effect = subMesh.effect;
  28075. }
  28076. else {
  28077. effect = this._effectiveMaterial.getEffect();
  28078. }
  28079. if (!effect) {
  28080. return this;
  28081. }
  28082. var sideOrientation = this.overrideMaterialSideOrientation;
  28083. if (sideOrientation == null) {
  28084. sideOrientation = this._effectiveMaterial.sideOrientation;
  28085. if (this._getWorldMatrixDeterminant() < 0) {
  28086. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  28087. }
  28088. }
  28089. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  28090. if (this._effectiveMaterial.forceDepthWrite) {
  28091. engine.setDepthWrite(true);
  28092. }
  28093. // Bind
  28094. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  28095. if (!hardwareInstancedRendering) {
  28096. this._bind(subMesh, effect, fillMode);
  28097. }
  28098. var world = this.getWorldMatrix();
  28099. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28100. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  28101. }
  28102. else {
  28103. this._effectiveMaterial.bind(world, this);
  28104. }
  28105. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  28106. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  28107. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28108. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  28109. }
  28110. // Draw
  28111. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  28112. // Unbind
  28113. this._effectiveMaterial.unbind();
  28114. // Outline - step 2
  28115. if (this.renderOutline && savedDepthWrite) {
  28116. engine.setDepthWrite(true);
  28117. engine.setColorWrite(false);
  28118. scene.getOutlineRenderer().render(subMesh, batch);
  28119. engine.setColorWrite(true);
  28120. }
  28121. // Overlay
  28122. if (this.renderOverlay) {
  28123. var currentMode = engine.getAlphaMode();
  28124. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28125. scene.getOutlineRenderer().render(subMesh, batch, true);
  28126. engine.setAlphaMode(currentMode);
  28127. }
  28128. this.onAfterRenderObservable.notifyObservers(this);
  28129. return this;
  28130. };
  28131. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  28132. if (isInstance && effectiveMaterial) {
  28133. effectiveMaterial.bindOnlyWorldMatrix(world);
  28134. }
  28135. };
  28136. /**
  28137. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  28138. */
  28139. Mesh.prototype.getEmittedParticleSystems = function () {
  28140. var results = new Array();
  28141. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28142. var particleSystem = this.getScene().particleSystems[index];
  28143. if (particleSystem.emitter === this) {
  28144. results.push(particleSystem);
  28145. }
  28146. }
  28147. return results;
  28148. };
  28149. /**
  28150. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  28151. */
  28152. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  28153. var results = new Array();
  28154. var descendants = this.getDescendants();
  28155. descendants.push(this);
  28156. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  28157. var particleSystem = this.getScene().particleSystems[index];
  28158. var emitter = particleSystem.emitter;
  28159. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  28160. results.push(particleSystem);
  28161. }
  28162. }
  28163. return results;
  28164. };
  28165. Mesh.prototype._checkDelayState = function () {
  28166. var scene = this.getScene();
  28167. if (this._geometry) {
  28168. this._geometry.load(scene);
  28169. }
  28170. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  28171. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28172. this._queueLoad(scene);
  28173. }
  28174. return this;
  28175. };
  28176. Mesh.prototype._queueLoad = function (scene) {
  28177. var _this = this;
  28178. scene._addPendingData(this);
  28179. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  28180. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28181. if (data instanceof ArrayBuffer) {
  28182. _this._delayLoadingFunction(data, _this);
  28183. }
  28184. else {
  28185. _this._delayLoadingFunction(JSON.parse(data), _this);
  28186. }
  28187. _this.instances.forEach(function (instance) {
  28188. instance._syncSubMeshes();
  28189. });
  28190. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28191. scene._removePendingData(_this);
  28192. }, function () { }, scene.database, getBinaryData);
  28193. return this;
  28194. };
  28195. /**
  28196. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  28197. */
  28198. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  28199. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28200. return false;
  28201. }
  28202. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  28203. return false;
  28204. }
  28205. this._checkDelayState();
  28206. return true;
  28207. };
  28208. /**
  28209. * Sets the mesh material by the material or multiMaterial `id` property.
  28210. * The material `id` is a string identifying the material or the multiMaterial.
  28211. * This method returns the Mesh.
  28212. */
  28213. Mesh.prototype.setMaterialByID = function (id) {
  28214. var materials = this.getScene().materials;
  28215. var index;
  28216. for (index = materials.length - 1; index > -1; index--) {
  28217. if (materials[index].id === id) {
  28218. this.material = materials[index];
  28219. return this;
  28220. }
  28221. }
  28222. // Multi
  28223. var multiMaterials = this.getScene().multiMaterials;
  28224. for (index = multiMaterials.length - 1; index > -1; index--) {
  28225. if (multiMaterials[index].id === id) {
  28226. this.material = multiMaterials[index];
  28227. return this;
  28228. }
  28229. }
  28230. return this;
  28231. };
  28232. /**
  28233. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  28234. */
  28235. Mesh.prototype.getAnimatables = function () {
  28236. var results = new Array();
  28237. if (this.material) {
  28238. results.push(this.material);
  28239. }
  28240. if (this.skeleton) {
  28241. results.push(this.skeleton);
  28242. }
  28243. return results;
  28244. };
  28245. /**
  28246. * Modifies the mesh geometry according to the passed transformation matrix.
  28247. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  28248. * The mesh normals are modified accordingly the same transformation.
  28249. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  28250. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28251. * Returns the Mesh.
  28252. */
  28253. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  28254. // Position
  28255. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28256. return this;
  28257. }
  28258. var submeshes = this.subMeshes.splice(0);
  28259. this._resetPointsArrayCache();
  28260. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28261. var temp = new Array();
  28262. var index;
  28263. for (index = 0; index < data.length; index += 3) {
  28264. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  28265. }
  28266. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  28267. // Normals
  28268. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28269. return this;
  28270. }
  28271. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28272. temp = [];
  28273. for (index = 0; index < data.length; index += 3) {
  28274. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  28275. }
  28276. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  28277. // flip faces?
  28278. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  28279. this.flipFaces();
  28280. }
  28281. // Restore submeshes
  28282. this.releaseSubMeshes();
  28283. this.subMeshes = submeshes;
  28284. return this;
  28285. };
  28286. /**
  28287. * Modifies the mesh geometry according to its own current World Matrix.
  28288. * The mesh World Matrix is then reset.
  28289. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  28290. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  28291. * Note that, under the hood, this method sets a new VertexBuffer each call.
  28292. * Returns the Mesh.
  28293. */
  28294. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  28295. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  28296. this.scaling.copyFromFloats(1, 1, 1);
  28297. this.position.copyFromFloats(0, 0, 0);
  28298. this.rotation.copyFromFloats(0, 0, 0);
  28299. //only if quaternion is already set
  28300. if (this.rotationQuaternion) {
  28301. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  28302. }
  28303. this._worldMatrix = BABYLON.Matrix.Identity();
  28304. return this;
  28305. };
  28306. Object.defineProperty(Mesh.prototype, "_positions", {
  28307. // Cache
  28308. get: function () {
  28309. if (this._geometry) {
  28310. return this._geometry._positions;
  28311. }
  28312. return null;
  28313. },
  28314. enumerable: true,
  28315. configurable: true
  28316. });
  28317. Mesh.prototype._resetPointsArrayCache = function () {
  28318. if (this._geometry) {
  28319. this._geometry._resetPointsArrayCache();
  28320. }
  28321. return this;
  28322. };
  28323. Mesh.prototype._generatePointsArray = function () {
  28324. if (this._geometry) {
  28325. return this._geometry._generatePointsArray();
  28326. }
  28327. return false;
  28328. };
  28329. /**
  28330. * Returns a new Mesh object generated from the current mesh properties.
  28331. * This method must not get confused with createInstance().
  28332. * The parameter `name` is a string, the name given to the new mesh.
  28333. * The optional parameter `newParent` can be any Node object (default `null`).
  28334. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  28335. * 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.
  28336. */
  28337. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  28338. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  28339. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  28340. };
  28341. /**
  28342. * Disposes the Mesh.
  28343. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  28344. * Returns nothing.
  28345. */
  28346. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  28347. var _this = this;
  28348. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  28349. this.morphTargetManager = null;
  28350. if (this._geometry) {
  28351. this._geometry.releaseForMesh(this, true);
  28352. }
  28353. // Sources
  28354. var meshes = this.getScene().meshes;
  28355. meshes.forEach(function (abstractMesh) {
  28356. var mesh = abstractMesh;
  28357. if (mesh._source && mesh._source === _this) {
  28358. mesh._source = null;
  28359. }
  28360. });
  28361. this._source = null;
  28362. // Instances
  28363. if (this._instancesBuffer) {
  28364. this._instancesBuffer.dispose();
  28365. this._instancesBuffer = null;
  28366. }
  28367. while (this.instances.length) {
  28368. this.instances[0].dispose();
  28369. }
  28370. // Effect layers.
  28371. var effectLayers = this.getScene().effectLayers;
  28372. for (var i = 0; i < effectLayers.length; i++) {
  28373. var effectLayer = effectLayers[i];
  28374. if (effectLayer) {
  28375. effectLayer._disposeMesh(this);
  28376. }
  28377. }
  28378. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  28379. };
  28380. /**
  28381. * Modifies the mesh geometry according to a displacement map.
  28382. * 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.
  28383. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28384. * This method returns nothing.
  28385. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  28386. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28387. * 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.
  28388. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28389. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28390. *
  28391. * Returns the Mesh.
  28392. */
  28393. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  28394. var _this = this;
  28395. var scene = this.getScene();
  28396. var onload = function (img) {
  28397. // Getting height map data
  28398. var canvas = document.createElement("canvas");
  28399. var context = canvas.getContext("2d");
  28400. var heightMapWidth = img.width;
  28401. var heightMapHeight = img.height;
  28402. canvas.width = heightMapWidth;
  28403. canvas.height = heightMapHeight;
  28404. context.drawImage(img, 0, 0);
  28405. // Create VertexData from map data
  28406. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  28407. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  28408. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  28409. //execute success callback, if set
  28410. if (onSuccess) {
  28411. onSuccess(_this);
  28412. }
  28413. };
  28414. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  28415. return this;
  28416. };
  28417. /**
  28418. * Modifies the mesh geometry according to a displacementMap buffer.
  28419. * 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.
  28420. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  28421. * This method returns nothing.
  28422. * 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.
  28423. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  28424. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  28425. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  28426. * The parameter `uvScale` is an optional vector2 used to scale UV.
  28427. *
  28428. * Returns the Mesh.
  28429. */
  28430. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  28431. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  28432. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  28433. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28434. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  28435. return this;
  28436. }
  28437. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28438. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28439. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28440. var position = BABYLON.Vector3.Zero();
  28441. var normal = BABYLON.Vector3.Zero();
  28442. var uv = BABYLON.Vector2.Zero();
  28443. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  28444. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  28445. for (var index = 0; index < positions.length; index += 3) {
  28446. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  28447. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  28448. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  28449. // Compute height
  28450. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  28451. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  28452. var pos = (u + v * heightMapWidth) * 4;
  28453. var r = buffer[pos] / 255.0;
  28454. var g = buffer[pos + 1] / 255.0;
  28455. var b = buffer[pos + 2] / 255.0;
  28456. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  28457. normal.normalize();
  28458. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  28459. position = position.add(normal);
  28460. position.toArray(positions, index);
  28461. }
  28462. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  28463. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  28464. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  28465. return this;
  28466. };
  28467. /**
  28468. * Modify the mesh to get a flat shading rendering.
  28469. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  28470. * This method returns the Mesh.
  28471. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  28472. */
  28473. Mesh.prototype.convertToFlatShadedMesh = function () {
  28474. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  28475. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28476. var kinds = this.getVerticesDataKinds();
  28477. var vbs = {};
  28478. var data = {};
  28479. var newdata = {};
  28480. var updatableNormals = false;
  28481. var kindIndex;
  28482. var kind;
  28483. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28484. kind = kinds[kindIndex];
  28485. var vertexBuffer = this.getVertexBuffer(kind);
  28486. if (kind === BABYLON.VertexBuffer.NormalKind) {
  28487. updatableNormals = vertexBuffer.isUpdatable();
  28488. kinds.splice(kindIndex, 1);
  28489. kindIndex--;
  28490. continue;
  28491. }
  28492. vbs[kind] = vertexBuffer;
  28493. data[kind] = vbs[kind].getData();
  28494. newdata[kind] = [];
  28495. }
  28496. // Save previous submeshes
  28497. var previousSubmeshes = this.subMeshes.slice(0);
  28498. var indices = this.getIndices();
  28499. var totalIndices = this.getTotalIndices();
  28500. // Generating unique vertices per face
  28501. var index;
  28502. for (index = 0; index < totalIndices; index++) {
  28503. var vertexIndex = indices[index];
  28504. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28505. kind = kinds[kindIndex];
  28506. var stride = vbs[kind].getStrideSize();
  28507. for (var offset = 0; offset < stride; offset++) {
  28508. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28509. }
  28510. }
  28511. }
  28512. // Updating faces & normal
  28513. var normals = [];
  28514. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  28515. for (index = 0; index < totalIndices; index += 3) {
  28516. indices[index] = index;
  28517. indices[index + 1] = index + 1;
  28518. indices[index + 2] = index + 2;
  28519. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  28520. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  28521. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  28522. var p1p2 = p1.subtract(p2);
  28523. var p3p2 = p3.subtract(p2);
  28524. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  28525. // Store same normals for every vertex
  28526. for (var localIndex = 0; localIndex < 3; localIndex++) {
  28527. normals.push(normal.x);
  28528. normals.push(normal.y);
  28529. normals.push(normal.z);
  28530. }
  28531. }
  28532. this.setIndices(indices);
  28533. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  28534. // Updating vertex buffers
  28535. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28536. kind = kinds[kindIndex];
  28537. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28538. }
  28539. // Updating submeshes
  28540. this.releaseSubMeshes();
  28541. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28542. var previousOne = previousSubmeshes[submeshIndex];
  28543. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28544. }
  28545. this.synchronizeInstances();
  28546. return this;
  28547. };
  28548. /**
  28549. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  28550. * In other words, more vertices, no more indices and a single bigger VBO.
  28551. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  28552. * Returns the Mesh.
  28553. */
  28554. Mesh.prototype.convertToUnIndexedMesh = function () {
  28555. /// <summary>Remove indices by unfolding faces into buffers</summary>
  28556. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  28557. var kinds = this.getVerticesDataKinds();
  28558. var vbs = {};
  28559. var data = {};
  28560. var newdata = {};
  28561. var kindIndex;
  28562. var kind;
  28563. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28564. kind = kinds[kindIndex];
  28565. var vertexBuffer = this.getVertexBuffer(kind);
  28566. vbs[kind] = vertexBuffer;
  28567. data[kind] = vbs[kind].getData();
  28568. newdata[kind] = [];
  28569. }
  28570. // Save previous submeshes
  28571. var previousSubmeshes = this.subMeshes.slice(0);
  28572. var indices = this.getIndices();
  28573. var totalIndices = this.getTotalIndices();
  28574. // Generating unique vertices per face
  28575. var index;
  28576. for (index = 0; index < totalIndices; index++) {
  28577. var vertexIndex = indices[index];
  28578. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28579. kind = kinds[kindIndex];
  28580. var stride = vbs[kind].getStrideSize();
  28581. for (var offset = 0; offset < stride; offset++) {
  28582. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  28583. }
  28584. }
  28585. }
  28586. // Updating indices
  28587. for (index = 0; index < totalIndices; index += 3) {
  28588. indices[index] = index;
  28589. indices[index + 1] = index + 1;
  28590. indices[index + 2] = index + 2;
  28591. }
  28592. this.setIndices(indices);
  28593. // Updating vertex buffers
  28594. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  28595. kind = kinds[kindIndex];
  28596. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  28597. }
  28598. // Updating submeshes
  28599. this.releaseSubMeshes();
  28600. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  28601. var previousOne = previousSubmeshes[submeshIndex];
  28602. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  28603. }
  28604. this._unIndexed = true;
  28605. this.synchronizeInstances();
  28606. return this;
  28607. };
  28608. /**
  28609. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  28610. * This method returns the Mesh.
  28611. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  28612. */
  28613. Mesh.prototype.flipFaces = function (flipNormals) {
  28614. if (flipNormals === void 0) { flipNormals = false; }
  28615. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  28616. var i;
  28617. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  28618. for (i = 0; i < vertex_data.normals.length; i++) {
  28619. vertex_data.normals[i] *= -1;
  28620. }
  28621. }
  28622. if (vertex_data.indices) {
  28623. var temp;
  28624. for (i = 0; i < vertex_data.indices.length; i += 3) {
  28625. // reassign indices
  28626. temp = vertex_data.indices[i + 1];
  28627. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  28628. vertex_data.indices[i + 2] = temp;
  28629. }
  28630. }
  28631. vertex_data.applyToMesh(this);
  28632. return this;
  28633. };
  28634. // Instances
  28635. /**
  28636. * Creates a new InstancedMesh object from the mesh model.
  28637. * An instance shares the same properties and the same material than its model.
  28638. * Only these properties of each instance can then be set individually :
  28639. * - position
  28640. * - rotation
  28641. * - rotationQuaternion
  28642. * - setPivotMatrix
  28643. * - scaling
  28644. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  28645. * Warning : this method is not supported for Line mesh and LineSystem
  28646. */
  28647. Mesh.prototype.createInstance = function (name) {
  28648. return new BABYLON.InstancedMesh(name, this);
  28649. };
  28650. /**
  28651. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  28652. * After this call, all the mesh instances have the same submeshes than the current mesh.
  28653. * This method returns the Mesh.
  28654. */
  28655. Mesh.prototype.synchronizeInstances = function () {
  28656. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  28657. var instance = this.instances[instanceIndex];
  28658. instance._syncSubMeshes();
  28659. }
  28660. return this;
  28661. };
  28662. /**
  28663. * Simplify the mesh according to the given array of settings.
  28664. * Function will return immediately and will simplify async. It returns the Mesh.
  28665. * @param settings a collection of simplification settings.
  28666. * @param parallelProcessing should all levels calculate parallel or one after the other.
  28667. * @param type the type of simplification to run.
  28668. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  28669. */
  28670. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  28671. if (parallelProcessing === void 0) { parallelProcessing = true; }
  28672. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  28673. this.getScene().simplificationQueue.addTask({
  28674. settings: settings,
  28675. parallelProcessing: parallelProcessing,
  28676. mesh: this,
  28677. simplificationType: simplificationType,
  28678. successCallback: successCallback
  28679. });
  28680. return this;
  28681. };
  28682. /**
  28683. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  28684. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  28685. * This should be used together with the simplification to avoid disappearing triangles.
  28686. * Returns the Mesh.
  28687. * @param successCallback an optional success callback to be called after the optimization finished.
  28688. */
  28689. Mesh.prototype.optimizeIndices = function (successCallback) {
  28690. var _this = this;
  28691. var indices = this.getIndices();
  28692. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28693. if (!positions || !indices) {
  28694. return this;
  28695. }
  28696. var vectorPositions = new Array();
  28697. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  28698. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  28699. }
  28700. var dupes = new Array();
  28701. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  28702. var realPos = vectorPositions.length - 1 - iteration;
  28703. var testedPosition = vectorPositions[realPos];
  28704. for (var j = 0; j < realPos; ++j) {
  28705. var againstPosition = vectorPositions[j];
  28706. if (testedPosition.equals(againstPosition)) {
  28707. dupes[realPos] = j;
  28708. break;
  28709. }
  28710. }
  28711. }, function () {
  28712. for (var i = 0; i < indices.length; ++i) {
  28713. indices[i] = dupes[indices[i]] || indices[i];
  28714. }
  28715. //indices are now reordered
  28716. var originalSubMeshes = _this.subMeshes.slice(0);
  28717. _this.setIndices(indices);
  28718. _this.subMeshes = originalSubMeshes;
  28719. if (successCallback) {
  28720. successCallback(_this);
  28721. }
  28722. });
  28723. return this;
  28724. };
  28725. Mesh.prototype.serialize = function (serializationObject) {
  28726. serializationObject.name = this.name;
  28727. serializationObject.id = this.id;
  28728. serializationObject.type = this.getClassName();
  28729. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28730. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28731. }
  28732. serializationObject.position = this.position.asArray();
  28733. if (this.rotationQuaternion) {
  28734. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  28735. }
  28736. else if (this.rotation) {
  28737. serializationObject.rotation = this.rotation.asArray();
  28738. }
  28739. serializationObject.scaling = this.scaling.asArray();
  28740. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  28741. serializationObject.isEnabled = this.isEnabled(false);
  28742. serializationObject.isVisible = this.isVisible;
  28743. serializationObject.infiniteDistance = this.infiniteDistance;
  28744. serializationObject.pickable = this.isPickable;
  28745. serializationObject.receiveShadows = this.receiveShadows;
  28746. serializationObject.billboardMode = this.billboardMode;
  28747. serializationObject.visibility = this.visibility;
  28748. serializationObject.checkCollisions = this.checkCollisions;
  28749. serializationObject.isBlocker = this.isBlocker;
  28750. // Parent
  28751. if (this.parent) {
  28752. serializationObject.parentId = this.parent.id;
  28753. }
  28754. // Geometry
  28755. serializationObject.isUnIndexed = this.isUnIndexed;
  28756. var geometry = this._geometry;
  28757. if (geometry) {
  28758. var geometryId = geometry.id;
  28759. serializationObject.geometryId = geometryId;
  28760. // SubMeshes
  28761. serializationObject.subMeshes = [];
  28762. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  28763. var subMesh = this.subMeshes[subIndex];
  28764. serializationObject.subMeshes.push({
  28765. materialIndex: subMesh.materialIndex,
  28766. verticesStart: subMesh.verticesStart,
  28767. verticesCount: subMesh.verticesCount,
  28768. indexStart: subMesh.indexStart,
  28769. indexCount: subMesh.indexCount
  28770. });
  28771. }
  28772. }
  28773. // Material
  28774. if (this.material) {
  28775. serializationObject.materialId = this.material.id;
  28776. }
  28777. else {
  28778. this.material = null;
  28779. }
  28780. // Morph targets
  28781. if (this.morphTargetManager) {
  28782. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  28783. }
  28784. // Skeleton
  28785. if (this.skeleton) {
  28786. serializationObject.skeletonId = this.skeleton.id;
  28787. }
  28788. // Physics
  28789. //TODO implement correct serialization for physics impostors.
  28790. var impostor = this.getPhysicsImpostor();
  28791. if (impostor) {
  28792. serializationObject.physicsMass = impostor.getParam("mass");
  28793. serializationObject.physicsFriction = impostor.getParam("friction");
  28794. serializationObject.physicsRestitution = impostor.getParam("mass");
  28795. serializationObject.physicsImpostor = impostor.type;
  28796. }
  28797. // Metadata
  28798. if (this.metadata) {
  28799. serializationObject.metadata = this.metadata;
  28800. }
  28801. // Instances
  28802. serializationObject.instances = [];
  28803. for (var index = 0; index < this.instances.length; index++) {
  28804. var instance = this.instances[index];
  28805. var serializationInstance = {
  28806. name: instance.name,
  28807. id: instance.id,
  28808. position: instance.position.asArray(),
  28809. scaling: instance.scaling.asArray()
  28810. };
  28811. if (instance.rotationQuaternion) {
  28812. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  28813. }
  28814. else if (instance.rotation) {
  28815. serializationInstance.rotation = instance.rotation.asArray();
  28816. }
  28817. serializationObject.instances.push(serializationInstance);
  28818. // Animations
  28819. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  28820. serializationInstance.ranges = instance.serializeAnimationRanges();
  28821. }
  28822. //
  28823. // Animations
  28824. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28825. serializationObject.ranges = this.serializeAnimationRanges();
  28826. // Layer mask
  28827. serializationObject.layerMask = this.layerMask;
  28828. // Alpha
  28829. serializationObject.alphaIndex = this.alphaIndex;
  28830. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  28831. // Overlay
  28832. serializationObject.overlayAlpha = this.overlayAlpha;
  28833. serializationObject.overlayColor = this.overlayColor.asArray();
  28834. serializationObject.renderOverlay = this.renderOverlay;
  28835. // Fog
  28836. serializationObject.applyFog = this.applyFog;
  28837. // Action Manager
  28838. if (this.actionManager) {
  28839. serializationObject.actions = this.actionManager.serialize(this.name);
  28840. }
  28841. };
  28842. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  28843. if (!this.geometry) {
  28844. return;
  28845. }
  28846. this._markSubMeshesAsAttributesDirty();
  28847. var morphTargetManager = this._morphTargetManager;
  28848. if (morphTargetManager && morphTargetManager.vertexCount) {
  28849. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  28850. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  28851. this.morphTargetManager = null;
  28852. return;
  28853. }
  28854. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  28855. var morphTarget = morphTargetManager.getActiveTarget(index);
  28856. var positions = morphTarget.getPositions();
  28857. if (!positions) {
  28858. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  28859. return;
  28860. }
  28861. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  28862. var normals = morphTarget.getNormals();
  28863. if (normals) {
  28864. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  28865. }
  28866. var tangents = morphTarget.getTangents();
  28867. if (tangents) {
  28868. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  28869. }
  28870. }
  28871. }
  28872. else {
  28873. var index = 0;
  28874. // Positions
  28875. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  28876. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  28877. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  28878. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  28879. }
  28880. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  28881. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  28882. }
  28883. index++;
  28884. }
  28885. }
  28886. };
  28887. // Statics
  28888. /**
  28889. * Returns a new Mesh object parsed from the source provided.
  28890. * The parameter `parsedMesh` is the source.
  28891. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  28892. */
  28893. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  28894. var mesh;
  28895. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  28896. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  28897. }
  28898. else {
  28899. mesh = new Mesh(parsedMesh.name, scene);
  28900. }
  28901. mesh.id = parsedMesh.id;
  28902. if (BABYLON.Tags) {
  28903. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  28904. }
  28905. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  28906. if (parsedMesh.metadata !== undefined) {
  28907. mesh.metadata = parsedMesh.metadata;
  28908. }
  28909. if (parsedMesh.rotationQuaternion) {
  28910. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  28911. }
  28912. else if (parsedMesh.rotation) {
  28913. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  28914. }
  28915. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  28916. if (parsedMesh.localMatrix) {
  28917. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  28918. }
  28919. else if (parsedMesh.pivotMatrix) {
  28920. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  28921. }
  28922. mesh.setEnabled(parsedMesh.isEnabled);
  28923. mesh.isVisible = parsedMesh.isVisible;
  28924. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  28925. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  28926. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  28927. if (parsedMesh.applyFog !== undefined) {
  28928. mesh.applyFog = parsedMesh.applyFog;
  28929. }
  28930. if (parsedMesh.pickable !== undefined) {
  28931. mesh.isPickable = parsedMesh.pickable;
  28932. }
  28933. if (parsedMesh.alphaIndex !== undefined) {
  28934. mesh.alphaIndex = parsedMesh.alphaIndex;
  28935. }
  28936. mesh.receiveShadows = parsedMesh.receiveShadows;
  28937. mesh.billboardMode = parsedMesh.billboardMode;
  28938. if (parsedMesh.visibility !== undefined) {
  28939. mesh.visibility = parsedMesh.visibility;
  28940. }
  28941. mesh.checkCollisions = parsedMesh.checkCollisions;
  28942. if (parsedMesh.isBlocker !== undefined) {
  28943. mesh.isBlocker = parsedMesh.isBlocker;
  28944. }
  28945. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  28946. // freezeWorldMatrix
  28947. if (parsedMesh.freezeWorldMatrix) {
  28948. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  28949. }
  28950. // Parent
  28951. if (parsedMesh.parentId) {
  28952. mesh._waitingParentId = parsedMesh.parentId;
  28953. }
  28954. // Actions
  28955. if (parsedMesh.actions !== undefined) {
  28956. mesh._waitingActions = parsedMesh.actions;
  28957. }
  28958. // Overlay
  28959. if (parsedMesh.overlayAlpha !== undefined) {
  28960. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  28961. }
  28962. if (parsedMesh.overlayColor !== undefined) {
  28963. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  28964. }
  28965. if (parsedMesh.renderOverlay !== undefined) {
  28966. mesh.renderOverlay = parsedMesh.renderOverlay;
  28967. }
  28968. // Geometry
  28969. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  28970. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  28971. if (parsedMesh.delayLoadingFile) {
  28972. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  28973. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  28974. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  28975. if (parsedMesh._binaryInfo) {
  28976. mesh._binaryInfo = parsedMesh._binaryInfo;
  28977. }
  28978. mesh._delayInfo = [];
  28979. if (parsedMesh.hasUVs) {
  28980. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  28981. }
  28982. if (parsedMesh.hasUVs2) {
  28983. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  28984. }
  28985. if (parsedMesh.hasUVs3) {
  28986. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  28987. }
  28988. if (parsedMesh.hasUVs4) {
  28989. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  28990. }
  28991. if (parsedMesh.hasUVs5) {
  28992. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  28993. }
  28994. if (parsedMesh.hasUVs6) {
  28995. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  28996. }
  28997. if (parsedMesh.hasColors) {
  28998. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  28999. }
  29000. if (parsedMesh.hasMatricesIndices) {
  29001. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29002. }
  29003. if (parsedMesh.hasMatricesWeights) {
  29004. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29005. }
  29006. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29007. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29008. mesh._checkDelayState();
  29009. }
  29010. }
  29011. else {
  29012. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29013. }
  29014. // Material
  29015. if (parsedMesh.materialId) {
  29016. mesh.setMaterialByID(parsedMesh.materialId);
  29017. }
  29018. else {
  29019. mesh.material = null;
  29020. }
  29021. // Morph targets
  29022. if (parsedMesh.morphTargetManagerId > -1) {
  29023. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29024. }
  29025. // Skeleton
  29026. if (parsedMesh.skeletonId > -1) {
  29027. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29028. if (parsedMesh.numBoneInfluencers) {
  29029. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29030. }
  29031. }
  29032. // Animations
  29033. if (parsedMesh.animations) {
  29034. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29035. var parsedAnimation = parsedMesh.animations[animationIndex];
  29036. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29037. }
  29038. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29039. }
  29040. if (parsedMesh.autoAnimate) {
  29041. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29042. }
  29043. // Layer Mask
  29044. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29045. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29046. }
  29047. else {
  29048. mesh.layerMask = 0x0FFFFFFF;
  29049. }
  29050. // Physics
  29051. if (parsedMesh.physicsImpostor) {
  29052. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29053. mass: parsedMesh.physicsMass,
  29054. friction: parsedMesh.physicsFriction,
  29055. restitution: parsedMesh.physicsRestitution
  29056. }, scene);
  29057. }
  29058. // Instances
  29059. if (parsedMesh.instances) {
  29060. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29061. var parsedInstance = parsedMesh.instances[index];
  29062. var instance = mesh.createInstance(parsedInstance.name);
  29063. if (parsedInstance.id) {
  29064. instance.id = parsedInstance.id;
  29065. }
  29066. if (BABYLON.Tags) {
  29067. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29068. }
  29069. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29070. if (parsedInstance.parentId) {
  29071. instance._waitingParentId = parsedInstance.parentId;
  29072. }
  29073. if (parsedInstance.rotationQuaternion) {
  29074. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29075. }
  29076. else if (parsedInstance.rotation) {
  29077. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29078. }
  29079. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29080. instance.checkCollisions = mesh.checkCollisions;
  29081. if (parsedMesh.animations) {
  29082. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29083. parsedAnimation = parsedMesh.animations[animationIndex];
  29084. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29085. }
  29086. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  29087. }
  29088. }
  29089. }
  29090. return mesh;
  29091. };
  29092. /**
  29093. * Creates a ribbon mesh.
  29094. * Please consider using the same method from the MeshBuilder class instead.
  29095. * 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.
  29096. *
  29097. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  29098. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  29099. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  29100. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  29101. * 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.
  29102. * 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.
  29103. * 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
  29104. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29105. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29106. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29107. */
  29108. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  29109. if (closeArray === void 0) { closeArray = false; }
  29110. if (updatable === void 0) { updatable = false; }
  29111. return BABYLON.MeshBuilder.CreateRibbon(name, {
  29112. pathArray: pathArray,
  29113. closeArray: closeArray,
  29114. closePath: closePath,
  29115. offset: offset,
  29116. updatable: updatable,
  29117. sideOrientation: sideOrientation,
  29118. instance: instance
  29119. }, scene);
  29120. };
  29121. /**
  29122. * Creates a plane polygonal mesh. By default, this is a disc.
  29123. * Please consider using the same method from the MeshBuilder class instead.
  29124. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  29125. * 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.
  29126. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29127. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29128. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29129. */
  29130. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  29131. if (scene === void 0) { scene = null; }
  29132. var options = {
  29133. radius: radius,
  29134. tessellation: tessellation,
  29135. sideOrientation: sideOrientation,
  29136. updatable: updatable
  29137. };
  29138. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  29139. };
  29140. /**
  29141. * Creates a box mesh.
  29142. * Please consider using the same method from the MeshBuilder class instead.
  29143. * The parameter `size` sets the size (float) of each box side (default 1).
  29144. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29145. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29146. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29147. */
  29148. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  29149. if (scene === void 0) { scene = null; }
  29150. var options = {
  29151. size: size,
  29152. sideOrientation: sideOrientation,
  29153. updatable: updatable
  29154. };
  29155. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  29156. };
  29157. /**
  29158. * Creates a sphere mesh.
  29159. * Please consider using the same method from the MeshBuilder class instead.
  29160. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  29161. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  29162. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29163. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29164. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29165. */
  29166. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  29167. var options = {
  29168. segments: segments,
  29169. diameterX: diameter,
  29170. diameterY: diameter,
  29171. diameterZ: diameter,
  29172. sideOrientation: sideOrientation,
  29173. updatable: updatable
  29174. };
  29175. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  29176. };
  29177. /**
  29178. * Creates a cylinder or a cone mesh.
  29179. * Please consider using the same method from the MeshBuilder class instead.
  29180. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  29181. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  29182. * 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.
  29183. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  29184. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  29185. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29186. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29187. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29188. */
  29189. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  29190. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  29191. if (scene !== undefined) {
  29192. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  29193. updatable = scene;
  29194. }
  29195. scene = subdivisions;
  29196. subdivisions = 1;
  29197. }
  29198. var options = {
  29199. height: height,
  29200. diameterTop: diameterTop,
  29201. diameterBottom: diameterBottom,
  29202. tessellation: tessellation,
  29203. subdivisions: subdivisions,
  29204. sideOrientation: sideOrientation,
  29205. updatable: updatable
  29206. };
  29207. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  29208. };
  29209. // Torus (Code from SharpDX.org)
  29210. /**
  29211. * Creates a torus mesh.
  29212. * Please consider using the same method from the MeshBuilder class instead.
  29213. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  29214. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  29215. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  29216. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29217. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29218. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29219. */
  29220. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  29221. var options = {
  29222. diameter: diameter,
  29223. thickness: thickness,
  29224. tessellation: tessellation,
  29225. sideOrientation: sideOrientation,
  29226. updatable: updatable
  29227. };
  29228. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  29229. };
  29230. /**
  29231. * Creates a torus knot mesh.
  29232. * Please consider using the same method from the MeshBuilder class instead.
  29233. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  29234. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  29235. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  29236. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  29237. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29238. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29239. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29240. */
  29241. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  29242. var options = {
  29243. radius: radius,
  29244. tube: tube,
  29245. radialSegments: radialSegments,
  29246. tubularSegments: tubularSegments,
  29247. p: p,
  29248. q: q,
  29249. sideOrientation: sideOrientation,
  29250. updatable: updatable
  29251. };
  29252. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  29253. };
  29254. /**
  29255. * Creates a line mesh.
  29256. * Please consider using the same method from the MeshBuilder class instead.
  29257. * 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.
  29258. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29259. * The parameter `points` is an array successive Vector3.
  29260. * 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
  29261. * When updating an instance, remember that only point positions can change, not the number of points.
  29262. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29263. */
  29264. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  29265. if (scene === void 0) { scene = null; }
  29266. if (updatable === void 0) { updatable = false; }
  29267. if (instance === void 0) { instance = null; }
  29268. var options = {
  29269. points: points,
  29270. updatable: updatable,
  29271. instance: instance
  29272. };
  29273. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  29274. };
  29275. /**
  29276. * Creates a dashed line mesh.
  29277. * Please consider using the same method from the MeshBuilder class instead.
  29278. * 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.
  29279. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  29280. * The parameter `points` is an array successive Vector3.
  29281. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  29282. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  29283. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  29284. * 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
  29285. * When updating an instance, remember that only point positions can change, not the number of points.
  29286. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29287. */
  29288. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  29289. if (scene === void 0) { scene = null; }
  29290. var options = {
  29291. points: points,
  29292. dashSize: dashSize,
  29293. gapSize: gapSize,
  29294. dashNb: dashNb,
  29295. updatable: updatable,
  29296. instance: instance
  29297. };
  29298. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  29299. };
  29300. /**
  29301. * Creates a polygon mesh.
  29302. * Please consider using the same method from the MeshBuilder class instead.
  29303. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  29304. * 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.
  29305. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29306. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29307. * Remember you can only change the shape positions, not their number when updating a polygon.
  29308. */
  29309. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  29310. var options = {
  29311. shape: shape,
  29312. holes: holes,
  29313. updatable: updatable,
  29314. sideOrientation: sideOrientation
  29315. };
  29316. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  29317. };
  29318. /**
  29319. * Creates an extruded polygon mesh, with depth in the Y direction.
  29320. * Please consider using the same method from the MeshBuilder class instead.
  29321. */
  29322. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  29323. var options = {
  29324. shape: shape,
  29325. holes: holes,
  29326. depth: depth,
  29327. updatable: updatable,
  29328. sideOrientation: sideOrientation
  29329. };
  29330. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  29331. };
  29332. /**
  29333. * Creates an extruded shape mesh.
  29334. * 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.
  29335. * Please consider using the same method from the MeshBuilder class instead.
  29336. *
  29337. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29338. * 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
  29339. * extruded along the Z axis.
  29340. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29341. * 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.
  29342. * The parameter `scale` (float, default 1) is the value to scale the shape.
  29343. * 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
  29344. * 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
  29345. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29346. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29347. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29348. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29349. */
  29350. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  29351. if (scene === void 0) { scene = null; }
  29352. var options = {
  29353. shape: shape,
  29354. path: path,
  29355. scale: scale,
  29356. rotation: rotation,
  29357. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29358. sideOrientation: sideOrientation,
  29359. instance: instance,
  29360. updatable: updatable
  29361. };
  29362. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  29363. };
  29364. /**
  29365. * Creates an custom extruded shape mesh.
  29366. * 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.
  29367. * Please consider using the same method from the MeshBuilder class instead.
  29368. *
  29369. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  29370. * 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
  29371. * extruded along the Z axis.
  29372. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  29373. * 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
  29374. * and the distance of this point from the begining of the path :
  29375. * ```javascript
  29376. * var rotationFunction = function(i, distance) {
  29377. * // do things
  29378. * return rotationValue; }
  29379. * ```
  29380. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  29381. * 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
  29382. * and the distance of this point from the begining of the path :
  29383. * ```javascript
  29384. * var scaleFunction = function(i, distance) {
  29385. * // do things
  29386. * return scaleValue;}
  29387. * ```
  29388. * It must returns a float value that will be the scale value applied to the shape on each path point.
  29389. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  29390. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  29391. * 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
  29392. * 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
  29393. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  29394. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29395. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29396. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29397. */
  29398. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  29399. var options = {
  29400. shape: shape,
  29401. path: path,
  29402. scaleFunction: scaleFunction,
  29403. rotationFunction: rotationFunction,
  29404. ribbonCloseArray: ribbonCloseArray,
  29405. ribbonClosePath: ribbonClosePath,
  29406. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  29407. sideOrientation: sideOrientation,
  29408. instance: instance,
  29409. updatable: updatable
  29410. };
  29411. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  29412. };
  29413. /**
  29414. * Creates lathe mesh.
  29415. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  29416. * Please consider using the same method from the MeshBuilder class instead.
  29417. * 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
  29418. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  29419. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  29420. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  29421. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29422. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29423. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29424. */
  29425. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  29426. var options = {
  29427. shape: shape,
  29428. radius: radius,
  29429. tessellation: tessellation,
  29430. sideOrientation: sideOrientation,
  29431. updatable: updatable
  29432. };
  29433. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  29434. };
  29435. /**
  29436. * Creates a plane mesh.
  29437. * Please consider using the same method from the MeshBuilder class instead.
  29438. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  29439. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29440. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29441. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29442. */
  29443. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  29444. var options = {
  29445. size: size,
  29446. width: size,
  29447. height: size,
  29448. sideOrientation: sideOrientation,
  29449. updatable: updatable
  29450. };
  29451. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  29452. };
  29453. /**
  29454. * Creates a ground mesh.
  29455. * Please consider using the same method from the MeshBuilder class instead.
  29456. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  29457. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  29458. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29459. */
  29460. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  29461. var options = {
  29462. width: width,
  29463. height: height,
  29464. subdivisions: subdivisions,
  29465. updatable: updatable
  29466. };
  29467. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  29468. };
  29469. /**
  29470. * Creates a tiled ground mesh.
  29471. * Please consider using the same method from the MeshBuilder class instead.
  29472. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  29473. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  29474. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  29475. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  29476. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  29477. * numbers of subdivisions on the ground width and height of each tile.
  29478. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29479. */
  29480. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  29481. var options = {
  29482. xmin: xmin,
  29483. zmin: zmin,
  29484. xmax: xmax,
  29485. zmax: zmax,
  29486. subdivisions: subdivisions,
  29487. precision: precision,
  29488. updatable: updatable
  29489. };
  29490. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  29491. };
  29492. /**
  29493. * Creates a ground mesh from a height map.
  29494. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  29495. * Please consider using the same method from the MeshBuilder class instead.
  29496. * The parameter `url` sets the URL of the height map image resource.
  29497. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  29498. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  29499. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  29500. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  29501. * 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).
  29502. * This function is passed the newly built mesh :
  29503. * ```javascript
  29504. * function(mesh) { // do things
  29505. * return; }
  29506. * ```
  29507. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29508. */
  29509. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  29510. var options = {
  29511. width: width,
  29512. height: height,
  29513. subdivisions: subdivisions,
  29514. minHeight: minHeight,
  29515. maxHeight: maxHeight,
  29516. updatable: updatable,
  29517. onReady: onReady
  29518. };
  29519. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  29520. };
  29521. /**
  29522. * Creates a tube mesh.
  29523. * 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.
  29524. * Please consider using the same method from the MeshBuilder class instead.
  29525. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  29526. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  29527. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  29528. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  29529. * 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.
  29530. * It must return a radius value (positive float) :
  29531. * ```javascript
  29532. * var radiusFunction = function(i, distance) {
  29533. * // do things
  29534. * return radius; }
  29535. * ```
  29536. * 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
  29537. * 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
  29538. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29539. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29540. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29541. */
  29542. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  29543. var options = {
  29544. path: path,
  29545. radius: radius,
  29546. tessellation: tessellation,
  29547. radiusFunction: radiusFunction,
  29548. arc: 1,
  29549. cap: cap,
  29550. updatable: updatable,
  29551. sideOrientation: sideOrientation,
  29552. instance: instance
  29553. };
  29554. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  29555. };
  29556. /**
  29557. * Creates a polyhedron mesh.
  29558. * Please consider using the same method from the MeshBuilder class instead.
  29559. * 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
  29560. * to choose the wanted type.
  29561. * The parameter `size` (positive float, default 1) sets the polygon size.
  29562. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  29563. * 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`.
  29564. * 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
  29565. * 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)`).
  29566. * 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
  29567. * 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.
  29568. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29569. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29570. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29571. */
  29572. Mesh.CreatePolyhedron = function (name, options, scene) {
  29573. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  29574. };
  29575. /**
  29576. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  29577. * Please consider using the same method from the MeshBuilder class instead.
  29578. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  29579. * 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`).
  29580. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  29581. * 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.
  29582. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  29583. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  29584. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  29585. */
  29586. Mesh.CreateIcoSphere = function (name, options, scene) {
  29587. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  29588. };
  29589. /**
  29590. * Creates a decal mesh.
  29591. * Please consider using the same method from the MeshBuilder class instead.
  29592. * 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.
  29593. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  29594. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  29595. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  29596. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  29597. */
  29598. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  29599. var options = {
  29600. position: position,
  29601. normal: normal,
  29602. size: size,
  29603. angle: angle
  29604. };
  29605. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  29606. };
  29607. // Skeletons
  29608. /**
  29609. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29610. */
  29611. Mesh.prototype.setPositionsForCPUSkinning = function () {
  29612. if (!this._sourcePositions) {
  29613. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29614. if (!source) {
  29615. return this._sourcePositions;
  29616. }
  29617. this._sourcePositions = new Float32Array(source);
  29618. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  29619. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  29620. }
  29621. }
  29622. return this._sourcePositions;
  29623. };
  29624. /**
  29625. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  29626. */
  29627. Mesh.prototype.setNormalsForCPUSkinning = function () {
  29628. if (!this._sourceNormals) {
  29629. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29630. if (!source) {
  29631. return this._sourceNormals;
  29632. }
  29633. this._sourceNormals = new Float32Array(source);
  29634. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  29635. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  29636. }
  29637. }
  29638. return this._sourceNormals;
  29639. };
  29640. /**
  29641. * Updates the vertex buffer by applying transformation from the bones.
  29642. * Returns the Mesh.
  29643. *
  29644. * @param {skeleton} skeleton to apply
  29645. */
  29646. Mesh.prototype.applySkeleton = function (skeleton) {
  29647. if (!this.geometry) {
  29648. return this;
  29649. }
  29650. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  29651. return this;
  29652. }
  29653. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  29654. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29655. return this;
  29656. }
  29657. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29658. return this;
  29659. }
  29660. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29661. return this;
  29662. }
  29663. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29664. return this;
  29665. }
  29666. if (!this._sourcePositions) {
  29667. var submeshes = this.subMeshes.slice();
  29668. this.setPositionsForCPUSkinning();
  29669. this.subMeshes = submeshes;
  29670. }
  29671. if (!this._sourceNormals) {
  29672. this.setNormalsForCPUSkinning();
  29673. }
  29674. // positionsData checks for not being Float32Array will only pass at most once
  29675. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29676. if (!positionsData) {
  29677. return this;
  29678. }
  29679. if (!(positionsData instanceof Float32Array)) {
  29680. positionsData = new Float32Array(positionsData);
  29681. }
  29682. // normalsData checks for not being Float32Array will only pass at most once
  29683. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29684. if (!normalsData) {
  29685. return this;
  29686. }
  29687. if (!(normalsData instanceof Float32Array)) {
  29688. normalsData = new Float32Array(normalsData);
  29689. }
  29690. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  29691. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  29692. if (!matricesWeightsData || !matricesIndicesData) {
  29693. return this;
  29694. }
  29695. var needExtras = this.numBoneInfluencers > 4;
  29696. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  29697. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  29698. var skeletonMatrices = skeleton.getTransformMatrices(this);
  29699. var tempVector3 = BABYLON.Vector3.Zero();
  29700. var finalMatrix = new BABYLON.Matrix();
  29701. var tempMatrix = new BABYLON.Matrix();
  29702. var matWeightIdx = 0;
  29703. var inf;
  29704. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  29705. var weight;
  29706. for (inf = 0; inf < 4; inf++) {
  29707. weight = matricesWeightsData[matWeightIdx + inf];
  29708. if (weight > 0) {
  29709. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  29710. finalMatrix.addToSelf(tempMatrix);
  29711. }
  29712. else
  29713. break;
  29714. }
  29715. if (needExtras) {
  29716. for (inf = 0; inf < 4; inf++) {
  29717. weight = matricesWeightsExtraData[matWeightIdx + inf];
  29718. if (weight > 0) {
  29719. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  29720. finalMatrix.addToSelf(tempMatrix);
  29721. }
  29722. else
  29723. break;
  29724. }
  29725. }
  29726. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  29727. tempVector3.toArray(positionsData, index);
  29728. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  29729. tempVector3.toArray(normalsData, index);
  29730. finalMatrix.reset();
  29731. }
  29732. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  29733. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  29734. return this;
  29735. };
  29736. // Tools
  29737. /**
  29738. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  29739. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  29740. */
  29741. Mesh.MinMax = function (meshes) {
  29742. var minVector = null;
  29743. var maxVector = null;
  29744. meshes.forEach(function (mesh, index, array) {
  29745. var boundingInfo = mesh.getBoundingInfo();
  29746. var boundingBox = boundingInfo.boundingBox;
  29747. if (!minVector || !maxVector) {
  29748. minVector = boundingBox.minimumWorld;
  29749. maxVector = boundingBox.maximumWorld;
  29750. }
  29751. else {
  29752. minVector.minimizeInPlace(boundingBox.minimumWorld);
  29753. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  29754. }
  29755. });
  29756. if (!minVector || !maxVector) {
  29757. return {
  29758. min: BABYLON.Vector3.Zero(),
  29759. max: BABYLON.Vector3.Zero()
  29760. };
  29761. }
  29762. return {
  29763. min: minVector,
  29764. max: maxVector
  29765. };
  29766. };
  29767. /**
  29768. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  29769. */
  29770. Mesh.Center = function (meshesOrMinMaxVector) {
  29771. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  29772. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  29773. };
  29774. /**
  29775. * Merge the array of meshes into a single mesh for performance reasons.
  29776. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  29777. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  29778. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  29779. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  29780. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  29781. */
  29782. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  29783. if (disposeSource === void 0) { disposeSource = true; }
  29784. var index;
  29785. if (!allow32BitsIndices) {
  29786. var totalVertices = 0;
  29787. // Counting vertices
  29788. for (index = 0; index < meshes.length; index++) {
  29789. if (meshes[index]) {
  29790. totalVertices += meshes[index].getTotalVertices();
  29791. if (totalVertices > 65536) {
  29792. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  29793. return null;
  29794. }
  29795. }
  29796. }
  29797. }
  29798. // Merge
  29799. var vertexData = null;
  29800. var otherVertexData;
  29801. var indiceArray = new Array();
  29802. var source = null;
  29803. for (index = 0; index < meshes.length; index++) {
  29804. if (meshes[index]) {
  29805. meshes[index].computeWorldMatrix(true);
  29806. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  29807. otherVertexData.transform(meshes[index].getWorldMatrix());
  29808. if (vertexData) {
  29809. vertexData.merge(otherVertexData);
  29810. }
  29811. else {
  29812. vertexData = otherVertexData;
  29813. source = meshes[index];
  29814. }
  29815. if (subdivideWithSubMeshes) {
  29816. indiceArray.push(meshes[index].getTotalIndices());
  29817. }
  29818. }
  29819. }
  29820. source = source;
  29821. if (!meshSubclass) {
  29822. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  29823. }
  29824. vertexData.applyToMesh(meshSubclass);
  29825. // Setting properties
  29826. meshSubclass.material = source.material;
  29827. meshSubclass.checkCollisions = source.checkCollisions;
  29828. // Cleaning
  29829. if (disposeSource) {
  29830. for (index = 0; index < meshes.length; index++) {
  29831. if (meshes[index]) {
  29832. meshes[index].dispose();
  29833. }
  29834. }
  29835. }
  29836. // Subdivide
  29837. if (subdivideWithSubMeshes) {
  29838. //-- Suppresions du submesh global
  29839. meshSubclass.releaseSubMeshes();
  29840. index = 0;
  29841. var offset = 0;
  29842. //-- aplique la subdivision en fonction du tableau d'indices
  29843. while (index < indiceArray.length) {
  29844. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  29845. offset += indiceArray[index];
  29846. index++;
  29847. }
  29848. }
  29849. return meshSubclass;
  29850. };
  29851. // Consts
  29852. Mesh._FRONTSIDE = 0;
  29853. Mesh._BACKSIDE = 1;
  29854. Mesh._DOUBLESIDE = 2;
  29855. Mesh._DEFAULTSIDE = 0;
  29856. Mesh._NO_CAP = 0;
  29857. Mesh._CAP_START = 1;
  29858. Mesh._CAP_END = 2;
  29859. Mesh._CAP_ALL = 3;
  29860. return Mesh;
  29861. }(BABYLON.AbstractMesh));
  29862. BABYLON.Mesh = Mesh;
  29863. })(BABYLON || (BABYLON = {}));
  29864. //# sourceMappingURL=babylon.mesh.js.map
  29865. var BABYLON;
  29866. (function (BABYLON) {
  29867. var BaseSubMesh = /** @class */ (function () {
  29868. function BaseSubMesh() {
  29869. }
  29870. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  29871. get: function () {
  29872. return this._materialEffect;
  29873. },
  29874. enumerable: true,
  29875. configurable: true
  29876. });
  29877. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  29878. if (defines === void 0) { defines = null; }
  29879. if (this._materialEffect === effect) {
  29880. if (!effect) {
  29881. this._materialDefines = null;
  29882. }
  29883. return;
  29884. }
  29885. this._materialDefines = defines;
  29886. this._materialEffect = effect;
  29887. };
  29888. return BaseSubMesh;
  29889. }());
  29890. BABYLON.BaseSubMesh = BaseSubMesh;
  29891. var SubMesh = /** @class */ (function (_super) {
  29892. __extends(SubMesh, _super);
  29893. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29894. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29895. var _this = _super.call(this) || this;
  29896. _this.materialIndex = materialIndex;
  29897. _this.verticesStart = verticesStart;
  29898. _this.verticesCount = verticesCount;
  29899. _this.indexStart = indexStart;
  29900. _this.indexCount = indexCount;
  29901. _this._renderId = 0;
  29902. _this._mesh = mesh;
  29903. _this._renderingMesh = renderingMesh || mesh;
  29904. mesh.subMeshes.push(_this);
  29905. _this._trianglePlanes = [];
  29906. _this._id = mesh.subMeshes.length - 1;
  29907. if (createBoundingBox) {
  29908. _this.refreshBoundingInfo();
  29909. mesh.computeWorldMatrix(true);
  29910. }
  29911. return _this;
  29912. }
  29913. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  29914. if (createBoundingBox === void 0) { createBoundingBox = true; }
  29915. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  29916. };
  29917. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  29918. get: function () {
  29919. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  29920. },
  29921. enumerable: true,
  29922. configurable: true
  29923. });
  29924. /**
  29925. * Returns the submesh BoudingInfo object.
  29926. */
  29927. SubMesh.prototype.getBoundingInfo = function () {
  29928. if (this.IsGlobal) {
  29929. return this._mesh.getBoundingInfo();
  29930. }
  29931. return this._boundingInfo;
  29932. };
  29933. /**
  29934. * Sets the submesh BoundingInfo.
  29935. * Return the SubMesh.
  29936. */
  29937. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  29938. this._boundingInfo = boundingInfo;
  29939. return this;
  29940. };
  29941. /**
  29942. * Returns the mesh of the current submesh.
  29943. */
  29944. SubMesh.prototype.getMesh = function () {
  29945. return this._mesh;
  29946. };
  29947. /**
  29948. * Returns the rendering mesh of the submesh.
  29949. */
  29950. SubMesh.prototype.getRenderingMesh = function () {
  29951. return this._renderingMesh;
  29952. };
  29953. /**
  29954. * Returns the submesh material.
  29955. */
  29956. SubMesh.prototype.getMaterial = function () {
  29957. var rootMaterial = this._renderingMesh.material;
  29958. if (rootMaterial === null || rootMaterial === undefined) {
  29959. return this._mesh.getScene().defaultMaterial;
  29960. }
  29961. else if (rootMaterial.getSubMaterial) {
  29962. var multiMaterial = rootMaterial;
  29963. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  29964. if (this._currentMaterial !== effectiveMaterial) {
  29965. this._currentMaterial = effectiveMaterial;
  29966. this._materialDefines = null;
  29967. }
  29968. return effectiveMaterial;
  29969. }
  29970. return rootMaterial;
  29971. };
  29972. // Methods
  29973. /**
  29974. * Sets a new updated BoundingInfo object to the submesh.
  29975. * Returns the SubMesh.
  29976. */
  29977. SubMesh.prototype.refreshBoundingInfo = function () {
  29978. this._lastColliderWorldVertices = null;
  29979. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  29980. return this;
  29981. }
  29982. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29983. if (!data) {
  29984. this._boundingInfo = this._mesh.getBoundingInfo();
  29985. return this;
  29986. }
  29987. var indices = this._renderingMesh.getIndices();
  29988. var extend;
  29989. //is this the only submesh?
  29990. if (this.indexStart === 0 && this.indexCount === indices.length) {
  29991. var boundingInfo = this._renderingMesh.getBoundingInfo();
  29992. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  29993. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  29994. }
  29995. else {
  29996. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  29997. }
  29998. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  29999. return this;
  30000. };
  30001. SubMesh.prototype._checkCollision = function (collider) {
  30002. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30003. return boundingInfo._checkCollision(collider);
  30004. };
  30005. /**
  30006. * Updates the submesh BoundingInfo.
  30007. * Returns the Submesh.
  30008. */
  30009. SubMesh.prototype.updateBoundingInfo = function (world) {
  30010. var boundingInfo = this.getBoundingInfo();
  30011. if (!boundingInfo) {
  30012. this.refreshBoundingInfo();
  30013. boundingInfo = this.getBoundingInfo();
  30014. }
  30015. boundingInfo.update(world);
  30016. return this;
  30017. };
  30018. /**
  30019. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30020. * Boolean returned.
  30021. */
  30022. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30023. var boundingInfo = this.getBoundingInfo();
  30024. if (!boundingInfo) {
  30025. return false;
  30026. }
  30027. return boundingInfo.isInFrustum(frustumPlanes);
  30028. };
  30029. /**
  30030. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30031. * Boolean returned.
  30032. */
  30033. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30034. var boundingInfo = this.getBoundingInfo();
  30035. if (!boundingInfo) {
  30036. return false;
  30037. }
  30038. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30039. };
  30040. /**
  30041. * Renders the submesh.
  30042. * Returns it.
  30043. */
  30044. SubMesh.prototype.render = function (enableAlphaMode) {
  30045. this._renderingMesh.render(this, enableAlphaMode);
  30046. return this;
  30047. };
  30048. /**
  30049. * Returns a new Index Buffer.
  30050. * Type returned : WebGLBuffer.
  30051. */
  30052. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30053. if (!this._linesIndexBuffer) {
  30054. var linesIndices = [];
  30055. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30056. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30057. }
  30058. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30059. this.linesIndexCount = linesIndices.length;
  30060. }
  30061. return this._linesIndexBuffer;
  30062. };
  30063. /**
  30064. * True is the passed Ray intersects the submesh bounding box.
  30065. * Boolean returned.
  30066. */
  30067. SubMesh.prototype.canIntersects = function (ray) {
  30068. var boundingInfo = this.getBoundingInfo();
  30069. if (!boundingInfo) {
  30070. return false;
  30071. }
  30072. return ray.intersectsBox(boundingInfo.boundingBox);
  30073. };
  30074. /**
  30075. * Returns an object IntersectionInfo.
  30076. */
  30077. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30078. var intersectInfo = null;
  30079. // LineMesh first as it's also a Mesh...
  30080. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  30081. var lineMesh = this._mesh;
  30082. // Line test
  30083. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  30084. var p0 = positions[indices[index]];
  30085. var p1 = positions[indices[index + 1]];
  30086. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  30087. if (length < 0) {
  30088. continue;
  30089. }
  30090. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  30091. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  30092. if (fastCheck) {
  30093. break;
  30094. }
  30095. }
  30096. }
  30097. }
  30098. else {
  30099. // Triangles test
  30100. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30101. var p0 = positions[indices[index]];
  30102. var p1 = positions[indices[index + 1]];
  30103. var p2 = positions[indices[index + 2]];
  30104. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  30105. if (currentIntersectInfo) {
  30106. if (currentIntersectInfo.distance < 0) {
  30107. continue;
  30108. }
  30109. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  30110. intersectInfo = currentIntersectInfo;
  30111. intersectInfo.faceId = index / 3;
  30112. if (fastCheck) {
  30113. break;
  30114. }
  30115. }
  30116. }
  30117. }
  30118. }
  30119. return intersectInfo;
  30120. };
  30121. SubMesh.prototype._rebuild = function () {
  30122. if (this._linesIndexBuffer) {
  30123. this._linesIndexBuffer = null;
  30124. }
  30125. };
  30126. // Clone
  30127. /**
  30128. * Creates a new Submesh from the passed Mesh.
  30129. */
  30130. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  30131. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  30132. if (!this.IsGlobal) {
  30133. var boundingInfo = this.getBoundingInfo();
  30134. if (!boundingInfo) {
  30135. return result;
  30136. }
  30137. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  30138. }
  30139. return result;
  30140. };
  30141. // Dispose
  30142. /**
  30143. * Disposes the Submesh.
  30144. * Returns nothing.
  30145. */
  30146. SubMesh.prototype.dispose = function () {
  30147. if (this._linesIndexBuffer) {
  30148. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  30149. this._linesIndexBuffer = null;
  30150. }
  30151. // Remove from mesh
  30152. var index = this._mesh.subMeshes.indexOf(this);
  30153. this._mesh.subMeshes.splice(index, 1);
  30154. };
  30155. // Statics
  30156. /**
  30157. * Creates a new Submesh from the passed parameters :
  30158. * - materialIndex (integer) : the index of the main mesh material.
  30159. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  30160. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  30161. * - mesh (Mesh) : the main mesh to create the submesh from.
  30162. * - renderingMesh (optional Mesh) : rendering mesh.
  30163. */
  30164. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  30165. var minVertexIndex = Number.MAX_VALUE;
  30166. var maxVertexIndex = -Number.MAX_VALUE;
  30167. renderingMesh = (renderingMesh || mesh);
  30168. var indices = renderingMesh.getIndices();
  30169. for (var index = startIndex; index < startIndex + indexCount; index++) {
  30170. var vertexIndex = indices[index];
  30171. if (vertexIndex < minVertexIndex)
  30172. minVertexIndex = vertexIndex;
  30173. if (vertexIndex > maxVertexIndex)
  30174. maxVertexIndex = vertexIndex;
  30175. }
  30176. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  30177. };
  30178. return SubMesh;
  30179. }(BaseSubMesh));
  30180. BABYLON.SubMesh = SubMesh;
  30181. })(BABYLON || (BABYLON = {}));
  30182. //# sourceMappingURL=babylon.subMesh.js.map
  30183. var __assign = (this && this.__assign) || Object.assign || function(t) {
  30184. for (var s, i = 1, n = arguments.length; i < n; i++) {
  30185. s = arguments[i];
  30186. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  30187. t[p] = s[p];
  30188. }
  30189. return t;
  30190. };
  30191. var BABYLON;
  30192. (function (BABYLON) {
  30193. /**
  30194. * Manages the defines for the Material.
  30195. */
  30196. var MaterialDefines = /** @class */ (function () {
  30197. function MaterialDefines() {
  30198. this._isDirty = true;
  30199. this._areLightsDirty = true;
  30200. this._areAttributesDirty = true;
  30201. this._areTexturesDirty = true;
  30202. this._areFresnelDirty = true;
  30203. this._areMiscDirty = true;
  30204. this._areImageProcessingDirty = true;
  30205. this._normals = false;
  30206. this._uvs = false;
  30207. this._needNormals = false;
  30208. this._needUVs = false;
  30209. }
  30210. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  30211. /**
  30212. * Specifies if the material needs to be re-calculated.
  30213. */
  30214. get: function () {
  30215. return this._isDirty;
  30216. },
  30217. enumerable: true,
  30218. configurable: true
  30219. });
  30220. /**
  30221. * Marks the material to indicate that it has been re-calculated.
  30222. */
  30223. MaterialDefines.prototype.markAsProcessed = function () {
  30224. this._isDirty = false;
  30225. this._areAttributesDirty = false;
  30226. this._areTexturesDirty = false;
  30227. this._areFresnelDirty = false;
  30228. this._areLightsDirty = false;
  30229. this._areMiscDirty = false;
  30230. this._areImageProcessingDirty = false;
  30231. };
  30232. /**
  30233. * Marks the material to indicate that it needs to be re-calculated.
  30234. */
  30235. MaterialDefines.prototype.markAsUnprocessed = function () {
  30236. this._isDirty = true;
  30237. };
  30238. /**
  30239. * Marks the material to indicate all of its defines need to be re-calculated.
  30240. */
  30241. MaterialDefines.prototype.markAllAsDirty = function () {
  30242. this._areTexturesDirty = true;
  30243. this._areAttributesDirty = true;
  30244. this._areLightsDirty = true;
  30245. this._areFresnelDirty = true;
  30246. this._areMiscDirty = true;
  30247. this._areImageProcessingDirty = true;
  30248. this._isDirty = true;
  30249. };
  30250. /**
  30251. * Marks the material to indicate that image processing needs to be re-calculated.
  30252. */
  30253. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  30254. this._areImageProcessingDirty = true;
  30255. this._isDirty = true;
  30256. };
  30257. /**
  30258. * Marks the material to indicate the lights need to be re-calculated.
  30259. */
  30260. MaterialDefines.prototype.markAsLightDirty = function () {
  30261. this._areLightsDirty = true;
  30262. this._isDirty = true;
  30263. };
  30264. /**
  30265. * Marks the attribute state as changed.
  30266. */
  30267. MaterialDefines.prototype.markAsAttributesDirty = function () {
  30268. this._areAttributesDirty = true;
  30269. this._isDirty = true;
  30270. };
  30271. /**
  30272. * Marks the texture state as changed.
  30273. */
  30274. MaterialDefines.prototype.markAsTexturesDirty = function () {
  30275. this._areTexturesDirty = true;
  30276. this._isDirty = true;
  30277. };
  30278. /**
  30279. * Marks the fresnel state as changed.
  30280. */
  30281. MaterialDefines.prototype.markAsFresnelDirty = function () {
  30282. this._areFresnelDirty = true;
  30283. this._isDirty = true;
  30284. };
  30285. /**
  30286. * Marks the misc state as changed.
  30287. */
  30288. MaterialDefines.prototype.markAsMiscDirty = function () {
  30289. this._areMiscDirty = true;
  30290. this._isDirty = true;
  30291. };
  30292. /**
  30293. * Rebuilds the material defines.
  30294. */
  30295. MaterialDefines.prototype.rebuild = function () {
  30296. if (this._keys) {
  30297. delete this._keys;
  30298. }
  30299. this._keys = [];
  30300. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  30301. var key = _a[_i];
  30302. if (key[0] === "_") {
  30303. continue;
  30304. }
  30305. this._keys.push(key);
  30306. }
  30307. };
  30308. /**
  30309. * Specifies if two material defines are equal.
  30310. * @param other - A material define instance to compare to.
  30311. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  30312. */
  30313. MaterialDefines.prototype.isEqual = function (other) {
  30314. if (this._keys.length !== other._keys.length) {
  30315. return false;
  30316. }
  30317. for (var index = 0; index < this._keys.length; index++) {
  30318. var prop = this._keys[index];
  30319. if (this[prop] !== other[prop]) {
  30320. return false;
  30321. }
  30322. }
  30323. return true;
  30324. };
  30325. /**
  30326. * Clones this instance's defines to another instance.
  30327. * @param other - material defines to clone values to.
  30328. */
  30329. MaterialDefines.prototype.cloneTo = function (other) {
  30330. if (this._keys.length !== other._keys.length) {
  30331. other._keys = this._keys.slice(0);
  30332. }
  30333. for (var index = 0; index < this._keys.length; index++) {
  30334. var prop = this._keys[index];
  30335. other[prop] = this[prop];
  30336. }
  30337. };
  30338. /**
  30339. * Resets the material define values.
  30340. */
  30341. MaterialDefines.prototype.reset = function () {
  30342. for (var index = 0; index < this._keys.length; index++) {
  30343. var prop = this._keys[index];
  30344. if (typeof (this[prop]) === "number") {
  30345. this[prop] = 0;
  30346. }
  30347. else {
  30348. this[prop] = false;
  30349. }
  30350. }
  30351. };
  30352. /**
  30353. * Converts the material define values to a string.
  30354. * @returns - String of material define information.
  30355. */
  30356. MaterialDefines.prototype.toString = function () {
  30357. var result = "";
  30358. for (var index = 0; index < this._keys.length; index++) {
  30359. var prop = this._keys[index];
  30360. var value = this[prop];
  30361. if (typeof (value) === "number") {
  30362. result += "#define " + prop + " " + this[prop] + "\n";
  30363. }
  30364. else if (value) {
  30365. result += "#define " + prop + "\n";
  30366. }
  30367. }
  30368. return result;
  30369. };
  30370. return MaterialDefines;
  30371. }());
  30372. BABYLON.MaterialDefines = MaterialDefines;
  30373. /**
  30374. * This offers the main features of a material in BJS.
  30375. */
  30376. var Material = /** @class */ (function () {
  30377. /**
  30378. * Creates a material instance.
  30379. * @param name - The name of the material.
  30380. * @param scene - The BJS scene to reference.
  30381. * @param doNotAdd - Specifies if the material should be added to the scene.
  30382. */
  30383. function Material(name, scene, doNotAdd) {
  30384. /**
  30385. * Specifies if the ready state should be checked on each call.
  30386. */
  30387. this.checkReadyOnEveryCall = false;
  30388. /**
  30389. * Specifies if the ready state should be checked once.
  30390. */
  30391. this.checkReadyOnlyOnce = false;
  30392. /**
  30393. * The state of the material.
  30394. */
  30395. this.state = "";
  30396. /**
  30397. * The alpha value of the material.
  30398. */
  30399. this._alpha = 1.0;
  30400. /**
  30401. * Specifies if back face culling is enabled.
  30402. */
  30403. this._backFaceCulling = true;
  30404. /**
  30405. * Specifies if the material should be serialized.
  30406. */
  30407. this.doNotSerialize = false;
  30408. /**
  30409. * Specifies if the effect should be stored on sub meshes.
  30410. */
  30411. this.storeEffectOnSubMeshes = false;
  30412. /**
  30413. * An event triggered when the material is disposed.
  30414. * @type {BABYLON.Observable}
  30415. */
  30416. this.onDisposeObservable = new BABYLON.Observable();
  30417. /**
  30418. * An event triggered when the material is bound.
  30419. * @type {BABYLON.Observable}
  30420. */
  30421. this.onBindObservable = new BABYLON.Observable();
  30422. /**
  30423. * An event triggered when the material is unbound.
  30424. * @type {BABYLON.Observable}
  30425. */
  30426. this.onUnBindObservable = new BABYLON.Observable();
  30427. /**
  30428. * Stores the value of the alpha mode.
  30429. */
  30430. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  30431. /**
  30432. * Stores the state of the need depth pre-pass value.
  30433. */
  30434. this._needDepthPrePass = false;
  30435. /**
  30436. * Specifies if depth writing should be disabled.
  30437. */
  30438. this.disableDepthWrite = false;
  30439. /**
  30440. * Specifies if depth writing should be forced.
  30441. */
  30442. this.forceDepthWrite = false;
  30443. /**
  30444. * Specifies if there should be a separate pass for culling.
  30445. */
  30446. this.separateCullingPass = false;
  30447. /**
  30448. * Stores the state specifing if fog should be enabled.
  30449. */
  30450. this._fogEnabled = true;
  30451. /**
  30452. * Stores the size of points.
  30453. */
  30454. this.pointSize = 1.0;
  30455. /**
  30456. * Stores the z offset value.
  30457. */
  30458. this.zOffset = 0;
  30459. /**
  30460. * Specifies if the material was previously ready.
  30461. */
  30462. this._wasPreviouslyReady = false;
  30463. /**
  30464. * Stores the fill mode state.
  30465. */
  30466. this._fillMode = Material.TriangleFillMode;
  30467. this.name = name;
  30468. this.id = name || BABYLON.Tools.RandomId();
  30469. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30470. if (this._scene.useRightHandedSystem) {
  30471. this.sideOrientation = Material.ClockWiseSideOrientation;
  30472. }
  30473. else {
  30474. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  30475. }
  30476. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  30477. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  30478. if (!doNotAdd) {
  30479. this._scene.materials.push(this);
  30480. }
  30481. }
  30482. Object.defineProperty(Material, "TriangleFillMode", {
  30483. /**
  30484. * Returns the triangle fill mode.
  30485. */
  30486. get: function () {
  30487. return Material._TriangleFillMode;
  30488. },
  30489. enumerable: true,
  30490. configurable: true
  30491. });
  30492. Object.defineProperty(Material, "WireFrameFillMode", {
  30493. /**
  30494. * Returns the wireframe mode.
  30495. */
  30496. get: function () {
  30497. return Material._WireFrameFillMode;
  30498. },
  30499. enumerable: true,
  30500. configurable: true
  30501. });
  30502. Object.defineProperty(Material, "PointFillMode", {
  30503. /**
  30504. * Returns the point fill mode.
  30505. */
  30506. get: function () {
  30507. return Material._PointFillMode;
  30508. },
  30509. enumerable: true,
  30510. configurable: true
  30511. });
  30512. Object.defineProperty(Material, "PointListDrawMode", {
  30513. /**
  30514. * Returns the point list draw mode.
  30515. */
  30516. get: function () {
  30517. return Material._PointListDrawMode;
  30518. },
  30519. enumerable: true,
  30520. configurable: true
  30521. });
  30522. Object.defineProperty(Material, "LineListDrawMode", {
  30523. /**
  30524. * Returns the line list draw mode.
  30525. */
  30526. get: function () {
  30527. return Material._LineListDrawMode;
  30528. },
  30529. enumerable: true,
  30530. configurable: true
  30531. });
  30532. Object.defineProperty(Material, "LineLoopDrawMode", {
  30533. /**
  30534. * Returns the line loop draw mode.
  30535. */
  30536. get: function () {
  30537. return Material._LineLoopDrawMode;
  30538. },
  30539. enumerable: true,
  30540. configurable: true
  30541. });
  30542. Object.defineProperty(Material, "LineStripDrawMode", {
  30543. /**
  30544. * Returns the line strip draw mode.
  30545. */
  30546. get: function () {
  30547. return Material._LineStripDrawMode;
  30548. },
  30549. enumerable: true,
  30550. configurable: true
  30551. });
  30552. Object.defineProperty(Material, "TriangleStripDrawMode", {
  30553. /**
  30554. * Returns the triangle strip draw mode.
  30555. */
  30556. get: function () {
  30557. return Material._TriangleStripDrawMode;
  30558. },
  30559. enumerable: true,
  30560. configurable: true
  30561. });
  30562. Object.defineProperty(Material, "TriangleFanDrawMode", {
  30563. /**
  30564. * Returns the triangle fan draw mode.
  30565. */
  30566. get: function () {
  30567. return Material._TriangleFanDrawMode;
  30568. },
  30569. enumerable: true,
  30570. configurable: true
  30571. });
  30572. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  30573. /**
  30574. * Returns the clock-wise side orientation.
  30575. */
  30576. get: function () {
  30577. return Material._ClockWiseSideOrientation;
  30578. },
  30579. enumerable: true,
  30580. configurable: true
  30581. });
  30582. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  30583. /**
  30584. * Returns the counter clock-wise side orientation.
  30585. */
  30586. get: function () {
  30587. return Material._CounterClockWiseSideOrientation;
  30588. },
  30589. enumerable: true,
  30590. configurable: true
  30591. });
  30592. Object.defineProperty(Material, "TextureDirtyFlag", {
  30593. /**
  30594. * Returns the dirty texture flag value.
  30595. */
  30596. get: function () {
  30597. return Material._TextureDirtyFlag;
  30598. },
  30599. enumerable: true,
  30600. configurable: true
  30601. });
  30602. Object.defineProperty(Material, "LightDirtyFlag", {
  30603. /**
  30604. * Returns the dirty light flag value.
  30605. */
  30606. get: function () {
  30607. return Material._LightDirtyFlag;
  30608. },
  30609. enumerable: true,
  30610. configurable: true
  30611. });
  30612. Object.defineProperty(Material, "FresnelDirtyFlag", {
  30613. /**
  30614. * Returns the dirty fresnel flag value.
  30615. */
  30616. get: function () {
  30617. return Material._FresnelDirtyFlag;
  30618. },
  30619. enumerable: true,
  30620. configurable: true
  30621. });
  30622. Object.defineProperty(Material, "AttributesDirtyFlag", {
  30623. /**
  30624. * Returns the dirty attributes flag value.
  30625. */
  30626. get: function () {
  30627. return Material._AttributesDirtyFlag;
  30628. },
  30629. enumerable: true,
  30630. configurable: true
  30631. });
  30632. Object.defineProperty(Material, "MiscDirtyFlag", {
  30633. /**
  30634. * Returns the dirty misc flag value.
  30635. */
  30636. get: function () {
  30637. return Material._MiscDirtyFlag;
  30638. },
  30639. enumerable: true,
  30640. configurable: true
  30641. });
  30642. Object.defineProperty(Material.prototype, "alpha", {
  30643. /**
  30644. * Gets the alpha value of the material.
  30645. */
  30646. get: function () {
  30647. return this._alpha;
  30648. },
  30649. /**
  30650. * Sets the alpha value of the material.
  30651. */
  30652. set: function (value) {
  30653. if (this._alpha === value) {
  30654. return;
  30655. }
  30656. this._alpha = value;
  30657. this.markAsDirty(Material.MiscDirtyFlag);
  30658. },
  30659. enumerable: true,
  30660. configurable: true
  30661. });
  30662. Object.defineProperty(Material.prototype, "backFaceCulling", {
  30663. /**
  30664. * Gets the back-face culling state.
  30665. */
  30666. get: function () {
  30667. return this._backFaceCulling;
  30668. },
  30669. /**
  30670. * Sets the back-face culling state.
  30671. */
  30672. set: function (value) {
  30673. if (this._backFaceCulling === value) {
  30674. return;
  30675. }
  30676. this._backFaceCulling = value;
  30677. this.markAsDirty(Material.TextureDirtyFlag);
  30678. },
  30679. enumerable: true,
  30680. configurable: true
  30681. });
  30682. Object.defineProperty(Material.prototype, "onDispose", {
  30683. /**
  30684. * Called during a dispose event.
  30685. */
  30686. set: function (callback) {
  30687. if (this._onDisposeObserver) {
  30688. this.onDisposeObservable.remove(this._onDisposeObserver);
  30689. }
  30690. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30691. },
  30692. enumerable: true,
  30693. configurable: true
  30694. });
  30695. Object.defineProperty(Material.prototype, "onBind", {
  30696. /**
  30697. * Called during a bind event.
  30698. */
  30699. set: function (callback) {
  30700. if (this._onBindObserver) {
  30701. this.onBindObservable.remove(this._onBindObserver);
  30702. }
  30703. this._onBindObserver = this.onBindObservable.add(callback);
  30704. },
  30705. enumerable: true,
  30706. configurable: true
  30707. });
  30708. Object.defineProperty(Material.prototype, "alphaMode", {
  30709. /**
  30710. * Gets the value of the alpha mode.
  30711. */
  30712. get: function () {
  30713. return this._alphaMode;
  30714. },
  30715. /**
  30716. * Sets the value of the alpha mode.
  30717. */
  30718. set: function (value) {
  30719. if (this._alphaMode === value) {
  30720. return;
  30721. }
  30722. this._alphaMode = value;
  30723. this.markAsDirty(Material.TextureDirtyFlag);
  30724. },
  30725. enumerable: true,
  30726. configurable: true
  30727. });
  30728. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  30729. /**
  30730. * Gets the depth pre-pass value.
  30731. */
  30732. get: function () {
  30733. return this._needDepthPrePass;
  30734. },
  30735. /**
  30736. * Sets the need depth pre-pass value.
  30737. */
  30738. set: function (value) {
  30739. if (this._needDepthPrePass === value) {
  30740. return;
  30741. }
  30742. this._needDepthPrePass = value;
  30743. if (this._needDepthPrePass) {
  30744. this.checkReadyOnEveryCall = true;
  30745. }
  30746. },
  30747. enumerable: true,
  30748. configurable: true
  30749. });
  30750. Object.defineProperty(Material.prototype, "fogEnabled", {
  30751. /**
  30752. * Gets the value of the fog enabled state.
  30753. */
  30754. get: function () {
  30755. return this._fogEnabled;
  30756. },
  30757. /**
  30758. * Sets the state for enabling fog.
  30759. */
  30760. set: function (value) {
  30761. if (this._fogEnabled === value) {
  30762. return;
  30763. }
  30764. this._fogEnabled = value;
  30765. this.markAsDirty(Material.MiscDirtyFlag);
  30766. },
  30767. enumerable: true,
  30768. configurable: true
  30769. });
  30770. Object.defineProperty(Material.prototype, "wireframe", {
  30771. /**
  30772. * Gets a value specifying if wireframe mode is enabled.
  30773. */
  30774. get: function () {
  30775. return this._fillMode === Material.WireFrameFillMode;
  30776. },
  30777. /**
  30778. * Sets the state of wireframe mode.
  30779. */
  30780. set: function (value) {
  30781. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  30782. },
  30783. enumerable: true,
  30784. configurable: true
  30785. });
  30786. Object.defineProperty(Material.prototype, "pointsCloud", {
  30787. /**
  30788. * Gets the value specifying if point clouds are enabled.
  30789. */
  30790. get: function () {
  30791. return this._fillMode === Material.PointFillMode;
  30792. },
  30793. /**
  30794. * Sets the state of point cloud mode.
  30795. */
  30796. set: function (value) {
  30797. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  30798. },
  30799. enumerable: true,
  30800. configurable: true
  30801. });
  30802. Object.defineProperty(Material.prototype, "fillMode", {
  30803. /**
  30804. * Gets the material fill mode.
  30805. */
  30806. get: function () {
  30807. return this._fillMode;
  30808. },
  30809. /**
  30810. * Sets the material fill mode.
  30811. */
  30812. set: function (value) {
  30813. if (this._fillMode === value) {
  30814. return;
  30815. }
  30816. this._fillMode = value;
  30817. this.markAsDirty(Material.MiscDirtyFlag);
  30818. },
  30819. enumerable: true,
  30820. configurable: true
  30821. });
  30822. /**
  30823. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30824. * subclasses should override adding information pertainent to themselves.
  30825. * @returns - String with material information.
  30826. */
  30827. Material.prototype.toString = function (fullDetails) {
  30828. var ret = "Name: " + this.name;
  30829. if (fullDetails) {
  30830. }
  30831. return ret;
  30832. };
  30833. /**
  30834. * Gets the class name of the material.
  30835. * @returns - String with the class name of the material.
  30836. */
  30837. Material.prototype.getClassName = function () {
  30838. return "Material";
  30839. };
  30840. Object.defineProperty(Material.prototype, "isFrozen", {
  30841. /**
  30842. * Specifies if updates for the material been locked.
  30843. */
  30844. get: function () {
  30845. return this.checkReadyOnlyOnce;
  30846. },
  30847. enumerable: true,
  30848. configurable: true
  30849. });
  30850. /**
  30851. * Locks updates for the material.
  30852. */
  30853. Material.prototype.freeze = function () {
  30854. this.checkReadyOnlyOnce = true;
  30855. };
  30856. /**
  30857. * Unlocks updates for the material.
  30858. */
  30859. Material.prototype.unfreeze = function () {
  30860. this.checkReadyOnlyOnce = false;
  30861. };
  30862. /**
  30863. * Specifies if the material is ready to be used.
  30864. * @param mesh - BJS mesh.
  30865. * @param useInstances - Specifies if instances should be used.
  30866. * @returns - Boolean indicating if the material is ready to be used.
  30867. */
  30868. Material.prototype.isReady = function (mesh, useInstances) {
  30869. return true;
  30870. };
  30871. /**
  30872. * Specifies that the submesh is ready to be used.
  30873. * @param mesh - BJS mesh.
  30874. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  30875. * @param useInstances - Specifies that instances should be used.
  30876. * @returns - boolean indicating that the submesh is ready or not.
  30877. */
  30878. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30879. return false;
  30880. };
  30881. /**
  30882. * Returns the material effect.
  30883. * @returns - Nullable material effect.
  30884. */
  30885. Material.prototype.getEffect = function () {
  30886. return this._effect;
  30887. };
  30888. /**
  30889. * Returns the BJS scene.
  30890. * @returns - BJS Scene.
  30891. */
  30892. Material.prototype.getScene = function () {
  30893. return this._scene;
  30894. };
  30895. /**
  30896. * Specifies if the material will require alpha blending
  30897. * @returns - Boolean specifying if alpha blending is needed.
  30898. */
  30899. Material.prototype.needAlphaBlending = function () {
  30900. return (this.alpha < 1.0);
  30901. };
  30902. /**
  30903. * Specifies if the mesh will require alpha blending.
  30904. * @param mesh - BJS mesh.
  30905. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  30906. */
  30907. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  30908. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  30909. };
  30910. /**
  30911. * Specifies if this material should be rendered in alpha test mode.
  30912. * @returns - Boolean specifying if an alpha test is needed.
  30913. */
  30914. Material.prototype.needAlphaTesting = function () {
  30915. return false;
  30916. };
  30917. /**
  30918. * Gets the texture used for the alpha test.
  30919. * @returns - Nullable alpha test texture.
  30920. */
  30921. Material.prototype.getAlphaTestTexture = function () {
  30922. return null;
  30923. };
  30924. /**
  30925. * Marks the material to indicate that it needs to be re-calculated.
  30926. */
  30927. Material.prototype.markDirty = function () {
  30928. this._wasPreviouslyReady = false;
  30929. };
  30930. Material.prototype._preBind = function (effect, overrideOrientation) {
  30931. if (overrideOrientation === void 0) { overrideOrientation = null; }
  30932. var engine = this._scene.getEngine();
  30933. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  30934. var reverse = orientation === Material.ClockWiseSideOrientation;
  30935. engine.enableEffect(effect ? effect : this._effect);
  30936. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  30937. return reverse;
  30938. };
  30939. /**
  30940. * Binds the material to the mesh.
  30941. * @param world - World transformation matrix.
  30942. * @param mesh - Mesh to bind the material to.
  30943. */
  30944. Material.prototype.bind = function (world, mesh) {
  30945. };
  30946. /**
  30947. * Binds the submesh to the material.
  30948. * @param world - World transformation matrix.
  30949. * @param mesh - Mesh containing the submesh.
  30950. * @param subMesh - Submesh to bind the material to.
  30951. */
  30952. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30953. };
  30954. /**
  30955. * Binds the world matrix to the material.
  30956. * @param world - World transformation matrix.
  30957. */
  30958. Material.prototype.bindOnlyWorldMatrix = function (world) {
  30959. };
  30960. /**
  30961. * Binds the scene's uniform buffer to the effect.
  30962. * @param effect - Effect to bind to the scene uniform buffer.
  30963. * @param sceneUbo - Scene uniform buffer.
  30964. */
  30965. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  30966. sceneUbo.bindToEffect(effect, "Scene");
  30967. };
  30968. /**
  30969. * Binds the view matrix to the effect.
  30970. * @param effect - Effect to bind the view matrix to.
  30971. */
  30972. Material.prototype.bindView = function (effect) {
  30973. if (!this._useUBO) {
  30974. effect.setMatrix("view", this.getScene().getViewMatrix());
  30975. }
  30976. else {
  30977. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30978. }
  30979. };
  30980. /**
  30981. * Binds the view projection matrix to the effect.
  30982. * @param effect - Effect to bind the view projection matrix to.
  30983. */
  30984. Material.prototype.bindViewProjection = function (effect) {
  30985. if (!this._useUBO) {
  30986. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  30987. }
  30988. else {
  30989. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  30990. }
  30991. };
  30992. /**
  30993. * Specifies if material alpha testing should be turned on for the mesh.
  30994. * @param mesh - BJS mesh.
  30995. */
  30996. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  30997. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  30998. };
  30999. /**
  31000. * Processes to execute after binding the material to a mesh.
  31001. * @param mesh - BJS mesh.
  31002. */
  31003. Material.prototype._afterBind = function (mesh) {
  31004. this._scene._cachedMaterial = this;
  31005. if (mesh) {
  31006. this._scene._cachedVisibility = mesh.visibility;
  31007. }
  31008. else {
  31009. this._scene._cachedVisibility = 1;
  31010. }
  31011. if (mesh) {
  31012. this.onBindObservable.notifyObservers(mesh);
  31013. }
  31014. if (this.disableDepthWrite) {
  31015. var engine = this._scene.getEngine();
  31016. this._cachedDepthWriteState = engine.getDepthWrite();
  31017. engine.setDepthWrite(false);
  31018. }
  31019. };
  31020. /**
  31021. * Unbinds the material from the mesh.
  31022. */
  31023. Material.prototype.unbind = function () {
  31024. this.onUnBindObservable.notifyObservers(this);
  31025. if (this.disableDepthWrite) {
  31026. var engine = this._scene.getEngine();
  31027. engine.setDepthWrite(this._cachedDepthWriteState);
  31028. }
  31029. };
  31030. /**
  31031. * Gets the active textures from the material.
  31032. * @returns - Array of textures.
  31033. */
  31034. Material.prototype.getActiveTextures = function () {
  31035. return [];
  31036. };
  31037. /**
  31038. * Specifies if the material uses a texture.
  31039. * @param texture - Texture to check against the material.
  31040. * @returns - Boolean specifying if the material uses the texture.
  31041. */
  31042. Material.prototype.hasTexture = function (texture) {
  31043. return false;
  31044. };
  31045. /**
  31046. * Makes a duplicate of the material, and gives it a new name.
  31047. * @param name - Name to call the duplicated material.
  31048. * @returns - Nullable cloned material
  31049. */
  31050. Material.prototype.clone = function (name) {
  31051. return null;
  31052. };
  31053. /**
  31054. * Gets the meshes bound to the material.
  31055. * @returns - Array of meshes bound to the material.
  31056. */
  31057. Material.prototype.getBindedMeshes = function () {
  31058. var result = new Array();
  31059. for (var index = 0; index < this._scene.meshes.length; index++) {
  31060. var mesh = this._scene.meshes[index];
  31061. if (mesh.material === this) {
  31062. result.push(mesh);
  31063. }
  31064. }
  31065. return result;
  31066. };
  31067. /**
  31068. * Force shader compilation
  31069. * @param mesh - BJS mesh.
  31070. * @param onCompiled - function to execute once the material is compiled.
  31071. * @param options - options to pass to this function.
  31072. */
  31073. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  31074. var _this = this;
  31075. var localOptions = __assign({ clipPlane: false }, options);
  31076. var subMesh = new BABYLON.BaseSubMesh();
  31077. var scene = this.getScene();
  31078. var checkReady = function () {
  31079. if (!_this._scene || !_this._scene.getEngine()) {
  31080. return;
  31081. }
  31082. if (subMesh._materialDefines) {
  31083. subMesh._materialDefines._renderId = -1;
  31084. }
  31085. var clipPlaneState = scene.clipPlane;
  31086. if (localOptions.clipPlane) {
  31087. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  31088. }
  31089. if (_this.storeEffectOnSubMeshes) {
  31090. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  31091. if (onCompiled) {
  31092. onCompiled(_this);
  31093. }
  31094. }
  31095. else {
  31096. setTimeout(checkReady, 16);
  31097. }
  31098. }
  31099. else {
  31100. if (_this.isReady(mesh)) {
  31101. if (onCompiled) {
  31102. onCompiled(_this);
  31103. }
  31104. }
  31105. else {
  31106. setTimeout(checkReady, 16);
  31107. }
  31108. }
  31109. if (localOptions.clipPlane) {
  31110. scene.clipPlane = clipPlaneState;
  31111. }
  31112. };
  31113. checkReady();
  31114. };
  31115. /**
  31116. * Force shader compilation.
  31117. * @param mesh The mesh that will use this material
  31118. * @param options Additional options for compiling the shaders
  31119. * @returns A promise that resolves when the compilation completes
  31120. */
  31121. Material.prototype.forceCompilationAsync = function (mesh, options) {
  31122. var _this = this;
  31123. return new Promise(function (resolve) {
  31124. _this.forceCompilation(mesh, function () {
  31125. resolve();
  31126. }, options);
  31127. });
  31128. };
  31129. /**
  31130. * Marks a define in the material to indicate that it needs to be re-computed.
  31131. * @param flag - Material define flag.
  31132. */
  31133. Material.prototype.markAsDirty = function (flag) {
  31134. if (flag & Material.TextureDirtyFlag) {
  31135. this._markAllSubMeshesAsTexturesDirty();
  31136. }
  31137. if (flag & Material.LightDirtyFlag) {
  31138. this._markAllSubMeshesAsLightsDirty();
  31139. }
  31140. if (flag & Material.FresnelDirtyFlag) {
  31141. this._markAllSubMeshesAsFresnelDirty();
  31142. }
  31143. if (flag & Material.AttributesDirtyFlag) {
  31144. this._markAllSubMeshesAsAttributesDirty();
  31145. }
  31146. if (flag & Material.MiscDirtyFlag) {
  31147. this._markAllSubMeshesAsMiscDirty();
  31148. }
  31149. this.getScene().resetCachedMaterial();
  31150. };
  31151. /**
  31152. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  31153. * @param func - function which checks material defines against the submeshes.
  31154. */
  31155. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  31156. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  31157. var mesh = _a[_i];
  31158. if (!mesh.subMeshes) {
  31159. continue;
  31160. }
  31161. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  31162. var subMesh = _c[_b];
  31163. if (subMesh.getMaterial() !== this) {
  31164. continue;
  31165. }
  31166. if (!subMesh._materialDefines) {
  31167. continue;
  31168. }
  31169. func(subMesh._materialDefines);
  31170. }
  31171. }
  31172. };
  31173. /**
  31174. * Indicates that image processing needs to be re-calculated for all submeshes.
  31175. */
  31176. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  31177. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  31178. };
  31179. /**
  31180. * Indicates that textures need to be re-calculated for all submeshes.
  31181. */
  31182. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  31183. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  31184. };
  31185. /**
  31186. * Indicates that fresnel needs to be re-calculated for all submeshes.
  31187. */
  31188. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  31189. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  31190. };
  31191. /**
  31192. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  31193. */
  31194. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  31195. this._markAllSubMeshesAsDirty(function (defines) {
  31196. defines.markAsFresnelDirty();
  31197. defines.markAsMiscDirty();
  31198. });
  31199. };
  31200. /**
  31201. * Indicates that lights need to be re-calculated for all submeshes.
  31202. */
  31203. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  31204. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  31205. };
  31206. /**
  31207. * Indicates that attributes need to be re-calculated for all submeshes.
  31208. */
  31209. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  31210. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  31211. };
  31212. /**
  31213. * Indicates that misc needs to be re-calculated for all submeshes.
  31214. */
  31215. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  31216. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  31217. };
  31218. /**
  31219. * Indicates that textures and misc need to be re-calculated for all submeshes.
  31220. */
  31221. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  31222. this._markAllSubMeshesAsDirty(function (defines) {
  31223. defines.markAsTexturesDirty();
  31224. defines.markAsMiscDirty();
  31225. });
  31226. };
  31227. /**
  31228. * Disposes the material.
  31229. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  31230. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  31231. */
  31232. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  31233. // Animations
  31234. this.getScene().stopAnimation(this);
  31235. // Remove from scene
  31236. var index = this._scene.materials.indexOf(this);
  31237. if (index >= 0) {
  31238. this._scene.materials.splice(index, 1);
  31239. }
  31240. // Remove from meshes
  31241. for (index = 0; index < this._scene.meshes.length; index++) {
  31242. var mesh = this._scene.meshes[index];
  31243. if (mesh.material === this) {
  31244. mesh.material = null;
  31245. if (mesh.geometry) {
  31246. var geometry = (mesh.geometry);
  31247. if (this.storeEffectOnSubMeshes) {
  31248. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  31249. var subMesh = _a[_i];
  31250. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  31251. if (forceDisposeEffect && subMesh._materialEffect) {
  31252. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  31253. }
  31254. }
  31255. }
  31256. else {
  31257. geometry._releaseVertexArrayObject(this._effect);
  31258. }
  31259. }
  31260. }
  31261. }
  31262. this._uniformBuffer.dispose();
  31263. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  31264. if (forceDisposeEffect && this._effect) {
  31265. if (!this.storeEffectOnSubMeshes) {
  31266. this._scene.getEngine()._releaseEffect(this._effect);
  31267. }
  31268. this._effect = null;
  31269. }
  31270. // Callback
  31271. this.onDisposeObservable.notifyObservers(this);
  31272. this.onDisposeObservable.clear();
  31273. this.onBindObservable.clear();
  31274. this.onUnBindObservable.clear();
  31275. };
  31276. /**
  31277. * Serializes this material.
  31278. * @returns - serialized material object.
  31279. */
  31280. Material.prototype.serialize = function () {
  31281. return BABYLON.SerializationHelper.Serialize(this);
  31282. };
  31283. /**
  31284. * Creates a MultiMaterial from parse MultiMaterial data.
  31285. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  31286. * @param scene - BJS scene.
  31287. * @returns - MultiMaterial.
  31288. */
  31289. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  31290. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  31291. multiMaterial.id = parsedMultiMaterial.id;
  31292. if (BABYLON.Tags) {
  31293. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  31294. }
  31295. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  31296. var subMatId = parsedMultiMaterial.materials[matIndex];
  31297. if (subMatId) {
  31298. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  31299. }
  31300. else {
  31301. multiMaterial.subMaterials.push(null);
  31302. }
  31303. }
  31304. return multiMaterial;
  31305. };
  31306. /**
  31307. * Creates a material from parsed material data.
  31308. * @param parsedMaterial - Parsed material data.
  31309. * @param scene - BJS scene.
  31310. * @param rootUrl - Root URL containing the material information.
  31311. * @returns - Parsed material.
  31312. */
  31313. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  31314. if (!parsedMaterial.customType) {
  31315. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  31316. }
  31317. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  31318. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  31319. if (!BABYLON.LegacyPBRMaterial) {
  31320. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  31321. return;
  31322. }
  31323. }
  31324. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  31325. return materialType.Parse(parsedMaterial, scene, rootUrl);
  31326. ;
  31327. };
  31328. // Triangle views
  31329. Material._TriangleFillMode = 0;
  31330. Material._WireFrameFillMode = 1;
  31331. Material._PointFillMode = 2;
  31332. // Draw modes
  31333. Material._PointListDrawMode = 3;
  31334. Material._LineListDrawMode = 4;
  31335. Material._LineLoopDrawMode = 5;
  31336. Material._LineStripDrawMode = 6;
  31337. Material._TriangleStripDrawMode = 7;
  31338. Material._TriangleFanDrawMode = 8;
  31339. /**
  31340. * Stores the clock-wise side orientation.
  31341. */
  31342. Material._ClockWiseSideOrientation = 0;
  31343. /**
  31344. * Stores the counter clock-wise side orientation.
  31345. */
  31346. Material._CounterClockWiseSideOrientation = 1;
  31347. /**
  31348. * The dirty texture flag value.
  31349. */
  31350. Material._TextureDirtyFlag = 1;
  31351. /**
  31352. * The dirty light flag value.
  31353. */
  31354. Material._LightDirtyFlag = 2;
  31355. /**
  31356. * The dirty fresnel flag value.
  31357. */
  31358. Material._FresnelDirtyFlag = 4;
  31359. /**
  31360. * The dirty attribute flag value.
  31361. */
  31362. Material._AttributesDirtyFlag = 8;
  31363. /**
  31364. * The dirty misc flag value.
  31365. */
  31366. Material._MiscDirtyFlag = 16;
  31367. __decorate([
  31368. BABYLON.serialize()
  31369. ], Material.prototype, "id", void 0);
  31370. __decorate([
  31371. BABYLON.serialize()
  31372. ], Material.prototype, "name", void 0);
  31373. __decorate([
  31374. BABYLON.serialize()
  31375. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  31376. __decorate([
  31377. BABYLON.serialize()
  31378. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  31379. __decorate([
  31380. BABYLON.serialize()
  31381. ], Material.prototype, "state", void 0);
  31382. __decorate([
  31383. BABYLON.serialize("alpha")
  31384. ], Material.prototype, "_alpha", void 0);
  31385. __decorate([
  31386. BABYLON.serialize("backFaceCulling")
  31387. ], Material.prototype, "_backFaceCulling", void 0);
  31388. __decorate([
  31389. BABYLON.serialize()
  31390. ], Material.prototype, "sideOrientation", void 0);
  31391. __decorate([
  31392. BABYLON.serialize("alphaMode")
  31393. ], Material.prototype, "_alphaMode", void 0);
  31394. __decorate([
  31395. BABYLON.serialize()
  31396. ], Material.prototype, "_needDepthPrePass", void 0);
  31397. __decorate([
  31398. BABYLON.serialize()
  31399. ], Material.prototype, "disableDepthWrite", void 0);
  31400. __decorate([
  31401. BABYLON.serialize()
  31402. ], Material.prototype, "forceDepthWrite", void 0);
  31403. __decorate([
  31404. BABYLON.serialize()
  31405. ], Material.prototype, "separateCullingPass", void 0);
  31406. __decorate([
  31407. BABYLON.serialize("fogEnabled")
  31408. ], Material.prototype, "_fogEnabled", void 0);
  31409. __decorate([
  31410. BABYLON.serialize()
  31411. ], Material.prototype, "pointSize", void 0);
  31412. __decorate([
  31413. BABYLON.serialize()
  31414. ], Material.prototype, "zOffset", void 0);
  31415. __decorate([
  31416. BABYLON.serialize()
  31417. ], Material.prototype, "wireframe", null);
  31418. __decorate([
  31419. BABYLON.serialize()
  31420. ], Material.prototype, "pointsCloud", null);
  31421. __decorate([
  31422. BABYLON.serialize()
  31423. ], Material.prototype, "fillMode", null);
  31424. return Material;
  31425. }());
  31426. BABYLON.Material = Material;
  31427. })(BABYLON || (BABYLON = {}));
  31428. //# sourceMappingURL=babylon.material.js.map
  31429. var BABYLON;
  31430. (function (BABYLON) {
  31431. var UniformBuffer = /** @class */ (function () {
  31432. /**
  31433. * Uniform buffer objects.
  31434. *
  31435. * Handles blocks of uniform on the GPU.
  31436. *
  31437. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  31438. *
  31439. * For more information, please refer to :
  31440. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  31441. */
  31442. function UniformBuffer(engine, data, dynamic) {
  31443. this._engine = engine;
  31444. this._noUBO = !engine.supportsUniformBuffers;
  31445. this._dynamic = dynamic;
  31446. this._data = data || [];
  31447. this._uniformLocations = {};
  31448. this._uniformSizes = {};
  31449. this._uniformLocationPointer = 0;
  31450. this._needSync = false;
  31451. if (this._noUBO) {
  31452. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  31453. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  31454. this.updateFloat = this._updateFloatForEffect;
  31455. this.updateFloat2 = this._updateFloat2ForEffect;
  31456. this.updateFloat3 = this._updateFloat3ForEffect;
  31457. this.updateFloat4 = this._updateFloat4ForEffect;
  31458. this.updateMatrix = this._updateMatrixForEffect;
  31459. this.updateVector3 = this._updateVector3ForEffect;
  31460. this.updateVector4 = this._updateVector4ForEffect;
  31461. this.updateColor3 = this._updateColor3ForEffect;
  31462. this.updateColor4 = this._updateColor4ForEffect;
  31463. }
  31464. else {
  31465. this._engine._uniformBuffers.push(this);
  31466. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  31467. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  31468. this.updateFloat = this._updateFloatForUniform;
  31469. this.updateFloat2 = this._updateFloat2ForUniform;
  31470. this.updateFloat3 = this._updateFloat3ForUniform;
  31471. this.updateFloat4 = this._updateFloat4ForUniform;
  31472. this.updateMatrix = this._updateMatrixForUniform;
  31473. this.updateVector3 = this._updateVector3ForUniform;
  31474. this.updateVector4 = this._updateVector4ForUniform;
  31475. this.updateColor3 = this._updateColor3ForUniform;
  31476. this.updateColor4 = this._updateColor4ForUniform;
  31477. }
  31478. }
  31479. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  31480. // Properties
  31481. /**
  31482. * Indicates if the buffer is using the WebGL2 UBO implementation,
  31483. * or just falling back on setUniformXXX calls.
  31484. */
  31485. get: function () {
  31486. return !this._noUBO;
  31487. },
  31488. enumerable: true,
  31489. configurable: true
  31490. });
  31491. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  31492. /**
  31493. * Indicates if the WebGL underlying uniform buffer is in sync
  31494. * with the javascript cache data.
  31495. */
  31496. get: function () {
  31497. return !this._needSync;
  31498. },
  31499. enumerable: true,
  31500. configurable: true
  31501. });
  31502. /**
  31503. * Indicates if the WebGL underlying uniform buffer is dynamic.
  31504. * Also, a dynamic UniformBuffer will disable cache verification and always
  31505. * update the underlying WebGL uniform buffer to the GPU.
  31506. */
  31507. UniformBuffer.prototype.isDynamic = function () {
  31508. return this._dynamic !== undefined;
  31509. };
  31510. /**
  31511. * The data cache on JS side.
  31512. */
  31513. UniformBuffer.prototype.getData = function () {
  31514. return this._bufferData;
  31515. };
  31516. /**
  31517. * The underlying WebGL Uniform buffer.
  31518. */
  31519. UniformBuffer.prototype.getBuffer = function () {
  31520. return this._buffer;
  31521. };
  31522. /**
  31523. * std140 layout specifies how to align data within an UBO structure.
  31524. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  31525. * for specs.
  31526. */
  31527. UniformBuffer.prototype._fillAlignment = function (size) {
  31528. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  31529. // and 4x4 matrices
  31530. // TODO : change if other types are used
  31531. var alignment;
  31532. if (size <= 2) {
  31533. alignment = size;
  31534. }
  31535. else {
  31536. alignment = 4;
  31537. }
  31538. if ((this._uniformLocationPointer % alignment) !== 0) {
  31539. var oldPointer = this._uniformLocationPointer;
  31540. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  31541. var diff = this._uniformLocationPointer - oldPointer;
  31542. for (var i = 0; i < diff; i++) {
  31543. this._data.push(0);
  31544. }
  31545. }
  31546. };
  31547. /**
  31548. * Adds an uniform in the buffer.
  31549. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  31550. * for the layout to be correct !
  31551. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31552. * @param {number|number[]} size Data size, or data directly.
  31553. */
  31554. UniformBuffer.prototype.addUniform = function (name, size) {
  31555. if (this._noUBO) {
  31556. return;
  31557. }
  31558. if (this._uniformLocations[name] !== undefined) {
  31559. // Already existing uniform
  31560. return;
  31561. }
  31562. // This function must be called in the order of the shader layout !
  31563. // size can be the size of the uniform, or data directly
  31564. var data;
  31565. if (size instanceof Array) {
  31566. data = size;
  31567. size = data.length;
  31568. }
  31569. else {
  31570. size = size;
  31571. data = [];
  31572. // Fill with zeros
  31573. for (var i = 0; i < size; i++) {
  31574. data.push(0);
  31575. }
  31576. }
  31577. this._fillAlignment(size);
  31578. this._uniformSizes[name] = size;
  31579. this._uniformLocations[name] = this._uniformLocationPointer;
  31580. this._uniformLocationPointer += size;
  31581. for (var i = 0; i < size; i++) {
  31582. this._data.push(data[i]);
  31583. }
  31584. this._needSync = true;
  31585. };
  31586. /**
  31587. * Wrapper for addUniform.
  31588. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31589. * @param {Matrix} mat A 4x4 matrix.
  31590. */
  31591. UniformBuffer.prototype.addMatrix = function (name, mat) {
  31592. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  31593. };
  31594. /**
  31595. * Wrapper for addUniform.
  31596. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31597. * @param {number} x
  31598. * @param {number} y
  31599. */
  31600. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  31601. var temp = [x, y];
  31602. this.addUniform(name, temp);
  31603. };
  31604. /**
  31605. * Wrapper for addUniform.
  31606. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31607. * @param {number} x
  31608. * @param {number} y
  31609. * @param {number} z
  31610. */
  31611. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  31612. var temp = [x, y, z];
  31613. this.addUniform(name, temp);
  31614. };
  31615. /**
  31616. * Wrapper for addUniform.
  31617. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31618. * @param {Color3} color
  31619. */
  31620. UniformBuffer.prototype.addColor3 = function (name, color) {
  31621. var temp = new Array();
  31622. color.toArray(temp);
  31623. this.addUniform(name, temp);
  31624. };
  31625. /**
  31626. * Wrapper for addUniform.
  31627. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31628. * @param {Color3} color
  31629. * @param {number} alpha
  31630. */
  31631. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  31632. var temp = new Array();
  31633. color.toArray(temp);
  31634. temp.push(alpha);
  31635. this.addUniform(name, temp);
  31636. };
  31637. /**
  31638. * Wrapper for addUniform.
  31639. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31640. * @param {Vector3} vector
  31641. */
  31642. UniformBuffer.prototype.addVector3 = function (name, vector) {
  31643. var temp = new Array();
  31644. vector.toArray(temp);
  31645. this.addUniform(name, temp);
  31646. };
  31647. /**
  31648. * Wrapper for addUniform.
  31649. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31650. */
  31651. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  31652. this.addUniform(name, 12);
  31653. };
  31654. /**
  31655. * Wrapper for addUniform.
  31656. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  31657. */
  31658. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  31659. this.addUniform(name, 8);
  31660. };
  31661. /**
  31662. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  31663. */
  31664. UniformBuffer.prototype.create = function () {
  31665. if (this._noUBO) {
  31666. return;
  31667. }
  31668. if (this._buffer) {
  31669. return; // nothing to do
  31670. }
  31671. // See spec, alignment must be filled as a vec4
  31672. this._fillAlignment(4);
  31673. this._bufferData = new Float32Array(this._data);
  31674. this._rebuild();
  31675. this._needSync = true;
  31676. };
  31677. UniformBuffer.prototype._rebuild = function () {
  31678. if (this._noUBO) {
  31679. return;
  31680. }
  31681. if (this._dynamic) {
  31682. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  31683. }
  31684. else {
  31685. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  31686. }
  31687. };
  31688. /**
  31689. * Updates the WebGL Uniform Buffer on the GPU.
  31690. * If the `dynamic` flag is set to true, no cache comparison is done.
  31691. * Otherwise, the buffer will be updated only if the cache differs.
  31692. */
  31693. UniformBuffer.prototype.update = function () {
  31694. if (!this._buffer) {
  31695. this.create();
  31696. return;
  31697. }
  31698. if (!this._dynamic && !this._needSync) {
  31699. return;
  31700. }
  31701. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  31702. this._needSync = false;
  31703. };
  31704. /**
  31705. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  31706. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31707. * @param {number[]|Float32Array} data Flattened data
  31708. * @param {number} size Size of the data.
  31709. */
  31710. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  31711. var location = this._uniformLocations[uniformName];
  31712. if (location === undefined) {
  31713. if (this._buffer) {
  31714. // Cannot add an uniform if the buffer is already created
  31715. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  31716. return;
  31717. }
  31718. this.addUniform(uniformName, size);
  31719. location = this._uniformLocations[uniformName];
  31720. }
  31721. if (!this._buffer) {
  31722. this.create();
  31723. }
  31724. if (!this._dynamic) {
  31725. // Cache for static uniform buffers
  31726. var changed = false;
  31727. for (var i = 0; i < size; i++) {
  31728. if (this._bufferData[location + i] !== data[i]) {
  31729. changed = true;
  31730. this._bufferData[location + i] = data[i];
  31731. }
  31732. }
  31733. this._needSync = this._needSync || changed;
  31734. }
  31735. else {
  31736. // No cache for dynamic
  31737. for (var i = 0; i < size; i++) {
  31738. this._bufferData[location + i] = data[i];
  31739. }
  31740. }
  31741. };
  31742. // Update methods
  31743. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  31744. // To match std140, matrix must be realigned
  31745. for (var i = 0; i < 3; i++) {
  31746. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  31747. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  31748. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  31749. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31750. }
  31751. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  31752. };
  31753. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  31754. this._currentEffect.setMatrix3x3(name, matrix);
  31755. };
  31756. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  31757. this._currentEffect.setMatrix2x2(name, matrix);
  31758. };
  31759. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  31760. // To match std140, matrix must be realigned
  31761. for (var i = 0; i < 2; i++) {
  31762. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  31763. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  31764. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  31765. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  31766. }
  31767. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  31768. };
  31769. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  31770. this._currentEffect.setFloat(name, x);
  31771. };
  31772. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  31773. UniformBuffer._tempBuffer[0] = x;
  31774. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  31775. };
  31776. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  31777. if (suffix === void 0) { suffix = ""; }
  31778. this._currentEffect.setFloat2(name + suffix, x, y);
  31779. };
  31780. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  31781. if (suffix === void 0) { suffix = ""; }
  31782. UniformBuffer._tempBuffer[0] = x;
  31783. UniformBuffer._tempBuffer[1] = y;
  31784. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  31785. };
  31786. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  31787. if (suffix === void 0) { suffix = ""; }
  31788. this._currentEffect.setFloat3(name + suffix, x, y, z);
  31789. };
  31790. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  31791. if (suffix === void 0) { suffix = ""; }
  31792. UniformBuffer._tempBuffer[0] = x;
  31793. UniformBuffer._tempBuffer[1] = y;
  31794. UniformBuffer._tempBuffer[2] = z;
  31795. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31796. };
  31797. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  31798. if (suffix === void 0) { suffix = ""; }
  31799. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  31800. };
  31801. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  31802. if (suffix === void 0) { suffix = ""; }
  31803. UniformBuffer._tempBuffer[0] = x;
  31804. UniformBuffer._tempBuffer[1] = y;
  31805. UniformBuffer._tempBuffer[2] = z;
  31806. UniformBuffer._tempBuffer[3] = w;
  31807. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31808. };
  31809. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  31810. this._currentEffect.setMatrix(name, mat);
  31811. };
  31812. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  31813. this.updateUniform(name, mat.toArray(), 16);
  31814. };
  31815. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  31816. this._currentEffect.setVector3(name, vector);
  31817. };
  31818. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  31819. vector.toArray(UniformBuffer._tempBuffer);
  31820. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31821. };
  31822. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  31823. this._currentEffect.setVector4(name, vector);
  31824. };
  31825. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  31826. vector.toArray(UniformBuffer._tempBuffer);
  31827. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31828. };
  31829. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  31830. if (suffix === void 0) { suffix = ""; }
  31831. this._currentEffect.setColor3(name + suffix, color);
  31832. };
  31833. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  31834. if (suffix === void 0) { suffix = ""; }
  31835. color.toArray(UniformBuffer._tempBuffer);
  31836. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  31837. };
  31838. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  31839. if (suffix === void 0) { suffix = ""; }
  31840. this._currentEffect.setColor4(name + suffix, color, alpha);
  31841. };
  31842. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  31843. if (suffix === void 0) { suffix = ""; }
  31844. color.toArray(UniformBuffer._tempBuffer);
  31845. UniformBuffer._tempBuffer[3] = alpha;
  31846. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  31847. };
  31848. /**
  31849. * Sets a sampler uniform on the effect.
  31850. * @param {string} name Name of the sampler.
  31851. * @param {Texture} texture
  31852. */
  31853. UniformBuffer.prototype.setTexture = function (name, texture) {
  31854. this._currentEffect.setTexture(name, texture);
  31855. };
  31856. /**
  31857. * Directly updates the value of the uniform in the cache AND on the GPU.
  31858. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  31859. * @param {number[]|Float32Array} data Flattened data
  31860. */
  31861. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  31862. this.updateUniform(uniformName, data, data.length);
  31863. this.update();
  31864. };
  31865. /**
  31866. * Binds this uniform buffer to an effect.
  31867. * @param {Effect} effect
  31868. * @param {string} name Name of the uniform block in the shader.
  31869. */
  31870. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  31871. this._currentEffect = effect;
  31872. if (this._noUBO || !this._buffer) {
  31873. return;
  31874. }
  31875. effect.bindUniformBuffer(this._buffer, name);
  31876. };
  31877. /**
  31878. * Disposes the uniform buffer.
  31879. */
  31880. UniformBuffer.prototype.dispose = function () {
  31881. if (this._noUBO) {
  31882. return;
  31883. }
  31884. var index = this._engine._uniformBuffers.indexOf(this);
  31885. if (index !== -1) {
  31886. this._engine._uniformBuffers.splice(index, 1);
  31887. }
  31888. if (!this._buffer) {
  31889. return;
  31890. }
  31891. if (this._engine._releaseBuffer(this._buffer)) {
  31892. this._buffer = null;
  31893. }
  31894. };
  31895. // Pool for avoiding memory leaks
  31896. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  31897. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  31898. return UniformBuffer;
  31899. }());
  31900. BABYLON.UniformBuffer = UniformBuffer;
  31901. })(BABYLON || (BABYLON = {}));
  31902. //# sourceMappingURL=babylon.uniformBuffer.js.map
  31903. var BABYLON;
  31904. (function (BABYLON) {
  31905. var VertexData = /** @class */ (function () {
  31906. function VertexData() {
  31907. }
  31908. VertexData.prototype.set = function (data, kind) {
  31909. switch (kind) {
  31910. case BABYLON.VertexBuffer.PositionKind:
  31911. this.positions = data;
  31912. break;
  31913. case BABYLON.VertexBuffer.NormalKind:
  31914. this.normals = data;
  31915. break;
  31916. case BABYLON.VertexBuffer.TangentKind:
  31917. this.tangents = data;
  31918. break;
  31919. case BABYLON.VertexBuffer.UVKind:
  31920. this.uvs = data;
  31921. break;
  31922. case BABYLON.VertexBuffer.UV2Kind:
  31923. this.uvs2 = data;
  31924. break;
  31925. case BABYLON.VertexBuffer.UV3Kind:
  31926. this.uvs3 = data;
  31927. break;
  31928. case BABYLON.VertexBuffer.UV4Kind:
  31929. this.uvs4 = data;
  31930. break;
  31931. case BABYLON.VertexBuffer.UV5Kind:
  31932. this.uvs5 = data;
  31933. break;
  31934. case BABYLON.VertexBuffer.UV6Kind:
  31935. this.uvs6 = data;
  31936. break;
  31937. case BABYLON.VertexBuffer.ColorKind:
  31938. this.colors = data;
  31939. break;
  31940. case BABYLON.VertexBuffer.MatricesIndicesKind:
  31941. this.matricesIndices = data;
  31942. break;
  31943. case BABYLON.VertexBuffer.MatricesWeightsKind:
  31944. this.matricesWeights = data;
  31945. break;
  31946. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  31947. this.matricesIndicesExtra = data;
  31948. break;
  31949. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  31950. this.matricesWeightsExtra = data;
  31951. break;
  31952. }
  31953. };
  31954. /**
  31955. * Associates the vertexData to the passed Mesh.
  31956. * Sets it as updatable or not (default `false`).
  31957. * Returns the VertexData.
  31958. */
  31959. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  31960. this._applyTo(mesh, updatable);
  31961. return this;
  31962. };
  31963. /**
  31964. * Associates the vertexData to the passed Geometry.
  31965. * Sets it as updatable or not (default `false`).
  31966. * Returns the VertexData.
  31967. */
  31968. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  31969. this._applyTo(geometry, updatable);
  31970. return this;
  31971. };
  31972. /**
  31973. * Updates the associated mesh.
  31974. * Returns the VertexData.
  31975. */
  31976. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  31977. this._update(mesh);
  31978. return this;
  31979. };
  31980. /**
  31981. * Updates the associated geometry.
  31982. * Returns the VertexData.
  31983. */
  31984. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  31985. this._update(geometry);
  31986. return this;
  31987. };
  31988. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  31989. if (updatable === void 0) { updatable = false; }
  31990. if (this.positions) {
  31991. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  31992. }
  31993. if (this.normals) {
  31994. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  31995. }
  31996. if (this.tangents) {
  31997. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  31998. }
  31999. if (this.uvs) {
  32000. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32001. }
  32002. if (this.uvs2) {
  32003. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32004. }
  32005. if (this.uvs3) {
  32006. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32007. }
  32008. if (this.uvs4) {
  32009. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32010. }
  32011. if (this.uvs5) {
  32012. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32013. }
  32014. if (this.uvs6) {
  32015. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32016. }
  32017. if (this.colors) {
  32018. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32019. }
  32020. if (this.matricesIndices) {
  32021. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32022. }
  32023. if (this.matricesWeights) {
  32024. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32025. }
  32026. if (this.matricesIndicesExtra) {
  32027. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32028. }
  32029. if (this.matricesWeightsExtra) {
  32030. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32031. }
  32032. if (this.indices) {
  32033. meshOrGeometry.setIndices(this.indices, null, updatable);
  32034. }
  32035. return this;
  32036. };
  32037. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32038. if (this.positions) {
  32039. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32040. }
  32041. if (this.normals) {
  32042. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32043. }
  32044. if (this.tangents) {
  32045. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  32046. }
  32047. if (this.uvs) {
  32048. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32049. }
  32050. if (this.uvs2) {
  32051. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32052. }
  32053. if (this.uvs3) {
  32054. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32055. }
  32056. if (this.uvs4) {
  32057. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32058. }
  32059. if (this.uvs5) {
  32060. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32061. }
  32062. if (this.uvs6) {
  32063. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32064. }
  32065. if (this.colors) {
  32066. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32067. }
  32068. if (this.matricesIndices) {
  32069. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32070. }
  32071. if (this.matricesWeights) {
  32072. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32073. }
  32074. if (this.matricesIndicesExtra) {
  32075. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32076. }
  32077. if (this.matricesWeightsExtra) {
  32078. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32079. }
  32080. if (this.indices) {
  32081. meshOrGeometry.setIndices(this.indices, null);
  32082. }
  32083. return this;
  32084. };
  32085. /**
  32086. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  32087. * Returns the VertexData.
  32088. */
  32089. VertexData.prototype.transform = function (matrix) {
  32090. var transformed = BABYLON.Vector3.Zero();
  32091. var index;
  32092. if (this.positions) {
  32093. var position = BABYLON.Vector3.Zero();
  32094. for (index = 0; index < this.positions.length; index += 3) {
  32095. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32096. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32097. this.positions[index] = transformed.x;
  32098. this.positions[index + 1] = transformed.y;
  32099. this.positions[index + 2] = transformed.z;
  32100. }
  32101. }
  32102. if (this.normals) {
  32103. var normal = BABYLON.Vector3.Zero();
  32104. for (index = 0; index < this.normals.length; index += 3) {
  32105. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32106. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32107. this.normals[index] = transformed.x;
  32108. this.normals[index + 1] = transformed.y;
  32109. this.normals[index + 2] = transformed.z;
  32110. }
  32111. }
  32112. if (this.tangents) {
  32113. var tangent = BABYLON.Vector4.Zero();
  32114. var tangentTransformed = BABYLON.Vector4.Zero();
  32115. for (index = 0; index < this.tangents.length; index += 4) {
  32116. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  32117. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  32118. this.tangents[index] = tangentTransformed.x;
  32119. this.tangents[index + 1] = tangentTransformed.y;
  32120. this.tangents[index + 2] = tangentTransformed.z;
  32121. this.tangents[index + 3] = tangentTransformed.w;
  32122. }
  32123. }
  32124. return this;
  32125. };
  32126. /**
  32127. * Merges the passed VertexData into the current one.
  32128. * Returns the modified VertexData.
  32129. */
  32130. VertexData.prototype.merge = function (other) {
  32131. this._validate();
  32132. other._validate();
  32133. if (!this.normals !== !other.normals ||
  32134. !this.tangents !== !other.tangents ||
  32135. !this.uvs !== !other.uvs ||
  32136. !this.uvs2 !== !other.uvs2 ||
  32137. !this.uvs3 !== !other.uvs3 ||
  32138. !this.uvs4 !== !other.uvs4 ||
  32139. !this.uvs5 !== !other.uvs5 ||
  32140. !this.uvs6 !== !other.uvs6 ||
  32141. !this.colors !== !other.colors ||
  32142. !this.matricesIndices !== !other.matricesIndices ||
  32143. !this.matricesWeights !== !other.matricesWeights ||
  32144. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  32145. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  32146. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  32147. }
  32148. if (other.indices) {
  32149. if (!this.indices) {
  32150. this.indices = [];
  32151. }
  32152. var offset = this.positions ? this.positions.length / 3 : 0;
  32153. for (var index = 0; index < other.indices.length; index++) {
  32154. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  32155. this.indices.push(other.indices[index] + offset);
  32156. }
  32157. }
  32158. this.positions = this._mergeElement(this.positions, other.positions);
  32159. this.normals = this._mergeElement(this.normals, other.normals);
  32160. this.tangents = this._mergeElement(this.tangents, other.tangents);
  32161. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32162. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32163. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32164. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32165. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32166. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32167. this.colors = this._mergeElement(this.colors, other.colors);
  32168. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32169. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32170. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32171. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32172. return this;
  32173. };
  32174. VertexData.prototype._mergeElement = function (source, other) {
  32175. if (!source) {
  32176. return other;
  32177. }
  32178. if (!other) {
  32179. return source;
  32180. }
  32181. var len = other.length + source.length;
  32182. var isSrcTypedArray = source instanceof Float32Array;
  32183. var isOthTypedArray = other instanceof Float32Array;
  32184. // use non-loop method when the source is Float32Array
  32185. if (isSrcTypedArray) {
  32186. var ret32 = new Float32Array(len);
  32187. ret32.set(source);
  32188. ret32.set(other, source.length);
  32189. return ret32;
  32190. // source is number[], when other is also use concat
  32191. }
  32192. else if (!isOthTypedArray) {
  32193. return source.concat(other);
  32194. // source is a number[], but other is a Float32Array, loop required
  32195. }
  32196. else {
  32197. var ret = source.slice(0); // copy source to a separate array
  32198. for (var i = 0, len = other.length; i < len; i++) {
  32199. ret.push(other[i]);
  32200. }
  32201. return ret;
  32202. }
  32203. };
  32204. VertexData.prototype._validate = function () {
  32205. if (!this.positions) {
  32206. throw new Error("Positions are required");
  32207. }
  32208. var getElementCount = function (kind, values) {
  32209. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  32210. if ((values.length % stride) !== 0) {
  32211. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  32212. }
  32213. return values.length / stride;
  32214. };
  32215. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  32216. var validateElementCount = function (kind, values) {
  32217. var elementCount = getElementCount(kind, values);
  32218. if (elementCount !== positionsElementCount) {
  32219. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  32220. }
  32221. };
  32222. if (this.normals)
  32223. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  32224. if (this.tangents)
  32225. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  32226. if (this.uvs)
  32227. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  32228. if (this.uvs2)
  32229. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  32230. if (this.uvs3)
  32231. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  32232. if (this.uvs4)
  32233. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  32234. if (this.uvs5)
  32235. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  32236. if (this.uvs6)
  32237. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  32238. if (this.colors)
  32239. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  32240. if (this.matricesIndices)
  32241. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  32242. if (this.matricesWeights)
  32243. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  32244. if (this.matricesIndicesExtra)
  32245. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  32246. if (this.matricesWeightsExtra)
  32247. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  32248. };
  32249. /**
  32250. * Serializes the VertexData.
  32251. * Returns a serialized object.
  32252. */
  32253. VertexData.prototype.serialize = function () {
  32254. var serializationObject = this.serialize();
  32255. if (this.positions) {
  32256. serializationObject.positions = this.positions;
  32257. }
  32258. if (this.normals) {
  32259. serializationObject.normals = this.normals;
  32260. }
  32261. if (this.tangents) {
  32262. serializationObject.tangents = this.tangents;
  32263. }
  32264. if (this.uvs) {
  32265. serializationObject.uvs = this.uvs;
  32266. }
  32267. if (this.uvs2) {
  32268. serializationObject.uvs2 = this.uvs2;
  32269. }
  32270. if (this.uvs3) {
  32271. serializationObject.uvs3 = this.uvs3;
  32272. }
  32273. if (this.uvs4) {
  32274. serializationObject.uvs4 = this.uvs4;
  32275. }
  32276. if (this.uvs5) {
  32277. serializationObject.uvs5 = this.uvs5;
  32278. }
  32279. if (this.uvs6) {
  32280. serializationObject.uvs6 = this.uvs6;
  32281. }
  32282. if (this.colors) {
  32283. serializationObject.colors = this.colors;
  32284. }
  32285. if (this.matricesIndices) {
  32286. serializationObject.matricesIndices = this.matricesIndices;
  32287. serializationObject.matricesIndices._isExpanded = true;
  32288. }
  32289. if (this.matricesWeights) {
  32290. serializationObject.matricesWeights = this.matricesWeights;
  32291. }
  32292. if (this.matricesIndicesExtra) {
  32293. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32294. serializationObject.matricesIndicesExtra._isExpanded = true;
  32295. }
  32296. if (this.matricesWeightsExtra) {
  32297. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32298. }
  32299. serializationObject.indices = this.indices;
  32300. return serializationObject;
  32301. };
  32302. // Statics
  32303. /**
  32304. * Returns the object VertexData associated to the passed mesh.
  32305. */
  32306. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  32307. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  32308. };
  32309. /**
  32310. * Returns the object VertexData associated to the passed geometry.
  32311. */
  32312. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  32313. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  32314. };
  32315. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  32316. var result = new VertexData();
  32317. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32318. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  32319. }
  32320. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32321. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  32322. }
  32323. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  32324. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  32325. }
  32326. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32327. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  32328. }
  32329. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32330. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  32331. }
  32332. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32333. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  32334. }
  32335. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32336. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  32337. }
  32338. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32339. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  32340. }
  32341. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32342. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  32343. }
  32344. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32345. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  32346. }
  32347. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32348. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  32349. }
  32350. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32351. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  32352. }
  32353. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32354. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  32355. }
  32356. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32357. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  32358. }
  32359. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32360. return result;
  32361. };
  32362. /**
  32363. * Creates the vertexData of the Ribbon.
  32364. */
  32365. VertexData.CreateRibbon = function (options) {
  32366. var pathArray = options.pathArray;
  32367. var closeArray = options.closeArray || false;
  32368. var closePath = options.closePath || false;
  32369. var invertUV = options.invertUV || false;
  32370. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32371. var offset = options.offset || defaultOffset;
  32372. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32373. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32374. var customUV = options.uvs;
  32375. var customColors = options.colors;
  32376. var positions = [];
  32377. var indices = [];
  32378. var normals = [];
  32379. var uvs = [];
  32380. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32381. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32382. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32383. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32384. var minlg; // minimal length among all paths from pathArray
  32385. var lg = []; // array of path lengths : nb of vertex per path
  32386. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32387. var p; // path iterator
  32388. var i; // point iterator
  32389. var j; // point iterator
  32390. // if single path in pathArray
  32391. if (pathArray.length < 2) {
  32392. var ar1 = [];
  32393. var ar2 = [];
  32394. for (i = 0; i < pathArray[0].length - offset; i++) {
  32395. ar1.push(pathArray[0][i]);
  32396. ar2.push(pathArray[0][i + offset]);
  32397. }
  32398. pathArray = [ar1, ar2];
  32399. }
  32400. // positions and horizontal distances (u)
  32401. var idc = 0;
  32402. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  32403. var path;
  32404. var l;
  32405. minlg = pathArray[0].length;
  32406. var vectlg;
  32407. var dist;
  32408. for (p = 0; p < pathArray.length; p++) {
  32409. uTotalDistance[p] = 0;
  32410. us[p] = [0];
  32411. path = pathArray[p];
  32412. l = path.length;
  32413. minlg = (minlg < l) ? minlg : l;
  32414. j = 0;
  32415. while (j < l) {
  32416. positions.push(path[j].x, path[j].y, path[j].z);
  32417. if (j > 0) {
  32418. vectlg = path[j].subtract(path[j - 1]).length();
  32419. dist = vectlg + uTotalDistance[p];
  32420. us[p].push(dist);
  32421. uTotalDistance[p] = dist;
  32422. }
  32423. j++;
  32424. }
  32425. if (closePath) {
  32426. j--;
  32427. positions.push(path[0].x, path[0].y, path[0].z);
  32428. vectlg = path[j].subtract(path[0]).length();
  32429. dist = vectlg + uTotalDistance[p];
  32430. us[p].push(dist);
  32431. uTotalDistance[p] = dist;
  32432. }
  32433. lg[p] = l + closePathCorr;
  32434. idx[p] = idc;
  32435. idc += (l + closePathCorr);
  32436. }
  32437. // vertical distances (v)
  32438. var path1;
  32439. var path2;
  32440. var vertex1 = null;
  32441. var vertex2 = null;
  32442. for (i = 0; i < minlg + closePathCorr; i++) {
  32443. vTotalDistance[i] = 0;
  32444. vs[i] = [0];
  32445. for (p = 0; p < pathArray.length - 1; p++) {
  32446. path1 = pathArray[p];
  32447. path2 = pathArray[p + 1];
  32448. if (i === minlg) {
  32449. vertex1 = path1[0];
  32450. vertex2 = path2[0];
  32451. }
  32452. else {
  32453. vertex1 = path1[i];
  32454. vertex2 = path2[i];
  32455. }
  32456. vectlg = vertex2.subtract(vertex1).length();
  32457. dist = vectlg + vTotalDistance[i];
  32458. vs[i].push(dist);
  32459. vTotalDistance[i] = dist;
  32460. }
  32461. if (closeArray && vertex2 && vertex1) {
  32462. path1 = pathArray[p];
  32463. path2 = pathArray[0];
  32464. if (i === minlg) {
  32465. vertex2 = path2[0];
  32466. }
  32467. vectlg = vertex2.subtract(vertex1).length();
  32468. dist = vectlg + vTotalDistance[i];
  32469. vTotalDistance[i] = dist;
  32470. }
  32471. }
  32472. // uvs
  32473. var u;
  32474. var v;
  32475. if (customUV) {
  32476. for (p = 0; p < customUV.length; p++) {
  32477. uvs.push(customUV[p].x, customUV[p].y);
  32478. }
  32479. }
  32480. else {
  32481. for (p = 0; p < pathArray.length; p++) {
  32482. for (i = 0; i < minlg + closePathCorr; i++) {
  32483. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  32484. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  32485. if (invertUV) {
  32486. uvs.push(v, u);
  32487. }
  32488. else {
  32489. uvs.push(u, v);
  32490. }
  32491. }
  32492. }
  32493. }
  32494. // indices
  32495. p = 0; // path index
  32496. var pi = 0; // positions array index
  32497. var l1 = lg[p] - 1; // path1 length
  32498. var l2 = lg[p + 1] - 1; // path2 length
  32499. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32500. var shft = idx[1] - idx[0]; // shift
  32501. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32502. while (pi <= min && p < path1nb) {
  32503. // 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
  32504. indices.push(pi, pi + shft, pi + 1);
  32505. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32506. pi += 1;
  32507. if (pi === min) {
  32508. p++;
  32509. if (p === lg.length - 1) {
  32510. shft = idx[0] - idx[p];
  32511. l1 = lg[p] - 1;
  32512. l2 = lg[0] - 1;
  32513. }
  32514. else {
  32515. shft = idx[p + 1] - idx[p];
  32516. l1 = lg[p] - 1;
  32517. l2 = lg[p + 1] - 1;
  32518. }
  32519. pi = idx[p];
  32520. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32521. }
  32522. }
  32523. // normals
  32524. VertexData.ComputeNormals(positions, indices, normals);
  32525. if (closePath) {
  32526. var indexFirst = 0;
  32527. var indexLast = 0;
  32528. for (p = 0; p < pathArray.length; p++) {
  32529. indexFirst = idx[p] * 3;
  32530. if (p + 1 < pathArray.length) {
  32531. indexLast = (idx[p + 1] - 1) * 3;
  32532. }
  32533. else {
  32534. indexLast = normals.length - 3;
  32535. }
  32536. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32537. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32538. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32539. normals[indexLast] = normals[indexFirst];
  32540. normals[indexLast + 1] = normals[indexFirst + 1];
  32541. normals[indexLast + 2] = normals[indexFirst + 2];
  32542. }
  32543. }
  32544. // sides
  32545. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32546. // Colors
  32547. var colors = null;
  32548. if (customColors) {
  32549. colors = new Float32Array(customColors.length * 4);
  32550. for (var c = 0; c < customColors.length; c++) {
  32551. colors[c * 4] = customColors[c].r;
  32552. colors[c * 4 + 1] = customColors[c].g;
  32553. colors[c * 4 + 2] = customColors[c].b;
  32554. colors[c * 4 + 3] = customColors[c].a;
  32555. }
  32556. }
  32557. // Result
  32558. var vertexData = new VertexData();
  32559. var positions32 = new Float32Array(positions);
  32560. var normals32 = new Float32Array(normals);
  32561. var uvs32 = new Float32Array(uvs);
  32562. vertexData.indices = indices;
  32563. vertexData.positions = positions32;
  32564. vertexData.normals = normals32;
  32565. vertexData.uvs = uvs32;
  32566. if (colors) {
  32567. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  32568. }
  32569. if (closePath) {
  32570. vertexData._idx = idx;
  32571. }
  32572. return vertexData;
  32573. };
  32574. /**
  32575. * Creates the VertexData of the Box.
  32576. */
  32577. VertexData.CreateBox = function (options) {
  32578. var normalsSource = [
  32579. new BABYLON.Vector3(0, 0, 1),
  32580. new BABYLON.Vector3(0, 0, -1),
  32581. new BABYLON.Vector3(1, 0, 0),
  32582. new BABYLON.Vector3(-1, 0, 0),
  32583. new BABYLON.Vector3(0, 1, 0),
  32584. new BABYLON.Vector3(0, -1, 0)
  32585. ];
  32586. var indices = [];
  32587. var positions = [];
  32588. var normals = [];
  32589. var uvs = [];
  32590. var width = options.width || options.size || 1;
  32591. var height = options.height || options.size || 1;
  32592. var depth = options.depth || options.size || 1;
  32593. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32594. var faceUV = options.faceUV || new Array(6);
  32595. var faceColors = options.faceColors;
  32596. var colors = [];
  32597. // default face colors and UV if undefined
  32598. for (var f = 0; f < 6; f++) {
  32599. if (faceUV[f] === undefined) {
  32600. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32601. }
  32602. if (faceColors && faceColors[f] === undefined) {
  32603. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32604. }
  32605. }
  32606. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32607. // Create each face in turn.
  32608. for (var index = 0; index < normalsSource.length; index++) {
  32609. var normal = normalsSource[index];
  32610. // Get two vectors perpendicular to the face normal and to each other.
  32611. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32612. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32613. // Six indices (two triangles) per face.
  32614. var verticesLength = positions.length / 3;
  32615. indices.push(verticesLength);
  32616. indices.push(verticesLength + 1);
  32617. indices.push(verticesLength + 2);
  32618. indices.push(verticesLength);
  32619. indices.push(verticesLength + 2);
  32620. indices.push(verticesLength + 3);
  32621. // Four vertices per face.
  32622. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32623. positions.push(vertex.x, vertex.y, vertex.z);
  32624. normals.push(normal.x, normal.y, normal.z);
  32625. uvs.push(faceUV[index].z, faceUV[index].w);
  32626. if (faceColors) {
  32627. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32628. }
  32629. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32630. positions.push(vertex.x, vertex.y, vertex.z);
  32631. normals.push(normal.x, normal.y, normal.z);
  32632. uvs.push(faceUV[index].x, faceUV[index].w);
  32633. if (faceColors) {
  32634. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32635. }
  32636. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  32637. positions.push(vertex.x, vertex.y, vertex.z);
  32638. normals.push(normal.x, normal.y, normal.z);
  32639. uvs.push(faceUV[index].x, faceUV[index].y);
  32640. if (faceColors) {
  32641. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32642. }
  32643. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  32644. positions.push(vertex.x, vertex.y, vertex.z);
  32645. normals.push(normal.x, normal.y, normal.z);
  32646. uvs.push(faceUV[index].z, faceUV[index].y);
  32647. if (faceColors) {
  32648. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32649. }
  32650. }
  32651. // sides
  32652. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32653. // Result
  32654. var vertexData = new VertexData();
  32655. vertexData.indices = indices;
  32656. vertexData.positions = positions;
  32657. vertexData.normals = normals;
  32658. vertexData.uvs = uvs;
  32659. if (faceColors) {
  32660. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  32661. vertexData.colors = totalColors;
  32662. }
  32663. return vertexData;
  32664. };
  32665. /**
  32666. * Creates the VertexData of the Sphere.
  32667. */
  32668. VertexData.CreateSphere = function (options) {
  32669. var segments = options.segments || 32;
  32670. var diameterX = options.diameterX || options.diameter || 1;
  32671. var diameterY = options.diameterY || options.diameter || 1;
  32672. var diameterZ = options.diameterZ || options.diameter || 1;
  32673. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32674. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  32675. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32676. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  32677. var totalZRotationSteps = 2 + segments;
  32678. var totalYRotationSteps = 2 * totalZRotationSteps;
  32679. var indices = [];
  32680. var positions = [];
  32681. var normals = [];
  32682. var uvs = [];
  32683. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  32684. var normalizedZ = zRotationStep / totalZRotationSteps;
  32685. var angleZ = normalizedZ * Math.PI * slice;
  32686. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  32687. var normalizedY = yRotationStep / totalYRotationSteps;
  32688. var angleY = normalizedY * Math.PI * 2 * arc;
  32689. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  32690. var rotationY = BABYLON.Matrix.RotationY(angleY);
  32691. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  32692. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  32693. var vertex = complete.multiply(radius);
  32694. var normal = complete.divide(radius).normalize();
  32695. positions.push(vertex.x, vertex.y, vertex.z);
  32696. normals.push(normal.x, normal.y, normal.z);
  32697. uvs.push(normalizedY, normalizedZ);
  32698. }
  32699. if (zRotationStep > 0) {
  32700. var verticesCount = positions.length / 3;
  32701. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  32702. indices.push((firstIndex));
  32703. indices.push((firstIndex + 1));
  32704. indices.push(firstIndex + totalYRotationSteps + 1);
  32705. indices.push((firstIndex + totalYRotationSteps + 1));
  32706. indices.push((firstIndex + 1));
  32707. indices.push((firstIndex + totalYRotationSteps + 2));
  32708. }
  32709. }
  32710. }
  32711. // Sides
  32712. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32713. // Result
  32714. var vertexData = new VertexData();
  32715. vertexData.indices = indices;
  32716. vertexData.positions = positions;
  32717. vertexData.normals = normals;
  32718. vertexData.uvs = uvs;
  32719. return vertexData;
  32720. };
  32721. /**
  32722. * Creates the VertexData of the Cylinder or Cone.
  32723. */
  32724. VertexData.CreateCylinder = function (options) {
  32725. var height = options.height || 2;
  32726. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  32727. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  32728. var tessellation = options.tessellation || 24;
  32729. var subdivisions = options.subdivisions || 1;
  32730. var hasRings = options.hasRings ? true : false;
  32731. var enclose = options.enclose ? true : false;
  32732. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32733. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32734. var faceUV = options.faceUV || new Array(3);
  32735. var faceColors = options.faceColors;
  32736. // default face colors and UV if undefined
  32737. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  32738. var ringNb = (hasRings) ? subdivisions : 1;
  32739. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  32740. var f;
  32741. for (f = 0; f < surfaceNb; f++) {
  32742. if (faceColors && faceColors[f] === undefined) {
  32743. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32744. }
  32745. }
  32746. for (f = 0; f < surfaceNb; f++) {
  32747. if (faceUV && faceUV[f] === undefined) {
  32748. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32749. }
  32750. }
  32751. var indices = new Array();
  32752. var positions = new Array();
  32753. var normals = new Array();
  32754. var uvs = new Array();
  32755. var colors = new Array();
  32756. var angle_step = Math.PI * 2 * arc / tessellation;
  32757. var angle;
  32758. var h;
  32759. var radius;
  32760. var tan = (diameterBottom - diameterTop) / 2 / height;
  32761. var ringVertex = BABYLON.Vector3.Zero();
  32762. var ringNormal = BABYLON.Vector3.Zero();
  32763. var ringFirstVertex = BABYLON.Vector3.Zero();
  32764. var ringFirstNormal = BABYLON.Vector3.Zero();
  32765. var quadNormal = BABYLON.Vector3.Zero();
  32766. var Y = BABYLON.Axis.Y;
  32767. // positions, normals, uvs
  32768. var i;
  32769. var j;
  32770. var r;
  32771. var ringIdx = 1;
  32772. var s = 1; // surface index
  32773. var cs = 0;
  32774. var v = 0;
  32775. for (i = 0; i <= subdivisions; i++) {
  32776. h = i / subdivisions;
  32777. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  32778. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  32779. for (r = 0; r < ringIdx; r++) {
  32780. if (hasRings) {
  32781. s += r;
  32782. }
  32783. if (enclose) {
  32784. s += 2 * r;
  32785. }
  32786. for (j = 0; j <= tessellation; j++) {
  32787. angle = j * angle_step;
  32788. // position
  32789. ringVertex.x = Math.cos(-angle) * radius;
  32790. ringVertex.y = -height / 2 + h * height;
  32791. ringVertex.z = Math.sin(-angle) * radius;
  32792. // normal
  32793. if (diameterTop === 0 && i === subdivisions) {
  32794. // if no top cap, reuse former normals
  32795. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  32796. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  32797. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  32798. }
  32799. else {
  32800. ringNormal.x = ringVertex.x;
  32801. ringNormal.z = ringVertex.z;
  32802. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  32803. ringNormal.normalize();
  32804. }
  32805. // keep first ring vertex values for enclose
  32806. if (j === 0) {
  32807. ringFirstVertex.copyFrom(ringVertex);
  32808. ringFirstNormal.copyFrom(ringNormal);
  32809. }
  32810. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32811. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  32812. if (hasRings) {
  32813. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  32814. }
  32815. else {
  32816. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  32817. }
  32818. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  32819. if (faceColors) {
  32820. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  32821. }
  32822. }
  32823. // if enclose, add four vertices and their dedicated normals
  32824. if (arc !== 1 && enclose) {
  32825. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  32826. positions.push(0, ringVertex.y, 0);
  32827. positions.push(0, ringVertex.y, 0);
  32828. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  32829. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  32830. quadNormal.normalize();
  32831. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32832. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  32833. quadNormal.normalize();
  32834. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  32835. if (hasRings) {
  32836. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  32837. }
  32838. else {
  32839. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  32840. }
  32841. uvs.push(faceUV[s + 1].x, v);
  32842. uvs.push(faceUV[s + 1].z, v);
  32843. if (hasRings) {
  32844. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  32845. }
  32846. else {
  32847. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  32848. }
  32849. uvs.push(faceUV[s + 2].x, v);
  32850. uvs.push(faceUV[s + 2].z, v);
  32851. if (faceColors) {
  32852. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32853. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  32854. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32855. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  32856. }
  32857. }
  32858. if (cs !== s) {
  32859. cs = s;
  32860. }
  32861. }
  32862. }
  32863. // indices
  32864. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  32865. var s;
  32866. i = 0;
  32867. for (s = 0; s < subdivisions; s++) {
  32868. var i0 = 0;
  32869. var i1 = 0;
  32870. var i2 = 0;
  32871. var i3 = 0;
  32872. for (j = 0; j < tessellation; j++) {
  32873. i0 = i * (e + 1) + j;
  32874. i1 = (i + 1) * (e + 1) + j;
  32875. i2 = i * (e + 1) + (j + 1);
  32876. i3 = (i + 1) * (e + 1) + (j + 1);
  32877. indices.push(i0, i1, i2);
  32878. indices.push(i3, i2, i1);
  32879. }
  32880. if (arc !== 1 && enclose) {
  32881. indices.push(i0 + 2, i1 + 2, i2 + 2);
  32882. indices.push(i3 + 2, i2 + 2, i1 + 2);
  32883. indices.push(i0 + 4, i1 + 4, i2 + 4);
  32884. indices.push(i3 + 4, i2 + 4, i1 + 4);
  32885. }
  32886. i = (hasRings) ? (i + 2) : (i + 1);
  32887. }
  32888. // Caps
  32889. var createCylinderCap = function (isTop) {
  32890. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  32891. if (radius === 0) {
  32892. return;
  32893. }
  32894. // Cap positions, normals & uvs
  32895. var angle;
  32896. var circleVector;
  32897. var i;
  32898. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  32899. var c = null;
  32900. if (faceColors) {
  32901. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  32902. }
  32903. // cap center
  32904. var vbase = positions.length / 3;
  32905. var offset = isTop ? height / 2 : -height / 2;
  32906. var center = new BABYLON.Vector3(0, offset, 0);
  32907. positions.push(center.x, center.y, center.z);
  32908. normals.push(0, isTop ? 1 : -1, 0);
  32909. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  32910. if (c) {
  32911. colors.push(c.r, c.g, c.b, c.a);
  32912. }
  32913. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  32914. for (i = 0; i <= tessellation; i++) {
  32915. angle = Math.PI * 2 * i * arc / tessellation;
  32916. var cos = Math.cos(-angle);
  32917. var sin = Math.sin(-angle);
  32918. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  32919. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  32920. positions.push(circleVector.x, circleVector.y, circleVector.z);
  32921. normals.push(0, isTop ? 1 : -1, 0);
  32922. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  32923. if (c) {
  32924. colors.push(c.r, c.g, c.b, c.a);
  32925. }
  32926. }
  32927. // Cap indices
  32928. for (i = 0; i < tessellation; i++) {
  32929. if (!isTop) {
  32930. indices.push(vbase);
  32931. indices.push(vbase + (i + 1));
  32932. indices.push(vbase + (i + 2));
  32933. }
  32934. else {
  32935. indices.push(vbase);
  32936. indices.push(vbase + (i + 2));
  32937. indices.push(vbase + (i + 1));
  32938. }
  32939. }
  32940. };
  32941. // add caps to geometry
  32942. createCylinderCap(false);
  32943. createCylinderCap(true);
  32944. // Sides
  32945. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  32946. var vertexData = new VertexData();
  32947. vertexData.indices = indices;
  32948. vertexData.positions = positions;
  32949. vertexData.normals = normals;
  32950. vertexData.uvs = uvs;
  32951. if (faceColors) {
  32952. vertexData.colors = colors;
  32953. }
  32954. return vertexData;
  32955. };
  32956. /**
  32957. * Creates the VertexData of the Torus.
  32958. */
  32959. VertexData.CreateTorus = function (options) {
  32960. var indices = [];
  32961. var positions = [];
  32962. var normals = [];
  32963. var uvs = [];
  32964. var diameter = options.diameter || 1;
  32965. var thickness = options.thickness || 0.5;
  32966. var tessellation = options.tessellation || 16;
  32967. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32968. var stride = tessellation + 1;
  32969. for (var i = 0; i <= tessellation; i++) {
  32970. var u = i / tessellation;
  32971. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  32972. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  32973. for (var j = 0; j <= tessellation; j++) {
  32974. var v = 1 - j / tessellation;
  32975. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  32976. var dx = Math.cos(innerAngle);
  32977. var dy = Math.sin(innerAngle);
  32978. // Create a vertex.
  32979. var normal = new BABYLON.Vector3(dx, dy, 0);
  32980. var position = normal.scale(thickness / 2);
  32981. var textureCoordinate = new BABYLON.Vector2(u, v);
  32982. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  32983. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  32984. positions.push(position.x, position.y, position.z);
  32985. normals.push(normal.x, normal.y, normal.z);
  32986. uvs.push(textureCoordinate.x, textureCoordinate.y);
  32987. // And create indices for two triangles.
  32988. var nextI = (i + 1) % stride;
  32989. var nextJ = (j + 1) % stride;
  32990. indices.push(i * stride + j);
  32991. indices.push(i * stride + nextJ);
  32992. indices.push(nextI * stride + j);
  32993. indices.push(i * stride + nextJ);
  32994. indices.push(nextI * stride + nextJ);
  32995. indices.push(nextI * stride + j);
  32996. }
  32997. }
  32998. // Sides
  32999. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33000. // Result
  33001. var vertexData = new VertexData();
  33002. vertexData.indices = indices;
  33003. vertexData.positions = positions;
  33004. vertexData.normals = normals;
  33005. vertexData.uvs = uvs;
  33006. return vertexData;
  33007. };
  33008. /**
  33009. * Creates the VertexData of the LineSystem.
  33010. */
  33011. VertexData.CreateLineSystem = function (options) {
  33012. var indices = [];
  33013. var positions = [];
  33014. var lines = options.lines;
  33015. var colors = options.colors;
  33016. var vertexColors = [];
  33017. var idx = 0;
  33018. for (var l = 0; l < lines.length; l++) {
  33019. var points = lines[l];
  33020. for (var index = 0; index < points.length; index++) {
  33021. positions.push(points[index].x, points[index].y, points[index].z);
  33022. if (colors) {
  33023. var color = colors[l];
  33024. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33025. }
  33026. if (index > 0) {
  33027. indices.push(idx - 1);
  33028. indices.push(idx);
  33029. }
  33030. idx++;
  33031. }
  33032. }
  33033. var vertexData = new VertexData();
  33034. vertexData.indices = indices;
  33035. vertexData.positions = positions;
  33036. if (colors) {
  33037. vertexData.colors = vertexColors;
  33038. }
  33039. return vertexData;
  33040. };
  33041. /**
  33042. * Create the VertexData of the DashedLines.
  33043. */
  33044. VertexData.CreateDashedLines = function (options) {
  33045. var dashSize = options.dashSize || 3;
  33046. var gapSize = options.gapSize || 1;
  33047. var dashNb = options.dashNb || 200;
  33048. var points = options.points;
  33049. var positions = new Array();
  33050. var indices = new Array();
  33051. var curvect = BABYLON.Vector3.Zero();
  33052. var lg = 0;
  33053. var nb = 0;
  33054. var shft = 0;
  33055. var dashshft = 0;
  33056. var curshft = 0;
  33057. var idx = 0;
  33058. var i = 0;
  33059. for (i = 0; i < points.length - 1; i++) {
  33060. points[i + 1].subtractToRef(points[i], curvect);
  33061. lg += curvect.length();
  33062. }
  33063. shft = lg / dashNb;
  33064. dashshft = dashSize * shft / (dashSize + gapSize);
  33065. for (i = 0; i < points.length - 1; i++) {
  33066. points[i + 1].subtractToRef(points[i], curvect);
  33067. nb = Math.floor(curvect.length() / shft);
  33068. curvect.normalize();
  33069. for (var j = 0; j < nb; j++) {
  33070. curshft = shft * j;
  33071. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33072. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33073. indices.push(idx, idx + 1);
  33074. idx += 2;
  33075. }
  33076. }
  33077. // Result
  33078. var vertexData = new VertexData();
  33079. vertexData.positions = positions;
  33080. vertexData.indices = indices;
  33081. return vertexData;
  33082. };
  33083. /**
  33084. * Creates the VertexData of the Ground.
  33085. */
  33086. VertexData.CreateGround = function (options) {
  33087. var indices = [];
  33088. var positions = [];
  33089. var normals = [];
  33090. var uvs = [];
  33091. var row, col;
  33092. var width = options.width || 1;
  33093. var height = options.height || 1;
  33094. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33095. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33096. for (row = 0; row <= subdivisionsY; row++) {
  33097. for (col = 0; col <= subdivisionsX; col++) {
  33098. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33099. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33100. positions.push(position.x, position.y, position.z);
  33101. normals.push(normal.x, normal.y, normal.z);
  33102. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  33103. }
  33104. }
  33105. for (row = 0; row < subdivisionsY; row++) {
  33106. for (col = 0; col < subdivisionsX; col++) {
  33107. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33108. indices.push(col + 1 + row * (subdivisionsX + 1));
  33109. indices.push(col + row * (subdivisionsX + 1));
  33110. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33111. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33112. indices.push(col + row * (subdivisionsX + 1));
  33113. }
  33114. }
  33115. // Result
  33116. var vertexData = new VertexData();
  33117. vertexData.indices = indices;
  33118. vertexData.positions = positions;
  33119. vertexData.normals = normals;
  33120. vertexData.uvs = uvs;
  33121. return vertexData;
  33122. };
  33123. /**
  33124. * Creates the VertexData of the TiledGround.
  33125. */
  33126. VertexData.CreateTiledGround = function (options) {
  33127. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  33128. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  33129. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  33130. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  33131. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33132. var precision = options.precision || { w: 1, h: 1 };
  33133. var indices = new Array();
  33134. var positions = new Array();
  33135. var normals = new Array();
  33136. var uvs = new Array();
  33137. var row, col, tileRow, tileCol;
  33138. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33139. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33140. precision.w = (precision.w < 1) ? 1 : precision.w;
  33141. precision.h = (precision.h < 1) ? 1 : precision.h;
  33142. var tileSize = {
  33143. 'w': (xmax - xmin) / subdivisions.w,
  33144. 'h': (zmax - zmin) / subdivisions.h
  33145. };
  33146. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33147. // Indices
  33148. var base = positions.length / 3;
  33149. var rowLength = precision.w + 1;
  33150. for (row = 0; row < precision.h; row++) {
  33151. for (col = 0; col < precision.w; col++) {
  33152. var square = [
  33153. base + col + row * rowLength,
  33154. base + (col + 1) + row * rowLength,
  33155. base + (col + 1) + (row + 1) * rowLength,
  33156. base + col + (row + 1) * rowLength
  33157. ];
  33158. indices.push(square[1]);
  33159. indices.push(square[2]);
  33160. indices.push(square[3]);
  33161. indices.push(square[0]);
  33162. indices.push(square[1]);
  33163. indices.push(square[3]);
  33164. }
  33165. }
  33166. // Position, normals and uvs
  33167. var position = BABYLON.Vector3.Zero();
  33168. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33169. for (row = 0; row <= precision.h; row++) {
  33170. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33171. for (col = 0; col <= precision.w; col++) {
  33172. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33173. position.y = 0;
  33174. positions.push(position.x, position.y, position.z);
  33175. normals.push(normal.x, normal.y, normal.z);
  33176. uvs.push(col / precision.w, row / precision.h);
  33177. }
  33178. }
  33179. }
  33180. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33181. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33182. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33183. }
  33184. }
  33185. // Result
  33186. var vertexData = new VertexData();
  33187. vertexData.indices = indices;
  33188. vertexData.positions = positions;
  33189. vertexData.normals = normals;
  33190. vertexData.uvs = uvs;
  33191. return vertexData;
  33192. };
  33193. /**
  33194. * Creates the VertexData of the Ground designed from a heightmap.
  33195. */
  33196. VertexData.CreateGroundFromHeightMap = function (options) {
  33197. var indices = [];
  33198. var positions = [];
  33199. var normals = [];
  33200. var uvs = [];
  33201. var row, col;
  33202. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  33203. // Vertices
  33204. for (row = 0; row <= options.subdivisions; row++) {
  33205. for (col = 0; col <= options.subdivisions; col++) {
  33206. 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));
  33207. // Compute height
  33208. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33209. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33210. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33211. var r = options.buffer[pos] / 255.0;
  33212. var g = options.buffer[pos + 1] / 255.0;
  33213. var b = options.buffer[pos + 2] / 255.0;
  33214. var gradient = r * filter.r + g * filter.g + b * filter.b;
  33215. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33216. // Add vertex
  33217. positions.push(position.x, position.y, position.z);
  33218. normals.push(0, 0, 0);
  33219. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33220. }
  33221. }
  33222. // Indices
  33223. for (row = 0; row < options.subdivisions; row++) {
  33224. for (col = 0; col < options.subdivisions; col++) {
  33225. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33226. indices.push(col + 1 + row * (options.subdivisions + 1));
  33227. indices.push(col + row * (options.subdivisions + 1));
  33228. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33229. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33230. indices.push(col + row * (options.subdivisions + 1));
  33231. }
  33232. }
  33233. // Normals
  33234. VertexData.ComputeNormals(positions, indices, normals);
  33235. // Result
  33236. var vertexData = new VertexData();
  33237. vertexData.indices = indices;
  33238. vertexData.positions = positions;
  33239. vertexData.normals = normals;
  33240. vertexData.uvs = uvs;
  33241. return vertexData;
  33242. };
  33243. /**
  33244. * Creates the VertexData of the Plane.
  33245. */
  33246. VertexData.CreatePlane = function (options) {
  33247. var indices = [];
  33248. var positions = [];
  33249. var normals = [];
  33250. var uvs = [];
  33251. var width = options.width || options.size || 1;
  33252. var height = options.height || options.size || 1;
  33253. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33254. // Vertices
  33255. var halfWidth = width / 2.0;
  33256. var halfHeight = height / 2.0;
  33257. positions.push(-halfWidth, -halfHeight, 0);
  33258. normals.push(0, 0, -1.0);
  33259. uvs.push(0.0, 0.0);
  33260. positions.push(halfWidth, -halfHeight, 0);
  33261. normals.push(0, 0, -1.0);
  33262. uvs.push(1.0, 0.0);
  33263. positions.push(halfWidth, halfHeight, 0);
  33264. normals.push(0, 0, -1.0);
  33265. uvs.push(1.0, 1.0);
  33266. positions.push(-halfWidth, halfHeight, 0);
  33267. normals.push(0, 0, -1.0);
  33268. uvs.push(0.0, 1.0);
  33269. // Indices
  33270. indices.push(0);
  33271. indices.push(1);
  33272. indices.push(2);
  33273. indices.push(0);
  33274. indices.push(2);
  33275. indices.push(3);
  33276. // Sides
  33277. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33278. // Result
  33279. var vertexData = new VertexData();
  33280. vertexData.indices = indices;
  33281. vertexData.positions = positions;
  33282. vertexData.normals = normals;
  33283. vertexData.uvs = uvs;
  33284. return vertexData;
  33285. };
  33286. /**
  33287. * Creates the VertexData of the Disc or regular Polygon.
  33288. */
  33289. VertexData.CreateDisc = function (options) {
  33290. var positions = new Array();
  33291. var indices = new Array();
  33292. var normals = new Array();
  33293. var uvs = new Array();
  33294. var radius = options.radius || 0.5;
  33295. var tessellation = options.tessellation || 64;
  33296. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33297. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33298. // positions and uvs
  33299. positions.push(0, 0, 0); // disc center first
  33300. uvs.push(0.5, 0.5);
  33301. var theta = Math.PI * 2 * arc;
  33302. var step = theta / tessellation;
  33303. for (var a = 0; a < theta; a += step) {
  33304. var x = Math.cos(a);
  33305. var y = Math.sin(a);
  33306. var u = (x + 1) / 2;
  33307. var v = (1 - y) / 2;
  33308. positions.push(radius * x, radius * y, 0);
  33309. uvs.push(u, v);
  33310. }
  33311. if (arc === 1) {
  33312. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33313. uvs.push(uvs[2], uvs[3]);
  33314. }
  33315. //indices
  33316. var vertexNb = positions.length / 3;
  33317. for (var i = 1; i < vertexNb - 1; i++) {
  33318. indices.push(i + 1, 0, i);
  33319. }
  33320. // result
  33321. VertexData.ComputeNormals(positions, indices, normals);
  33322. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33323. var vertexData = new VertexData();
  33324. vertexData.indices = indices;
  33325. vertexData.positions = positions;
  33326. vertexData.normals = normals;
  33327. vertexData.uvs = uvs;
  33328. return vertexData;
  33329. };
  33330. /**
  33331. * Re-creates the VertexData of the Polygon for sideOrientation.
  33332. */
  33333. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  33334. var faceUV = fUV || new Array(3);
  33335. var faceColors = fColors;
  33336. var colors = [];
  33337. // default face colors and UV if undefined
  33338. for (var f = 0; f < 3; f++) {
  33339. if (faceUV[f] === undefined) {
  33340. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33341. }
  33342. if (faceColors && faceColors[f] === undefined) {
  33343. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33344. }
  33345. }
  33346. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33347. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33348. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33349. var indices = polygon.getIndices();
  33350. // set face colours and textures
  33351. var idx = 0;
  33352. var face = 0;
  33353. for (var index = 0; index < normals.length; index += 3) {
  33354. //Edge Face no. 1
  33355. if (Math.abs(normals[index + 1]) < 0.001) {
  33356. face = 1;
  33357. }
  33358. //Top Face no. 0
  33359. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  33360. face = 0;
  33361. }
  33362. //Bottom Face no. 2
  33363. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  33364. face = 2;
  33365. }
  33366. idx = index / 3;
  33367. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  33368. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  33369. if (faceColors) {
  33370. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  33371. }
  33372. }
  33373. // sides
  33374. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  33375. // Result
  33376. var vertexData = new VertexData();
  33377. vertexData.indices = indices;
  33378. vertexData.positions = positions;
  33379. vertexData.normals = normals;
  33380. vertexData.uvs = uvs;
  33381. if (faceColors) {
  33382. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33383. vertexData.colors = totalColors;
  33384. }
  33385. return vertexData;
  33386. };
  33387. /**
  33388. * Creates the VertexData of the IcoSphere.
  33389. */
  33390. VertexData.CreateIcoSphere = function (options) {
  33391. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33392. var radius = options.radius || 1;
  33393. var flat = (options.flat === undefined) ? true : options.flat;
  33394. var subdivisions = options.subdivisions || 4;
  33395. var radiusX = options.radiusX || radius;
  33396. var radiusY = options.radiusY || radius;
  33397. var radiusZ = options.radiusZ || radius;
  33398. var t = (1 + Math.sqrt(5)) / 2;
  33399. // 12 vertex x,y,z
  33400. var ico_vertices = [
  33401. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33402. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33403. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33404. ];
  33405. // index of 3 vertex makes a face of icopshere
  33406. var ico_indices = [
  33407. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33408. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33409. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33410. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33411. ];
  33412. // vertex for uv have aliased position, not for UV
  33413. var vertices_unalias_id = [
  33414. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33415. // vertex alias
  33416. 0,
  33417. 2,
  33418. 3,
  33419. 3,
  33420. 3,
  33421. 4,
  33422. 7,
  33423. 8,
  33424. 9,
  33425. 9,
  33426. 10,
  33427. 11 // 23: B + 12
  33428. ];
  33429. // uv as integer step (not pixels !)
  33430. var ico_vertexuv = [
  33431. 5, 1, 3, 1, 6, 4, 0, 0,
  33432. 5, 3, 4, 2, 2, 2, 4, 0,
  33433. 2, 0, 1, 1, 6, 0, 6, 2,
  33434. // vertex alias (for same vertex on different faces)
  33435. 0, 4,
  33436. 3, 3,
  33437. 4, 4,
  33438. 3, 1,
  33439. 4, 2,
  33440. 4, 4,
  33441. 0, 2,
  33442. 1, 1,
  33443. 2, 2,
  33444. 3, 3,
  33445. 1, 3,
  33446. 2, 4 // 23: B + 12
  33447. ];
  33448. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33449. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33450. // First island of uv mapping
  33451. // v = 4h 3+ 2
  33452. // v = 3h 9+ 4
  33453. // v = 2h 9+ 5 B
  33454. // v = 1h 9 1 0
  33455. // v = 0h 3 8 7 A
  33456. // u = 0 1 2 3 4 5 6 *a
  33457. // Second island of uv mapping
  33458. // v = 4h 0+ B+ 4+
  33459. // v = 3h A+ 2+
  33460. // v = 2h 7+ 6 3+
  33461. // v = 1h 8+ 3+
  33462. // v = 0h
  33463. // u = 0 1 2 3 4 5 6 *a
  33464. // Face layout on texture UV mapping
  33465. // ============
  33466. // \ 4 /\ 16 / ======
  33467. // \ / \ / /\ 11 /
  33468. // \/ 7 \/ / \ /
  33469. // ======= / 10 \/
  33470. // /\ 17 /\ =======
  33471. // / \ / \ \ 15 /\
  33472. // / 8 \/ 12 \ \ / \
  33473. // ============ \/ 6 \
  33474. // \ 18 /\ ============
  33475. // \ / \ \ 5 /\ 0 /
  33476. // \/ 13 \ \ / \ /
  33477. // ======= \/ 1 \/
  33478. // =============
  33479. // /\ 19 /\ 2 /\
  33480. // / \ / \ / \
  33481. // / 14 \/ 9 \/ 3 \
  33482. // ===================
  33483. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33484. var ustep = 138 / 1024;
  33485. var vstep = 239 / 1024;
  33486. var uoffset = 60 / 1024;
  33487. var voffset = 26 / 1024;
  33488. // Second island should have margin, not to touch the first island
  33489. // avoid any borderline artefact in pixel rounding
  33490. var island_u_offset = -40 / 1024;
  33491. var island_v_offset = +20 / 1024;
  33492. // face is either island 0 or 1 :
  33493. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33494. var island = [
  33495. 0, 0, 0, 0, 1,
  33496. 0, 0, 1, 1, 0,
  33497. 0, 0, 1, 1, 0,
  33498. 0, 1, 1, 1, 0 // 15 - 19
  33499. ];
  33500. var indices = new Array();
  33501. var positions = new Array();
  33502. var normals = new Array();
  33503. var uvs = new Array();
  33504. var current_indice = 0;
  33505. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33506. var face_vertex_pos = new Array(3);
  33507. var face_vertex_uv = new Array(3);
  33508. var v012;
  33509. for (v012 = 0; v012 < 3; v012++) {
  33510. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33511. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33512. }
  33513. // create all with normals
  33514. for (var face = 0; face < 20; face++) {
  33515. // 3 vertex per face
  33516. for (v012 = 0; v012 < 3; v012++) {
  33517. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33518. var v_id = ico_indices[3 * face + v012];
  33519. // vertex have 3D position (x,y,z)
  33520. 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]);
  33521. // Normalize to get normal, then scale to radius
  33522. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33523. // uv Coordinates from vertex ID
  33524. 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);
  33525. }
  33526. // Subdivide the face (interpolate pos, norm, uv)
  33527. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33528. // - norm is linear interpolation of vertex corner normal
  33529. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33530. // - uv is linear interpolation
  33531. //
  33532. // Topology is as below for sub-divide by 2
  33533. // vertex shown as v0,v1,v2
  33534. // interp index is i1 to progress in range [v0,v1[
  33535. // interp index is i2 to progress in range [v0,v2[
  33536. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33537. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33538. //
  33539. //
  33540. // i2 v2
  33541. // ^ ^
  33542. // / / \
  33543. // / / \
  33544. // / / \
  33545. // / / (0,1) \
  33546. // / #---------\
  33547. // / / \ (0,0)'/ \
  33548. // / / \ / \
  33549. // / / \ / \
  33550. // / / (0,0) \ / (1,0) \
  33551. // / #---------#---------\
  33552. // v0 v1
  33553. //
  33554. // --------------------> i1
  33555. //
  33556. // interp of (i1,i2):
  33557. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33558. // along i1 : lerp(x0,x1, i1/(S-i2))
  33559. //
  33560. // centroid of triangle is needed to get help normal computation
  33561. // (c1,c2) are used for centroid location
  33562. var interp_vertex = function (i1, i2, c1, c2) {
  33563. // vertex is interpolated from
  33564. // - face_vertex_pos[0..2]
  33565. // - face_vertex_uv[0..2]
  33566. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33567. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33568. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33569. pos_interp.normalize();
  33570. var vertex_normal;
  33571. if (flat) {
  33572. // in flat mode, recalculate normal as face centroid normal
  33573. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33574. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33575. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33576. }
  33577. else {
  33578. // in smooth mode, recalculate normal from each single vertex position
  33579. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33580. }
  33581. // Vertex normal need correction due to X,Y,Z radius scaling
  33582. vertex_normal.x /= radiusX;
  33583. vertex_normal.y /= radiusY;
  33584. vertex_normal.z /= radiusZ;
  33585. vertex_normal.normalize();
  33586. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33587. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33588. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33589. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33590. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33591. uvs.push(uv_interp.x, uv_interp.y);
  33592. // push each vertex has member of a face
  33593. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33594. indices.push(current_indice);
  33595. current_indice++;
  33596. };
  33597. for (var i2 = 0; i2 < subdivisions; i2++) {
  33598. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33599. // face : (i1,i2) for /\ :
  33600. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33601. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33602. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33603. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33604. if (i1 + i2 + 1 < subdivisions) {
  33605. // face : (i1,i2)' for \/ :
  33606. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33607. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33608. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33609. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33610. }
  33611. }
  33612. }
  33613. }
  33614. // Sides
  33615. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33616. // Result
  33617. var vertexData = new VertexData();
  33618. vertexData.indices = indices;
  33619. vertexData.positions = positions;
  33620. vertexData.normals = normals;
  33621. vertexData.uvs = uvs;
  33622. return vertexData;
  33623. };
  33624. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33625. /**
  33626. * Creates the VertexData of the Polyhedron.
  33627. */
  33628. VertexData.CreatePolyhedron = function (options) {
  33629. // provided polyhedron types :
  33630. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33631. // 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)
  33632. var polyhedra = [];
  33633. 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]] };
  33634. 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]] };
  33635. polyhedra[2] = {
  33636. 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]],
  33637. 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]]
  33638. };
  33639. polyhedra[3] = {
  33640. 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]],
  33641. 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]]
  33642. };
  33643. polyhedra[4] = {
  33644. 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]],
  33645. 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]]
  33646. };
  33647. 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]] };
  33648. 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]] };
  33649. 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]] };
  33650. 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]] };
  33651. 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]] };
  33652. 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]] };
  33653. 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]] };
  33654. 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]] };
  33655. 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]] };
  33656. polyhedra[14] = {
  33657. 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]],
  33658. 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]]
  33659. };
  33660. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33661. var size = options.size;
  33662. var sizeX = options.sizeX || size || 1;
  33663. var sizeY = options.sizeY || size || 1;
  33664. var sizeZ = options.sizeZ || size || 1;
  33665. var data = options.custom || polyhedra[type];
  33666. var nbfaces = data.face.length;
  33667. var faceUV = options.faceUV || new Array(nbfaces);
  33668. var faceColors = options.faceColors;
  33669. var flat = (options.flat === undefined) ? true : options.flat;
  33670. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33671. var positions = new Array();
  33672. var indices = new Array();
  33673. var normals = new Array();
  33674. var uvs = new Array();
  33675. var colors = new Array();
  33676. var index = 0;
  33677. var faceIdx = 0; // face cursor in the array "indexes"
  33678. var indexes = new Array();
  33679. var i = 0;
  33680. var f = 0;
  33681. var u, v, ang, x, y, tmp;
  33682. // default face colors and UV if undefined
  33683. if (flat) {
  33684. for (f = 0; f < nbfaces; f++) {
  33685. if (faceColors && faceColors[f] === undefined) {
  33686. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33687. }
  33688. if (faceUV && faceUV[f] === undefined) {
  33689. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33690. }
  33691. }
  33692. }
  33693. if (!flat) {
  33694. for (i = 0; i < data.vertex.length; i++) {
  33695. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33696. uvs.push(0, 0);
  33697. }
  33698. for (f = 0; f < nbfaces; f++) {
  33699. for (i = 0; i < data.face[f].length - 2; i++) {
  33700. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33701. }
  33702. }
  33703. }
  33704. else {
  33705. for (f = 0; f < nbfaces; f++) {
  33706. var fl = data.face[f].length; // number of vertices of the current face
  33707. ang = 2 * Math.PI / fl;
  33708. x = 0.5 * Math.tan(ang / 2);
  33709. y = 0.5;
  33710. // positions, uvs, colors
  33711. for (i = 0; i < fl; i++) {
  33712. // positions
  33713. 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);
  33714. indexes.push(index);
  33715. index++;
  33716. // uvs
  33717. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33718. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33719. uvs.push(u, v);
  33720. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33721. y = x * Math.sin(ang) + y * Math.cos(ang);
  33722. x = tmp;
  33723. // colors
  33724. if (faceColors) {
  33725. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33726. }
  33727. }
  33728. // indices from indexes
  33729. for (i = 0; i < fl - 2; i++) {
  33730. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33731. }
  33732. faceIdx += fl;
  33733. }
  33734. }
  33735. VertexData.ComputeNormals(positions, indices, normals);
  33736. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33737. var vertexData = new VertexData();
  33738. vertexData.positions = positions;
  33739. vertexData.indices = indices;
  33740. vertexData.normals = normals;
  33741. vertexData.uvs = uvs;
  33742. if (faceColors && flat) {
  33743. vertexData.colors = colors;
  33744. }
  33745. return vertexData;
  33746. };
  33747. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  33748. /**
  33749. * Creates the VertexData of the Torus Knot.
  33750. */
  33751. VertexData.CreateTorusKnot = function (options) {
  33752. var indices = new Array();
  33753. var positions = new Array();
  33754. var normals = new Array();
  33755. var uvs = new Array();
  33756. var radius = options.radius || 2;
  33757. var tube = options.tube || 0.5;
  33758. var radialSegments = options.radialSegments || 32;
  33759. var tubularSegments = options.tubularSegments || 32;
  33760. var p = options.p || 2;
  33761. var q = options.q || 3;
  33762. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33763. // Helper
  33764. var getPos = function (angle) {
  33765. var cu = Math.cos(angle);
  33766. var su = Math.sin(angle);
  33767. var quOverP = q / p * angle;
  33768. var cs = Math.cos(quOverP);
  33769. var tx = radius * (2 + cs) * 0.5 * cu;
  33770. var ty = radius * (2 + cs) * su * 0.5;
  33771. var tz = radius * Math.sin(quOverP) * 0.5;
  33772. return new BABYLON.Vector3(tx, ty, tz);
  33773. };
  33774. // Vertices
  33775. var i;
  33776. var j;
  33777. for (i = 0; i <= radialSegments; i++) {
  33778. var modI = i % radialSegments;
  33779. var u = modI / radialSegments * 2 * p * Math.PI;
  33780. var p1 = getPos(u);
  33781. var p2 = getPos(u + 0.01);
  33782. var tang = p2.subtract(p1);
  33783. var n = p2.add(p1);
  33784. var bitan = BABYLON.Vector3.Cross(tang, n);
  33785. n = BABYLON.Vector3.Cross(bitan, tang);
  33786. bitan.normalize();
  33787. n.normalize();
  33788. for (j = 0; j < tubularSegments; j++) {
  33789. var modJ = j % tubularSegments;
  33790. var v = modJ / tubularSegments * 2 * Math.PI;
  33791. var cx = -tube * Math.cos(v);
  33792. var cy = tube * Math.sin(v);
  33793. positions.push(p1.x + cx * n.x + cy * bitan.x);
  33794. positions.push(p1.y + cx * n.y + cy * bitan.y);
  33795. positions.push(p1.z + cx * n.z + cy * bitan.z);
  33796. uvs.push(i / radialSegments);
  33797. uvs.push(j / tubularSegments);
  33798. }
  33799. }
  33800. for (i = 0; i < radialSegments; i++) {
  33801. for (j = 0; j < tubularSegments; j++) {
  33802. var jNext = (j + 1) % tubularSegments;
  33803. var a = i * tubularSegments + j;
  33804. var b = (i + 1) * tubularSegments + j;
  33805. var c = (i + 1) * tubularSegments + jNext;
  33806. var d = i * tubularSegments + jNext;
  33807. indices.push(d);
  33808. indices.push(b);
  33809. indices.push(a);
  33810. indices.push(d);
  33811. indices.push(c);
  33812. indices.push(b);
  33813. }
  33814. }
  33815. // Normals
  33816. VertexData.ComputeNormals(positions, indices, normals);
  33817. // Sides
  33818. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33819. // Result
  33820. var vertexData = new VertexData();
  33821. vertexData.indices = indices;
  33822. vertexData.positions = positions;
  33823. vertexData.normals = normals;
  33824. vertexData.uvs = uvs;
  33825. return vertexData;
  33826. };
  33827. // Tools
  33828. /**
  33829. * @param {any} - positions (number[] or Float32Array)
  33830. * @param {any} - indices (number[] or Uint16Array)
  33831. * @param {any} - normals (number[] or Float32Array)
  33832. * options (optional) :
  33833. * facetPositions : optional array of facet positions (vector3)
  33834. * facetNormals : optional array of facet normals (vector3)
  33835. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  33836. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  33837. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  33838. * bbSize : optional bounding box size data, required for facetPartitioning computation
  33839. * bInfo : optional bounding info, required for facetPartitioning computation
  33840. * useRightHandedSystem: optional boolean to for right handed system computation
  33841. * depthSort : optional boolean to enable the facet depth sort computation
  33842. * distanceTo : optional Vector3 to compute the facet depth from this location
  33843. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  33844. */
  33845. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  33846. // temporary scalar variables
  33847. var index = 0; // facet index
  33848. var p1p2x = 0.0; // p1p2 vector x coordinate
  33849. var p1p2y = 0.0; // p1p2 vector y coordinate
  33850. var p1p2z = 0.0; // p1p2 vector z coordinate
  33851. var p3p2x = 0.0; // p3p2 vector x coordinate
  33852. var p3p2y = 0.0; // p3p2 vector y coordinate
  33853. var p3p2z = 0.0; // p3p2 vector z coordinate
  33854. var faceNormalx = 0.0; // facet normal x coordinate
  33855. var faceNormaly = 0.0; // facet normal y coordinate
  33856. var faceNormalz = 0.0; // facet normal z coordinate
  33857. var length = 0.0; // facet normal length before normalization
  33858. var v1x = 0; // vector1 x index in the positions array
  33859. var v1y = 0; // vector1 y index in the positions array
  33860. var v1z = 0; // vector1 z index in the positions array
  33861. var v2x = 0; // vector2 x index in the positions array
  33862. var v2y = 0; // vector2 y index in the positions array
  33863. var v2z = 0; // vector2 z index in the positions array
  33864. var v3x = 0; // vector3 x index in the positions array
  33865. var v3y = 0; // vector3 y index in the positions array
  33866. var v3z = 0; // vector3 z index in the positions array
  33867. var computeFacetNormals = false;
  33868. var computeFacetPositions = false;
  33869. var computeFacetPartitioning = false;
  33870. var computeDepthSort = false;
  33871. var faceNormalSign = 1;
  33872. var ratio = 0;
  33873. var distanceTo = null;
  33874. if (options) {
  33875. computeFacetNormals = (options.facetNormals) ? true : false;
  33876. computeFacetPositions = (options.facetPositions) ? true : false;
  33877. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  33878. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  33879. ratio = options.ratio || 0;
  33880. computeDepthSort = (options.depthSort) ? true : false;
  33881. distanceTo = (options.distanceTo);
  33882. if (computeDepthSort) {
  33883. if (distanceTo === undefined) {
  33884. distanceTo = BABYLON.Vector3.Zero();
  33885. }
  33886. var depthSortedFacets = options.depthSortedFacets;
  33887. }
  33888. }
  33889. // facetPartitioning reinit if needed
  33890. var xSubRatio = 0;
  33891. var ySubRatio = 0;
  33892. var zSubRatio = 0;
  33893. var subSq = 0;
  33894. if (computeFacetPartitioning && options && options.bbSize) {
  33895. var ox = 0; // X partitioning index for facet position
  33896. var oy = 0; // Y partinioning index for facet position
  33897. var oz = 0; // Z partinioning index for facet position
  33898. var b1x = 0; // X partitioning index for facet v1 vertex
  33899. var b1y = 0; // Y partitioning index for facet v1 vertex
  33900. var b1z = 0; // z partitioning index for facet v1 vertex
  33901. var b2x = 0; // X partitioning index for facet v2 vertex
  33902. var b2y = 0; // Y partitioning index for facet v2 vertex
  33903. var b2z = 0; // Z partitioning index for facet v2 vertex
  33904. var b3x = 0; // X partitioning index for facet v3 vertex
  33905. var b3y = 0; // Y partitioning index for facet v3 vertex
  33906. var b3z = 0; // Z partitioning index for facet v3 vertex
  33907. var block_idx_o = 0; // facet barycenter block index
  33908. var block_idx_v1 = 0; // v1 vertex block index
  33909. var block_idx_v2 = 0; // v2 vertex block index
  33910. var block_idx_v3 = 0; // v3 vertex block index
  33911. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  33912. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  33913. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  33914. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  33915. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  33916. subSq = options.subDiv.max * options.subDiv.max;
  33917. options.facetPartitioning.length = 0;
  33918. }
  33919. // reset the normals
  33920. for (index = 0; index < positions.length; index++) {
  33921. normals[index] = 0.0;
  33922. }
  33923. // Loop : 1 indice triplet = 1 facet
  33924. var nbFaces = (indices.length / 3) | 0;
  33925. for (index = 0; index < nbFaces; index++) {
  33926. // get the indexes of the coordinates of each vertex of the facet
  33927. v1x = indices[index * 3] * 3;
  33928. v1y = v1x + 1;
  33929. v1z = v1x + 2;
  33930. v2x = indices[index * 3 + 1] * 3;
  33931. v2y = v2x + 1;
  33932. v2z = v2x + 2;
  33933. v3x = indices[index * 3 + 2] * 3;
  33934. v3y = v3x + 1;
  33935. v3z = v3x + 2;
  33936. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  33937. p1p2y = positions[v1y] - positions[v2y];
  33938. p1p2z = positions[v1z] - positions[v2z];
  33939. p3p2x = positions[v3x] - positions[v2x];
  33940. p3p2y = positions[v3y] - positions[v2y];
  33941. p3p2z = positions[v3z] - positions[v2z];
  33942. // compute the face normal with the cross product
  33943. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  33944. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  33945. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  33946. // normalize this normal and store it in the array facetData
  33947. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  33948. length = (length === 0) ? 1.0 : length;
  33949. faceNormalx /= length;
  33950. faceNormaly /= length;
  33951. faceNormalz /= length;
  33952. if (computeFacetNormals && options) {
  33953. options.facetNormals[index].x = faceNormalx;
  33954. options.facetNormals[index].y = faceNormaly;
  33955. options.facetNormals[index].z = faceNormalz;
  33956. }
  33957. if (computeFacetPositions && options) {
  33958. // compute and the facet barycenter coordinates in the array facetPositions
  33959. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  33960. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  33961. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  33962. }
  33963. if (computeFacetPartitioning && options) {
  33964. // store the facet indexes in arrays in the main facetPartitioning array :
  33965. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  33966. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  33967. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  33968. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  33969. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33970. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33971. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33972. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33973. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33974. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33975. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  33976. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  33977. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  33978. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  33979. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  33980. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  33981. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  33982. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  33983. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  33984. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  33985. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  33986. // push each facet index in each block containing the vertex
  33987. options.facetPartitioning[block_idx_v1].push(index);
  33988. if (block_idx_v2 != block_idx_v1) {
  33989. options.facetPartitioning[block_idx_v2].push(index);
  33990. }
  33991. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  33992. options.facetPartitioning[block_idx_v3].push(index);
  33993. }
  33994. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  33995. options.facetPartitioning[block_idx_o].push(index);
  33996. }
  33997. }
  33998. if (computeDepthSort && options && options.facetPositions) {
  33999. var dsf = depthSortedFacets[index];
  34000. dsf.ind = index * 3;
  34001. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34002. }
  34003. // compute the normals anyway
  34004. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34005. normals[v1y] += faceNormaly;
  34006. normals[v1z] += faceNormalz;
  34007. normals[v2x] += faceNormalx;
  34008. normals[v2y] += faceNormaly;
  34009. normals[v2z] += faceNormalz;
  34010. normals[v3x] += faceNormalx;
  34011. normals[v3y] += faceNormaly;
  34012. normals[v3z] += faceNormalz;
  34013. }
  34014. // last normalization of each normal
  34015. for (index = 0; index < normals.length / 3; index++) {
  34016. faceNormalx = normals[index * 3];
  34017. faceNormaly = normals[index * 3 + 1];
  34018. faceNormalz = normals[index * 3 + 2];
  34019. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34020. length = (length === 0) ? 1.0 : length;
  34021. faceNormalx /= length;
  34022. faceNormaly /= length;
  34023. faceNormalz /= length;
  34024. normals[index * 3] = faceNormalx;
  34025. normals[index * 3 + 1] = faceNormaly;
  34026. normals[index * 3 + 2] = faceNormalz;
  34027. }
  34028. };
  34029. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34030. var li = indices.length;
  34031. var ln = normals.length;
  34032. var i;
  34033. var n;
  34034. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34035. switch (sideOrientation) {
  34036. case BABYLON.Mesh.FRONTSIDE:
  34037. // nothing changed
  34038. break;
  34039. case BABYLON.Mesh.BACKSIDE:
  34040. var tmp;
  34041. // indices
  34042. for (i = 0; i < li; i += 3) {
  34043. tmp = indices[i];
  34044. indices[i] = indices[i + 2];
  34045. indices[i + 2] = tmp;
  34046. }
  34047. // normals
  34048. for (n = 0; n < ln; n++) {
  34049. normals[n] = -normals[n];
  34050. }
  34051. break;
  34052. case BABYLON.Mesh.DOUBLESIDE:
  34053. // positions
  34054. var lp = positions.length;
  34055. var l = lp / 3;
  34056. for (var p = 0; p < lp; p++) {
  34057. positions[lp + p] = positions[p];
  34058. }
  34059. // indices
  34060. for (i = 0; i < li; i += 3) {
  34061. indices[i + li] = indices[i + 2] + l;
  34062. indices[i + 1 + li] = indices[i + 1] + l;
  34063. indices[i + 2 + li] = indices[i] + l;
  34064. }
  34065. // normals
  34066. for (n = 0; n < ln; n++) {
  34067. normals[ln + n] = -normals[n];
  34068. }
  34069. // uvs
  34070. var lu = uvs.length;
  34071. var u = 0;
  34072. for (u = 0; u < lu; u++) {
  34073. uvs[u + lu] = uvs[u];
  34074. }
  34075. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34076. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  34077. u = 0;
  34078. for (i = 0; i < lu / 2; i++) {
  34079. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  34080. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  34081. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  34082. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  34083. u += 2;
  34084. }
  34085. break;
  34086. }
  34087. };
  34088. /**
  34089. * Creates a new VertexData from the imported parameters.
  34090. */
  34091. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34092. var vertexData = new VertexData();
  34093. // positions
  34094. var positions = parsedVertexData.positions;
  34095. if (positions) {
  34096. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34097. }
  34098. // normals
  34099. var normals = parsedVertexData.normals;
  34100. if (normals) {
  34101. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34102. }
  34103. // tangents
  34104. var tangents = parsedVertexData.tangents;
  34105. if (tangents) {
  34106. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  34107. }
  34108. // uvs
  34109. var uvs = parsedVertexData.uvs;
  34110. if (uvs) {
  34111. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34112. }
  34113. // uv2s
  34114. var uv2s = parsedVertexData.uv2s;
  34115. if (uv2s) {
  34116. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34117. }
  34118. // uv3s
  34119. var uv3s = parsedVertexData.uv3s;
  34120. if (uv3s) {
  34121. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34122. }
  34123. // uv4s
  34124. var uv4s = parsedVertexData.uv4s;
  34125. if (uv4s) {
  34126. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34127. }
  34128. // uv5s
  34129. var uv5s = parsedVertexData.uv5s;
  34130. if (uv5s) {
  34131. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34132. }
  34133. // uv6s
  34134. var uv6s = parsedVertexData.uv6s;
  34135. if (uv6s) {
  34136. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34137. }
  34138. // colors
  34139. var colors = parsedVertexData.colors;
  34140. if (colors) {
  34141. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34142. }
  34143. // matricesIndices
  34144. var matricesIndices = parsedVertexData.matricesIndices;
  34145. if (matricesIndices) {
  34146. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34147. }
  34148. // matricesWeights
  34149. var matricesWeights = parsedVertexData.matricesWeights;
  34150. if (matricesWeights) {
  34151. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34152. }
  34153. // indices
  34154. var indices = parsedVertexData.indices;
  34155. if (indices) {
  34156. vertexData.indices = indices;
  34157. }
  34158. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34159. };
  34160. return VertexData;
  34161. }());
  34162. BABYLON.VertexData = VertexData;
  34163. })(BABYLON || (BABYLON = {}));
  34164. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34165. var BABYLON;
  34166. (function (BABYLON) {
  34167. /**
  34168. * Class used to store geometry data (vertex buffers + index buffer)
  34169. */
  34170. var Geometry = /** @class */ (function () {
  34171. /**
  34172. * Creates a new geometry
  34173. * @param id defines the unique ID
  34174. * @param scene defines the hosting scene
  34175. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  34176. * @param updatable defines if geometry must be updatable (false by default)
  34177. * @param mesh defines the mesh that will be associated with the geometry
  34178. */
  34179. function Geometry(id, scene, vertexData, updatable, mesh) {
  34180. if (updatable === void 0) { updatable = false; }
  34181. if (mesh === void 0) { mesh = null; }
  34182. /**
  34183. * Gets the delay loading state of the geometry (none by default which means not delayed)
  34184. */
  34185. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34186. this._totalVertices = 0;
  34187. this._isDisposed = false;
  34188. this._indexBufferIsUpdatable = false;
  34189. this.id = id;
  34190. this._engine = scene.getEngine();
  34191. this._meshes = [];
  34192. this._scene = scene;
  34193. //Init vertex buffer cache
  34194. this._vertexBuffers = {};
  34195. this._indices = [];
  34196. this._updatable = updatable;
  34197. // vertexData
  34198. if (vertexData) {
  34199. this.setAllVerticesData(vertexData, updatable);
  34200. }
  34201. else {
  34202. this._totalVertices = 0;
  34203. this._indices = [];
  34204. }
  34205. if (this._engine.getCaps().vertexArrayObject) {
  34206. this._vertexArrayObjects = {};
  34207. }
  34208. // applyToMesh
  34209. if (mesh) {
  34210. if (mesh.getClassName() === "LinesMesh") {
  34211. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34212. this.updateExtend();
  34213. }
  34214. this.applyToMesh(mesh);
  34215. mesh.computeWorldMatrix(true);
  34216. }
  34217. }
  34218. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34219. /**
  34220. * 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
  34221. */
  34222. get: function () {
  34223. return this._boundingBias;
  34224. },
  34225. /**
  34226. * 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
  34227. */
  34228. set: function (value) {
  34229. if (this._boundingBias && this._boundingBias.equals(value)) {
  34230. return;
  34231. }
  34232. this._boundingBias = value.clone();
  34233. this.updateBoundingInfo(true, null);
  34234. },
  34235. enumerable: true,
  34236. configurable: true
  34237. });
  34238. /**
  34239. * Static function used to attach a new empty geometry to a mesh
  34240. * @param mesh defines the mesh to attach the geometry to
  34241. * @returns the new {BABYLON.Geometry}
  34242. */
  34243. Geometry.CreateGeometryForMesh = function (mesh) {
  34244. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  34245. geometry.applyToMesh(mesh);
  34246. return geometry;
  34247. };
  34248. Object.defineProperty(Geometry.prototype, "extend", {
  34249. /**
  34250. * Gets the current extend of the geometry
  34251. */
  34252. get: function () {
  34253. return this._extend;
  34254. },
  34255. enumerable: true,
  34256. configurable: true
  34257. });
  34258. /**
  34259. * Gets the hosting scene
  34260. * @returns the hosting {BABYLON.Scene}
  34261. */
  34262. Geometry.prototype.getScene = function () {
  34263. return this._scene;
  34264. };
  34265. /**
  34266. * Gets the hosting engine
  34267. * @returns the hosting {BABYLON.Engine}
  34268. */
  34269. Geometry.prototype.getEngine = function () {
  34270. return this._engine;
  34271. };
  34272. /**
  34273. * Defines if the geometry is ready to use
  34274. * @returns true if the geometry is ready to be used
  34275. */
  34276. Geometry.prototype.isReady = function () {
  34277. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34278. };
  34279. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  34280. /**
  34281. * Gets a value indicating that the geometry should not be serialized
  34282. */
  34283. get: function () {
  34284. for (var index = 0; index < this._meshes.length; index++) {
  34285. if (!this._meshes[index].doNotSerialize) {
  34286. return false;
  34287. }
  34288. }
  34289. return true;
  34290. },
  34291. enumerable: true,
  34292. configurable: true
  34293. });
  34294. /** @ignore */
  34295. Geometry.prototype._rebuild = function () {
  34296. if (this._vertexArrayObjects) {
  34297. this._vertexArrayObjects = {};
  34298. }
  34299. // Index buffer
  34300. if (this._meshes.length !== 0 && this._indices) {
  34301. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34302. }
  34303. // Vertex buffers
  34304. for (var key in this._vertexBuffers) {
  34305. var vertexBuffer = this._vertexBuffers[key];
  34306. vertexBuffer._rebuild();
  34307. }
  34308. };
  34309. /**
  34310. * Affects all gemetry data in one call
  34311. * @param vertexData defines the geometry data
  34312. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  34313. */
  34314. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34315. vertexData.applyToGeometry(this, updatable);
  34316. this.notifyUpdate();
  34317. };
  34318. /**
  34319. * Set specific vertex data
  34320. * @param kind defines the data kind (Position, normal, etc...)
  34321. * @param data defines the vertex data to use
  34322. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  34323. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  34324. */
  34325. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34326. if (updatable === void 0) { updatable = false; }
  34327. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34328. this.setVerticesBuffer(buffer);
  34329. };
  34330. /**
  34331. * Removes a specific vertex data
  34332. * @param kind defines the data kind (Position, normal, etc...)
  34333. */
  34334. Geometry.prototype.removeVerticesData = function (kind) {
  34335. if (this._vertexBuffers[kind]) {
  34336. this._vertexBuffers[kind].dispose();
  34337. delete this._vertexBuffers[kind];
  34338. }
  34339. };
  34340. /**
  34341. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  34342. * @param buffer defines the vertex buffer to use
  34343. */
  34344. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34345. var kind = buffer.getKind();
  34346. if (this._vertexBuffers[kind]) {
  34347. this._vertexBuffers[kind].dispose();
  34348. }
  34349. this._vertexBuffers[kind] = buffer;
  34350. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34351. var data = buffer.getData();
  34352. var stride = buffer.getStrideSize();
  34353. this._totalVertices = data.length / stride;
  34354. this.updateExtend(data, stride);
  34355. this._resetPointsArrayCache();
  34356. var meshes = this._meshes;
  34357. var numOfMeshes = meshes.length;
  34358. for (var index = 0; index < numOfMeshes; index++) {
  34359. var mesh = meshes[index];
  34360. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34361. mesh._createGlobalSubMesh(false);
  34362. mesh.computeWorldMatrix(true);
  34363. }
  34364. }
  34365. this.notifyUpdate(kind);
  34366. if (this._vertexArrayObjects) {
  34367. this._disposeVertexArrayObjects();
  34368. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  34369. }
  34370. };
  34371. /**
  34372. * Update a specific vertex buffer
  34373. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  34374. * It will do nothing if the buffer is not updatable
  34375. * @param kind defines the data kind (Position, normal, etc...)
  34376. * @param data defines the data to use
  34377. * @param offset defines the offset in the target buffer where to store the data
  34378. */
  34379. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34380. var vertexBuffer = this.getVertexBuffer(kind);
  34381. if (!vertexBuffer) {
  34382. return;
  34383. }
  34384. vertexBuffer.updateDirectly(data, offset);
  34385. this.notifyUpdate(kind);
  34386. };
  34387. /**
  34388. * Update a specific vertex buffer
  34389. * This function will create a new buffer if the current one is not updatable
  34390. * @param kind defines the data kind (Position, normal, etc...)
  34391. * @param data defines the data to use
  34392. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  34393. */
  34394. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34395. if (updateExtends === void 0) { updateExtends = false; }
  34396. var vertexBuffer = this.getVertexBuffer(kind);
  34397. if (!vertexBuffer) {
  34398. return;
  34399. }
  34400. vertexBuffer.update(data);
  34401. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34402. var stride = vertexBuffer.getStrideSize();
  34403. this._totalVertices = data.length / stride;
  34404. this.updateBoundingInfo(updateExtends, data);
  34405. }
  34406. this.notifyUpdate(kind);
  34407. };
  34408. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34409. if (updateExtends) {
  34410. this.updateExtend(data);
  34411. }
  34412. var meshes = this._meshes;
  34413. var numOfMeshes = meshes.length;
  34414. this._resetPointsArrayCache();
  34415. for (var index = 0; index < numOfMeshes; index++) {
  34416. var mesh = meshes[index];
  34417. if (updateExtends) {
  34418. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34419. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34420. var subMesh = mesh.subMeshes[subIndex];
  34421. subMesh.refreshBoundingInfo();
  34422. }
  34423. }
  34424. }
  34425. };
  34426. /** @ignore */
  34427. Geometry.prototype._bind = function (effect, indexToBind) {
  34428. if (!effect) {
  34429. return;
  34430. }
  34431. if (indexToBind === undefined) {
  34432. indexToBind = this._indexBuffer;
  34433. }
  34434. var vbs = this.getVertexBuffers();
  34435. if (!vbs) {
  34436. return;
  34437. }
  34438. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  34439. this._engine.bindBuffers(vbs, indexToBind, effect);
  34440. return;
  34441. }
  34442. // Using VAO
  34443. if (!this._vertexArrayObjects[effect.key]) {
  34444. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  34445. }
  34446. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  34447. };
  34448. /**
  34449. * Gets total number of vertices
  34450. * @returns the total number of vertices
  34451. */
  34452. Geometry.prototype.getTotalVertices = function () {
  34453. if (!this.isReady()) {
  34454. return 0;
  34455. }
  34456. return this._totalVertices;
  34457. };
  34458. /**
  34459. * Gets a specific vertex data attached to this geometry
  34460. * @param kind defines the data kind (Position, normal, etc...)
  34461. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34462. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  34463. * @returns a float array containing vertex data
  34464. */
  34465. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  34466. var vertexBuffer = this.getVertexBuffer(kind);
  34467. if (!vertexBuffer) {
  34468. return null;
  34469. }
  34470. var orig = vertexBuffer.getData();
  34471. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  34472. return orig;
  34473. }
  34474. else {
  34475. var len = orig.length;
  34476. var copy = [];
  34477. for (var i = 0; i < len; i++) {
  34478. copy.push(orig[i]);
  34479. }
  34480. return copy;
  34481. }
  34482. };
  34483. /**
  34484. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  34485. * @param kind defines the data kind (Position, normal, etc...)
  34486. * @returns true if the vertex buffer with the specified kind is updatable
  34487. */
  34488. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  34489. var vb = this._vertexBuffers[kind];
  34490. if (!vb) {
  34491. return false;
  34492. }
  34493. return vb.isUpdatable();
  34494. };
  34495. /**
  34496. * Gets a specific vertex buffer
  34497. * @param kind defines the data kind (Position, normal, etc...)
  34498. * @returns a {BABYLON.VertexBuffer}
  34499. */
  34500. Geometry.prototype.getVertexBuffer = function (kind) {
  34501. if (!this.isReady()) {
  34502. return null;
  34503. }
  34504. return this._vertexBuffers[kind];
  34505. };
  34506. /**
  34507. * Returns all vertex buffers
  34508. * @return an object holding all vertex buffers indexed by kind
  34509. */
  34510. Geometry.prototype.getVertexBuffers = function () {
  34511. if (!this.isReady()) {
  34512. return null;
  34513. }
  34514. return this._vertexBuffers;
  34515. };
  34516. /**
  34517. * Gets a boolean indicating if specific vertex buffer is present
  34518. * @param kind defines the data kind (Position, normal, etc...)
  34519. * @returns true if data is present
  34520. */
  34521. Geometry.prototype.isVerticesDataPresent = function (kind) {
  34522. if (!this._vertexBuffers) {
  34523. if (this._delayInfo) {
  34524. return this._delayInfo.indexOf(kind) !== -1;
  34525. }
  34526. return false;
  34527. }
  34528. return this._vertexBuffers[kind] !== undefined;
  34529. };
  34530. /**
  34531. * Gets a list of all attached data kinds (Position, normal, etc...)
  34532. * @returns a list of string containing all kinds
  34533. */
  34534. Geometry.prototype.getVerticesDataKinds = function () {
  34535. var result = [];
  34536. var kind;
  34537. if (!this._vertexBuffers && this._delayInfo) {
  34538. for (kind in this._delayInfo) {
  34539. result.push(kind);
  34540. }
  34541. }
  34542. else {
  34543. for (kind in this._vertexBuffers) {
  34544. result.push(kind);
  34545. }
  34546. }
  34547. return result;
  34548. };
  34549. /**
  34550. * Update index buffer
  34551. * @param indices defines the indices to store in the index buffer
  34552. * @param offset defines the offset in the target buffer where to store the data
  34553. */
  34554. Geometry.prototype.updateIndices = function (indices, offset) {
  34555. if (!this._indexBuffer) {
  34556. return;
  34557. }
  34558. if (!this._indexBufferIsUpdatable) {
  34559. this.setIndices(indices, null, true);
  34560. }
  34561. else {
  34562. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  34563. }
  34564. };
  34565. /**
  34566. * Creates a new index buffer
  34567. * @param indices defines the indices to store in the index buffer
  34568. * @param totalVertices defines the total number of vertices (could be null)
  34569. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  34570. */
  34571. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  34572. if (totalVertices === void 0) { totalVertices = null; }
  34573. if (updatable === void 0) { updatable = false; }
  34574. if (this._indexBuffer) {
  34575. this._engine._releaseBuffer(this._indexBuffer);
  34576. }
  34577. this._disposeVertexArrayObjects();
  34578. this._indices = indices;
  34579. this._indexBufferIsUpdatable = updatable;
  34580. if (this._meshes.length !== 0 && this._indices) {
  34581. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  34582. }
  34583. if (totalVertices != undefined) {
  34584. this._totalVertices = totalVertices;
  34585. }
  34586. var meshes = this._meshes;
  34587. var numOfMeshes = meshes.length;
  34588. for (var index = 0; index < numOfMeshes; index++) {
  34589. meshes[index]._createGlobalSubMesh(true);
  34590. }
  34591. this.notifyUpdate();
  34592. };
  34593. /**
  34594. * Return the total number of indices
  34595. * @returns the total number of indices
  34596. */
  34597. Geometry.prototype.getTotalIndices = function () {
  34598. if (!this.isReady()) {
  34599. return 0;
  34600. }
  34601. return this._indices.length;
  34602. };
  34603. /**
  34604. * Gets the index buffer array
  34605. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  34606. * @returns the index buffer array
  34607. */
  34608. Geometry.prototype.getIndices = function (copyWhenShared) {
  34609. if (!this.isReady()) {
  34610. return null;
  34611. }
  34612. var orig = this._indices;
  34613. if (!copyWhenShared || this._meshes.length === 1) {
  34614. return orig;
  34615. }
  34616. else {
  34617. var len = orig.length;
  34618. var copy = [];
  34619. for (var i = 0; i < len; i++) {
  34620. copy.push(orig[i]);
  34621. }
  34622. return copy;
  34623. }
  34624. };
  34625. /**
  34626. * Gets the index buffer
  34627. * @return the index buffer
  34628. */
  34629. Geometry.prototype.getIndexBuffer = function () {
  34630. if (!this.isReady()) {
  34631. return null;
  34632. }
  34633. return this._indexBuffer;
  34634. };
  34635. /** @ignore */
  34636. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  34637. if (effect === void 0) { effect = null; }
  34638. if (!effect || !this._vertexArrayObjects) {
  34639. return;
  34640. }
  34641. if (this._vertexArrayObjects[effect.key]) {
  34642. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  34643. delete this._vertexArrayObjects[effect.key];
  34644. }
  34645. };
  34646. /**
  34647. * Release the associated resources for a specific mesh
  34648. * @param mesh defines the source mesh
  34649. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  34650. */
  34651. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  34652. var meshes = this._meshes;
  34653. var index = meshes.indexOf(mesh);
  34654. if (index === -1) {
  34655. return;
  34656. }
  34657. meshes.splice(index, 1);
  34658. mesh._geometry = null;
  34659. if (meshes.length === 0 && shouldDispose) {
  34660. this.dispose();
  34661. }
  34662. };
  34663. /**
  34664. * Apply current geometry to a given mesh
  34665. * @param mesh defines the mesh to apply geometry to
  34666. */
  34667. Geometry.prototype.applyToMesh = function (mesh) {
  34668. if (mesh._geometry === this) {
  34669. return;
  34670. }
  34671. var previousGeometry = mesh._geometry;
  34672. if (previousGeometry) {
  34673. previousGeometry.releaseForMesh(mesh);
  34674. }
  34675. var meshes = this._meshes;
  34676. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  34677. mesh._geometry = this;
  34678. this._scene.pushGeometry(this);
  34679. meshes.push(mesh);
  34680. if (this.isReady()) {
  34681. this._applyToMesh(mesh);
  34682. }
  34683. else {
  34684. mesh._boundingInfo = this._boundingInfo;
  34685. }
  34686. };
  34687. Geometry.prototype.updateExtend = function (data, stride) {
  34688. if (data === void 0) { data = null; }
  34689. if (!data) {
  34690. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  34691. }
  34692. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  34693. };
  34694. Geometry.prototype._applyToMesh = function (mesh) {
  34695. var numOfMeshes = this._meshes.length;
  34696. // vertexBuffers
  34697. for (var kind in this._vertexBuffers) {
  34698. if (numOfMeshes === 1) {
  34699. this._vertexBuffers[kind].create();
  34700. }
  34701. var buffer = this._vertexBuffers[kind].getBuffer();
  34702. if (buffer)
  34703. buffer.references = numOfMeshes;
  34704. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34705. if (!this._extend) {
  34706. this.updateExtend(this._vertexBuffers[kind].getData());
  34707. }
  34708. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34709. mesh._createGlobalSubMesh(false);
  34710. //bounding info was just created again, world matrix should be applied again.
  34711. mesh._updateBoundingInfo();
  34712. }
  34713. }
  34714. // indexBuffer
  34715. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  34716. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  34717. }
  34718. if (this._indexBuffer) {
  34719. this._indexBuffer.references = numOfMeshes;
  34720. }
  34721. };
  34722. Geometry.prototype.notifyUpdate = function (kind) {
  34723. if (this.onGeometryUpdated) {
  34724. this.onGeometryUpdated(this, kind);
  34725. }
  34726. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  34727. var mesh = _a[_i];
  34728. mesh._markSubMeshesAsAttributesDirty();
  34729. }
  34730. };
  34731. /**
  34732. * Load the geometry if it was flagged as delay loaded
  34733. * @param scene defines the hosting scene
  34734. * @param onLoaded defines a callback called when the geometry is loaded
  34735. */
  34736. Geometry.prototype.load = function (scene, onLoaded) {
  34737. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  34738. return;
  34739. }
  34740. if (this.isReady()) {
  34741. if (onLoaded) {
  34742. onLoaded();
  34743. }
  34744. return;
  34745. }
  34746. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  34747. this._queueLoad(scene, onLoaded);
  34748. };
  34749. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  34750. var _this = this;
  34751. if (!this.delayLoadingFile) {
  34752. return;
  34753. }
  34754. scene._addPendingData(this);
  34755. scene._loadFile(this.delayLoadingFile, function (data) {
  34756. if (!_this._delayLoadingFunction) {
  34757. return;
  34758. }
  34759. _this._delayLoadingFunction(JSON.parse(data), _this);
  34760. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  34761. _this._delayInfo = [];
  34762. scene._removePendingData(_this);
  34763. var meshes = _this._meshes;
  34764. var numOfMeshes = meshes.length;
  34765. for (var index = 0; index < numOfMeshes; index++) {
  34766. _this._applyToMesh(meshes[index]);
  34767. }
  34768. if (onLoaded) {
  34769. onLoaded();
  34770. }
  34771. }, undefined, true);
  34772. };
  34773. /**
  34774. * Invert the geometry to move from a right handed system to a left handed one.
  34775. */
  34776. Geometry.prototype.toLeftHanded = function () {
  34777. // Flip faces
  34778. var tIndices = this.getIndices(false);
  34779. if (tIndices != null && tIndices.length > 0) {
  34780. for (var i = 0; i < tIndices.length; i += 3) {
  34781. var tTemp = tIndices[i + 0];
  34782. tIndices[i + 0] = tIndices[i + 2];
  34783. tIndices[i + 2] = tTemp;
  34784. }
  34785. this.setIndices(tIndices);
  34786. }
  34787. // Negate position.z
  34788. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  34789. if (tPositions != null && tPositions.length > 0) {
  34790. for (var i = 0; i < tPositions.length; i += 3) {
  34791. tPositions[i + 2] = -tPositions[i + 2];
  34792. }
  34793. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  34794. }
  34795. // Negate normal.z
  34796. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  34797. if (tNormals != null && tNormals.length > 0) {
  34798. for (var i = 0; i < tNormals.length; i += 3) {
  34799. tNormals[i + 2] = -tNormals[i + 2];
  34800. }
  34801. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  34802. }
  34803. };
  34804. // Cache
  34805. /** @ignore */
  34806. Geometry.prototype._resetPointsArrayCache = function () {
  34807. this._positions = null;
  34808. };
  34809. /** @ignore */
  34810. Geometry.prototype._generatePointsArray = function () {
  34811. if (this._positions)
  34812. return true;
  34813. this._positions = [];
  34814. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34815. if (!data) {
  34816. return false;
  34817. }
  34818. for (var index = 0; index < data.length; index += 3) {
  34819. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  34820. }
  34821. return true;
  34822. };
  34823. /**
  34824. * Gets a value indicating if the geometry is disposed
  34825. * @returns true if the geometry was disposed
  34826. */
  34827. Geometry.prototype.isDisposed = function () {
  34828. return this._isDisposed;
  34829. };
  34830. Geometry.prototype._disposeVertexArrayObjects = function () {
  34831. if (this._vertexArrayObjects) {
  34832. for (var kind in this._vertexArrayObjects) {
  34833. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  34834. }
  34835. this._vertexArrayObjects = {};
  34836. }
  34837. };
  34838. /**
  34839. * Free all associated resources
  34840. */
  34841. Geometry.prototype.dispose = function () {
  34842. var meshes = this._meshes;
  34843. var numOfMeshes = meshes.length;
  34844. var index;
  34845. for (index = 0; index < numOfMeshes; index++) {
  34846. this.releaseForMesh(meshes[index]);
  34847. }
  34848. this._meshes = [];
  34849. this._disposeVertexArrayObjects();
  34850. for (var kind in this._vertexBuffers) {
  34851. this._vertexBuffers[kind].dispose();
  34852. }
  34853. this._vertexBuffers = {};
  34854. this._totalVertices = 0;
  34855. if (this._indexBuffer) {
  34856. this._engine._releaseBuffer(this._indexBuffer);
  34857. }
  34858. this._indexBuffer = null;
  34859. this._indices = [];
  34860. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34861. this.delayLoadingFile = null;
  34862. this._delayLoadingFunction = null;
  34863. this._delayInfo = [];
  34864. this._boundingInfo = null;
  34865. this._scene.removeGeometry(this);
  34866. this._isDisposed = true;
  34867. };
  34868. /**
  34869. * Clone the current geometry into a new geometry
  34870. * @param id defines the unique ID of the new geometry
  34871. * @returns a new geometry object
  34872. */
  34873. Geometry.prototype.copy = function (id) {
  34874. var vertexData = new BABYLON.VertexData();
  34875. vertexData.indices = [];
  34876. var indices = this.getIndices();
  34877. if (indices) {
  34878. for (var index = 0; index < indices.length; index++) {
  34879. vertexData.indices.push(indices[index]);
  34880. }
  34881. }
  34882. var updatable = false;
  34883. var stopChecking = false;
  34884. var kind;
  34885. for (kind in this._vertexBuffers) {
  34886. // using slice() to make a copy of the array and not just reference it
  34887. var data = this.getVerticesData(kind);
  34888. if (data instanceof Float32Array) {
  34889. vertexData.set(new Float32Array(data), kind);
  34890. }
  34891. else {
  34892. vertexData.set(data.slice(0), kind);
  34893. }
  34894. if (!stopChecking) {
  34895. var vb = this.getVertexBuffer(kind);
  34896. if (vb) {
  34897. updatable = vb.isUpdatable();
  34898. stopChecking = !updatable;
  34899. }
  34900. }
  34901. }
  34902. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  34903. geometry.delayLoadState = this.delayLoadState;
  34904. geometry.delayLoadingFile = this.delayLoadingFile;
  34905. geometry._delayLoadingFunction = this._delayLoadingFunction;
  34906. for (kind in this._delayInfo) {
  34907. geometry._delayInfo = geometry._delayInfo || [];
  34908. geometry._delayInfo.push(kind);
  34909. }
  34910. // Bounding info
  34911. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34912. return geometry;
  34913. };
  34914. /**
  34915. * Serialize the current geometry info (and not the vertices data) into a JSON object
  34916. * @return a JSON representation of the current geometry data (without the vertices data)
  34917. */
  34918. Geometry.prototype.serialize = function () {
  34919. var serializationObject = {};
  34920. serializationObject.id = this.id;
  34921. serializationObject.updatable = this._updatable;
  34922. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34923. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34924. }
  34925. return serializationObject;
  34926. };
  34927. Geometry.prototype.toNumberArray = function (origin) {
  34928. if (Array.isArray(origin)) {
  34929. return origin;
  34930. }
  34931. else {
  34932. return Array.prototype.slice.call(origin);
  34933. }
  34934. };
  34935. /**
  34936. * Serialize all vertices data into a JSON oject
  34937. * @returns a JSON representation of the current geometry data
  34938. */
  34939. Geometry.prototype.serializeVerticeData = function () {
  34940. var serializationObject = this.serialize();
  34941. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34942. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  34943. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34944. serializationObject.positions._updatable = true;
  34945. }
  34946. }
  34947. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34948. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  34949. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34950. serializationObject.normals._updatable = true;
  34951. }
  34952. }
  34953. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  34954. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  34955. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  34956. serializationObject.tangets._updatable = true;
  34957. }
  34958. }
  34959. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  34960. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  34961. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  34962. serializationObject.uvs._updatable = true;
  34963. }
  34964. }
  34965. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  34966. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  34967. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  34968. serializationObject.uv2s._updatable = true;
  34969. }
  34970. }
  34971. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  34972. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  34973. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  34974. serializationObject.uv3s._updatable = true;
  34975. }
  34976. }
  34977. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  34978. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  34979. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  34980. serializationObject.uv4s._updatable = true;
  34981. }
  34982. }
  34983. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  34984. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  34985. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  34986. serializationObject.uv5s._updatable = true;
  34987. }
  34988. }
  34989. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  34990. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  34991. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  34992. serializationObject.uv6s._updatable = true;
  34993. }
  34994. }
  34995. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  34996. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  34997. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  34998. serializationObject.colors._updatable = true;
  34999. }
  35000. }
  35001. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35002. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35003. serializationObject.matricesIndices._isExpanded = true;
  35004. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35005. serializationObject.matricesIndices._updatable = true;
  35006. }
  35007. }
  35008. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35009. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35010. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35011. serializationObject.matricesWeights._updatable = true;
  35012. }
  35013. }
  35014. serializationObject.indices = this.toNumberArray(this.getIndices());
  35015. return serializationObject;
  35016. };
  35017. // Statics
  35018. /**
  35019. * Extracts a clone of a mesh geometry
  35020. * @param mesh defines the source mesh
  35021. * @param id defines the unique ID of the new geometry object
  35022. * @returns the new geometry object
  35023. */
  35024. Geometry.ExtractFromMesh = function (mesh, id) {
  35025. var geometry = mesh._geometry;
  35026. if (!geometry) {
  35027. return null;
  35028. }
  35029. return geometry.copy(id);
  35030. };
  35031. /**
  35032. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35033. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35034. * Be aware Math.random() could cause collisions, but:
  35035. * "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"
  35036. * @returns a string containing a new GUID
  35037. */
  35038. Geometry.RandomId = function () {
  35039. return BABYLON.Tools.RandomId();
  35040. };
  35041. /** @ignore */
  35042. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  35043. var scene = mesh.getScene();
  35044. // Geometry
  35045. var geometryId = parsedGeometry.geometryId;
  35046. if (geometryId) {
  35047. var geometry = scene.getGeometryByID(geometryId);
  35048. if (geometry) {
  35049. geometry.applyToMesh(mesh);
  35050. }
  35051. }
  35052. else if (parsedGeometry instanceof ArrayBuffer) {
  35053. var binaryInfo = mesh._binaryInfo;
  35054. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35055. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35056. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35057. }
  35058. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35059. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35060. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35061. }
  35062. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  35063. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  35064. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  35065. }
  35066. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35067. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35068. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35069. }
  35070. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35071. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35072. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35073. }
  35074. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35075. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35076. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35077. }
  35078. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35079. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35080. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35081. }
  35082. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35083. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35084. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35085. }
  35086. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35087. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35088. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35089. }
  35090. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35091. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35092. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35093. }
  35094. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35095. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35096. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35097. }
  35098. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35099. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35100. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35101. }
  35102. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35103. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35104. mesh.setIndices(indicesData, null);
  35105. }
  35106. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35107. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35108. mesh.subMeshes = [];
  35109. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35110. var materialIndex = subMeshesData[(i * 5) + 0];
  35111. var verticesStart = subMeshesData[(i * 5) + 1];
  35112. var verticesCount = subMeshesData[(i * 5) + 2];
  35113. var indexStart = subMeshesData[(i * 5) + 3];
  35114. var indexCount = subMeshesData[(i * 5) + 4];
  35115. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35116. }
  35117. }
  35118. }
  35119. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35120. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  35121. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  35122. if (parsedGeometry.tangents) {
  35123. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  35124. }
  35125. if (parsedGeometry.uvs) {
  35126. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  35127. }
  35128. if (parsedGeometry.uvs2) {
  35129. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  35130. }
  35131. if (parsedGeometry.uvs3) {
  35132. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  35133. }
  35134. if (parsedGeometry.uvs4) {
  35135. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  35136. }
  35137. if (parsedGeometry.uvs5) {
  35138. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  35139. }
  35140. if (parsedGeometry.uvs6) {
  35141. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  35142. }
  35143. if (parsedGeometry.colors) {
  35144. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  35145. }
  35146. if (parsedGeometry.matricesIndices) {
  35147. if (!parsedGeometry.matricesIndices._isExpanded) {
  35148. var floatIndices = [];
  35149. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35150. var matricesIndex = parsedGeometry.matricesIndices[i];
  35151. floatIndices.push(matricesIndex & 0x000000FF);
  35152. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35153. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35154. floatIndices.push(matricesIndex >> 24);
  35155. }
  35156. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  35157. }
  35158. else {
  35159. delete parsedGeometry.matricesIndices._isExpanded;
  35160. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  35161. }
  35162. }
  35163. if (parsedGeometry.matricesIndicesExtra) {
  35164. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35165. var floatIndices = [];
  35166. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35167. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35168. floatIndices.push(matricesIndex & 0x000000FF);
  35169. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35170. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35171. floatIndices.push(matricesIndex >> 24);
  35172. }
  35173. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  35174. }
  35175. else {
  35176. delete parsedGeometry.matricesIndices._isExpanded;
  35177. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  35178. }
  35179. }
  35180. if (parsedGeometry.matricesWeights) {
  35181. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  35182. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  35183. }
  35184. if (parsedGeometry.matricesWeightsExtra) {
  35185. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  35186. }
  35187. mesh.setIndices(parsedGeometry.indices, null);
  35188. }
  35189. // SubMeshes
  35190. if (parsedGeometry.subMeshes) {
  35191. mesh.subMeshes = [];
  35192. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35193. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35194. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35195. }
  35196. }
  35197. // Flat shading
  35198. if (mesh._shouldGenerateFlatShading) {
  35199. mesh.convertToFlatShadedMesh();
  35200. delete mesh._shouldGenerateFlatShading;
  35201. }
  35202. // Update
  35203. mesh.computeWorldMatrix(true);
  35204. // Octree
  35205. var sceneOctree = scene.selectionOctree;
  35206. if (sceneOctree !== undefined && sceneOctree !== null) {
  35207. sceneOctree.addMesh(mesh);
  35208. }
  35209. };
  35210. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  35211. var epsilon = 1e-3;
  35212. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  35213. return;
  35214. }
  35215. var noInfluenceBoneIndex = 0.0;
  35216. if (parsedGeometry.skeletonId > -1) {
  35217. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  35218. if (!skeleton) {
  35219. return;
  35220. }
  35221. noInfluenceBoneIndex = skeleton.bones.length;
  35222. }
  35223. else {
  35224. return;
  35225. }
  35226. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35227. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  35228. var matricesWeights = parsedGeometry.matricesWeights;
  35229. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  35230. var influencers = parsedGeometry.numBoneInfluencer;
  35231. var size = matricesWeights.length;
  35232. for (var i = 0; i < size; i += 4) {
  35233. var weight = 0.0;
  35234. var firstZeroWeight = -1;
  35235. for (var j = 0; j < 4; j++) {
  35236. var w = matricesWeights[i + j];
  35237. weight += w;
  35238. if (w < epsilon && firstZeroWeight < 0) {
  35239. firstZeroWeight = j;
  35240. }
  35241. }
  35242. if (matricesWeightsExtra) {
  35243. for (var j = 0; j < 4; j++) {
  35244. var w = matricesWeightsExtra[i + j];
  35245. weight += w;
  35246. if (w < epsilon && firstZeroWeight < 0) {
  35247. firstZeroWeight = j + 4;
  35248. }
  35249. }
  35250. }
  35251. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  35252. firstZeroWeight = influencers - 1;
  35253. }
  35254. if (weight > epsilon) {
  35255. var mweight = 1.0 / weight;
  35256. for (var j = 0; j < 4; j++) {
  35257. matricesWeights[i + j] *= mweight;
  35258. }
  35259. if (matricesWeightsExtra) {
  35260. for (var j = 0; j < 4; j++) {
  35261. matricesWeightsExtra[i + j] *= mweight;
  35262. }
  35263. }
  35264. }
  35265. else {
  35266. if (firstZeroWeight >= 4) {
  35267. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  35268. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  35269. }
  35270. else {
  35271. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  35272. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  35273. }
  35274. }
  35275. }
  35276. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  35277. if (parsedGeometry.matricesWeightsExtra) {
  35278. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  35279. }
  35280. };
  35281. /**
  35282. * Create a new geometry from persisted data (Using .babylon file format)
  35283. * @param parsedVertexData defines the persisted data
  35284. * @param scene defines the hosting scene
  35285. * @param rootUrl defines the root url to use to load assets (like delayed data)
  35286. * @returns the new geometry object
  35287. */
  35288. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35289. if (scene.getGeometryByID(parsedVertexData.id)) {
  35290. return null; // null since geometry could be something else than a box...
  35291. }
  35292. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  35293. if (BABYLON.Tags) {
  35294. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35295. }
  35296. if (parsedVertexData.delayLoadingFile) {
  35297. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35298. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35299. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35300. geometry._delayInfo = [];
  35301. if (parsedVertexData.hasUVs) {
  35302. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35303. }
  35304. if (parsedVertexData.hasUVs2) {
  35305. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35306. }
  35307. if (parsedVertexData.hasUVs3) {
  35308. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35309. }
  35310. if (parsedVertexData.hasUVs4) {
  35311. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35312. }
  35313. if (parsedVertexData.hasUVs5) {
  35314. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35315. }
  35316. if (parsedVertexData.hasUVs6) {
  35317. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35318. }
  35319. if (parsedVertexData.hasColors) {
  35320. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35321. }
  35322. if (parsedVertexData.hasMatricesIndices) {
  35323. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35324. }
  35325. if (parsedVertexData.hasMatricesWeights) {
  35326. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35327. }
  35328. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35329. }
  35330. else {
  35331. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35332. }
  35333. scene.pushGeometry(geometry, true);
  35334. return geometry;
  35335. };
  35336. return Geometry;
  35337. }());
  35338. BABYLON.Geometry = Geometry;
  35339. // Primitives
  35340. /// Abstract class
  35341. /**
  35342. * Abstract class used to provide common services for all typed geometries
  35343. */
  35344. var _PrimitiveGeometry = /** @class */ (function (_super) {
  35345. __extends(_PrimitiveGeometry, _super);
  35346. /**
  35347. * Creates a new typed geometry
  35348. * @param id defines the unique ID of the geometry
  35349. * @param scene defines the hosting scene
  35350. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35351. * @param mesh defines the hosting mesh (can be null)
  35352. */
  35353. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  35354. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  35355. if (mesh === void 0) { mesh = null; }
  35356. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  35357. _this._canBeRegenerated = _canBeRegenerated;
  35358. _this._beingRegenerated = true;
  35359. _this.regenerate();
  35360. _this._beingRegenerated = false;
  35361. return _this;
  35362. }
  35363. /**
  35364. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  35365. * @returns true if the geometry can be regenerated
  35366. */
  35367. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  35368. return this._canBeRegenerated;
  35369. };
  35370. /**
  35371. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  35372. */
  35373. _PrimitiveGeometry.prototype.regenerate = function () {
  35374. if (!this._canBeRegenerated) {
  35375. return;
  35376. }
  35377. this._beingRegenerated = true;
  35378. this.setAllVerticesData(this._regenerateVertexData(), false);
  35379. this._beingRegenerated = false;
  35380. };
  35381. /**
  35382. * Clone the geometry
  35383. * @param id defines the unique ID of the new geometry
  35384. * @returns the new geometry
  35385. */
  35386. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  35387. return _super.prototype.copy.call(this, id);
  35388. };
  35389. // overrides
  35390. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35391. if (!this._beingRegenerated) {
  35392. return;
  35393. }
  35394. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35395. };
  35396. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  35397. if (!this._beingRegenerated) {
  35398. return;
  35399. }
  35400. _super.prototype.setVerticesData.call(this, kind, data, false);
  35401. };
  35402. // to override
  35403. /** @ignore */
  35404. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  35405. throw new Error("Abstract method");
  35406. };
  35407. _PrimitiveGeometry.prototype.copy = function (id) {
  35408. throw new Error("Must be overriden in sub-classes.");
  35409. };
  35410. _PrimitiveGeometry.prototype.serialize = function () {
  35411. var serializationObject = _super.prototype.serialize.call(this);
  35412. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35413. return serializationObject;
  35414. };
  35415. return _PrimitiveGeometry;
  35416. }(Geometry));
  35417. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  35418. /**
  35419. * Creates a ribbon geometry
  35420. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  35421. */
  35422. var RibbonGeometry = /** @class */ (function (_super) {
  35423. __extends(RibbonGeometry, _super);
  35424. /**
  35425. * Creates a ribbon geometry
  35426. * @param id defines the unique ID of the geometry
  35427. * @param scene defines the hosting scene
  35428. * @param pathArray defines the array of paths to use
  35429. * @param closeArray defines if the last path and the first path must be joined
  35430. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  35431. * @param offset defines the offset between points
  35432. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35433. * @param mesh defines the hosting mesh (can be null)
  35434. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35435. */
  35436. function RibbonGeometry(id, scene,
  35437. /**
  35438. * Defines the array of paths to use
  35439. */
  35440. pathArray,
  35441. /**
  35442. * Defines if the last and first points of each path in your pathArray must be joined
  35443. */
  35444. closeArray,
  35445. /**
  35446. * Defines if the last and first points of each path in your pathArray must be joined
  35447. */
  35448. closePath,
  35449. /**
  35450. * Defines the offset between points
  35451. */
  35452. offset, canBeRegenerated, mesh,
  35453. /**
  35454. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35455. */
  35456. side) {
  35457. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35458. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35459. _this.pathArray = pathArray;
  35460. _this.closeArray = closeArray;
  35461. _this.closePath = closePath;
  35462. _this.offset = offset;
  35463. _this.side = side;
  35464. return _this;
  35465. }
  35466. /** @ignore */
  35467. RibbonGeometry.prototype._regenerateVertexData = function () {
  35468. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35469. };
  35470. RibbonGeometry.prototype.copy = function (id) {
  35471. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  35472. };
  35473. return RibbonGeometry;
  35474. }(_PrimitiveGeometry));
  35475. BABYLON.RibbonGeometry = RibbonGeometry;
  35476. /**
  35477. * Creates a box geometry
  35478. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  35479. */
  35480. var BoxGeometry = /** @class */ (function (_super) {
  35481. __extends(BoxGeometry, _super);
  35482. /**
  35483. * Creates a box geometry
  35484. * @param id defines the unique ID of the geometry
  35485. * @param scene defines the hosting scene
  35486. * @param size defines the zise of the box (width, height and depth are the same)
  35487. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35488. * @param mesh defines the hosting mesh (can be null)
  35489. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35490. */
  35491. function BoxGeometry(id, scene,
  35492. /**
  35493. * Defines the zise of the box (width, height and depth are the same)
  35494. */
  35495. size, canBeRegenerated, mesh,
  35496. /**
  35497. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35498. */
  35499. side) {
  35500. if (mesh === void 0) { mesh = null; }
  35501. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35502. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35503. _this.size = size;
  35504. _this.side = side;
  35505. return _this;
  35506. }
  35507. BoxGeometry.prototype._regenerateVertexData = function () {
  35508. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35509. };
  35510. BoxGeometry.prototype.copy = function (id) {
  35511. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  35512. };
  35513. BoxGeometry.prototype.serialize = function () {
  35514. var serializationObject = _super.prototype.serialize.call(this);
  35515. serializationObject.size = this.size;
  35516. return serializationObject;
  35517. };
  35518. BoxGeometry.Parse = function (parsedBox, scene) {
  35519. if (scene.getGeometryByID(parsedBox.id)) {
  35520. return null; // null since geometry could be something else than a box...
  35521. }
  35522. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35523. if (BABYLON.Tags) {
  35524. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35525. }
  35526. scene.pushGeometry(box, true);
  35527. return box;
  35528. };
  35529. return BoxGeometry;
  35530. }(_PrimitiveGeometry));
  35531. BABYLON.BoxGeometry = BoxGeometry;
  35532. /**
  35533. * Creates a sphere geometry
  35534. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  35535. */
  35536. var SphereGeometry = /** @class */ (function (_super) {
  35537. __extends(SphereGeometry, _super);
  35538. /**
  35539. * Create a new sphere geometry
  35540. * @param id defines the unique ID of the geometry
  35541. * @param scene defines the hosting scene
  35542. * @param segments defines the number of segments to use to create the sphere
  35543. * @param diameter defines the diameter of the sphere
  35544. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35545. * @param mesh defines the hosting mesh (can be null)
  35546. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35547. */
  35548. function SphereGeometry(id, scene,
  35549. /**
  35550. * Defines the number of segments to use to create the sphere
  35551. */
  35552. segments,
  35553. /**
  35554. * Defines the diameter of the sphere
  35555. */
  35556. diameter, canBeRegenerated, mesh,
  35557. /**
  35558. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35559. */
  35560. side) {
  35561. if (mesh === void 0) { mesh = null; }
  35562. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35563. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35564. _this.segments = segments;
  35565. _this.diameter = diameter;
  35566. _this.side = side;
  35567. return _this;
  35568. }
  35569. SphereGeometry.prototype._regenerateVertexData = function () {
  35570. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35571. };
  35572. SphereGeometry.prototype.copy = function (id) {
  35573. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35574. };
  35575. SphereGeometry.prototype.serialize = function () {
  35576. var serializationObject = _super.prototype.serialize.call(this);
  35577. serializationObject.segments = this.segments;
  35578. serializationObject.diameter = this.diameter;
  35579. return serializationObject;
  35580. };
  35581. SphereGeometry.Parse = function (parsedSphere, scene) {
  35582. if (scene.getGeometryByID(parsedSphere.id)) {
  35583. return null; // null since geometry could be something else than a sphere...
  35584. }
  35585. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35586. if (BABYLON.Tags) {
  35587. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35588. }
  35589. scene.pushGeometry(sphere, true);
  35590. return sphere;
  35591. };
  35592. return SphereGeometry;
  35593. }(_PrimitiveGeometry));
  35594. BABYLON.SphereGeometry = SphereGeometry;
  35595. /**
  35596. * Creates a disc geometry
  35597. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  35598. */
  35599. var DiscGeometry = /** @class */ (function (_super) {
  35600. __extends(DiscGeometry, _super);
  35601. /**
  35602. * Creates a new disc geometry
  35603. * @param id defines the unique ID of the geometry
  35604. * @param scene defines the hosting scene
  35605. * @param radius defines the radius of the disc
  35606. * @param tessellation defines the tesselation factor to apply to the disc
  35607. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35608. * @param mesh defines the hosting mesh (can be null)
  35609. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35610. */
  35611. function DiscGeometry(id, scene,
  35612. /**
  35613. * Defines the radius of the disc
  35614. */
  35615. radius,
  35616. /**
  35617. * Defines the tesselation factor to apply to the disc
  35618. */
  35619. tessellation, canBeRegenerated, mesh,
  35620. /**
  35621. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35622. */
  35623. side) {
  35624. if (mesh === void 0) { mesh = null; }
  35625. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35626. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35627. _this.radius = radius;
  35628. _this.tessellation = tessellation;
  35629. _this.side = side;
  35630. return _this;
  35631. }
  35632. DiscGeometry.prototype._regenerateVertexData = function () {
  35633. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35634. };
  35635. DiscGeometry.prototype.copy = function (id) {
  35636. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35637. };
  35638. return DiscGeometry;
  35639. }(_PrimitiveGeometry));
  35640. BABYLON.DiscGeometry = DiscGeometry;
  35641. /**
  35642. * Creates a new cylinder geometry
  35643. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  35644. */
  35645. var CylinderGeometry = /** @class */ (function (_super) {
  35646. __extends(CylinderGeometry, _super);
  35647. /**
  35648. * Creates a new cylinder geometry
  35649. * @param id defines the unique ID of the geometry
  35650. * @param scene defines the hosting scene
  35651. * @param height defines the height of the cylinder
  35652. * @param diameterTop defines the diameter of the cylinder's top cap
  35653. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  35654. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  35655. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  35656. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35657. * @param mesh defines the hosting mesh (can be null)
  35658. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35659. */
  35660. function CylinderGeometry(id, scene,
  35661. /**
  35662. * Defines the height of the cylinder
  35663. */
  35664. height,
  35665. /**
  35666. * Defines the diameter of the cylinder's top cap
  35667. */
  35668. diameterTop,
  35669. /**
  35670. * Defines the diameter of the cylinder's bottom cap
  35671. */
  35672. diameterBottom,
  35673. /**
  35674. * Defines the tessellation factor to apply to the cylinder
  35675. */
  35676. tessellation,
  35677. /**
  35678. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  35679. */
  35680. subdivisions, canBeRegenerated, mesh,
  35681. /**
  35682. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35683. */
  35684. side) {
  35685. if (subdivisions === void 0) { subdivisions = 1; }
  35686. if (mesh === void 0) { mesh = null; }
  35687. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35688. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35689. _this.height = height;
  35690. _this.diameterTop = diameterTop;
  35691. _this.diameterBottom = diameterBottom;
  35692. _this.tessellation = tessellation;
  35693. _this.subdivisions = subdivisions;
  35694. _this.side = side;
  35695. return _this;
  35696. }
  35697. CylinderGeometry.prototype._regenerateVertexData = function () {
  35698. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35699. };
  35700. CylinderGeometry.prototype.copy = function (id) {
  35701. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35702. };
  35703. CylinderGeometry.prototype.serialize = function () {
  35704. var serializationObject = _super.prototype.serialize.call(this);
  35705. serializationObject.height = this.height;
  35706. serializationObject.diameterTop = this.diameterTop;
  35707. serializationObject.diameterBottom = this.diameterBottom;
  35708. serializationObject.tessellation = this.tessellation;
  35709. return serializationObject;
  35710. };
  35711. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  35712. if (scene.getGeometryByID(parsedCylinder.id)) {
  35713. return null; // null since geometry could be something else than a cylinder...
  35714. }
  35715. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35716. if (BABYLON.Tags) {
  35717. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35718. }
  35719. scene.pushGeometry(cylinder, true);
  35720. return cylinder;
  35721. };
  35722. return CylinderGeometry;
  35723. }(_PrimitiveGeometry));
  35724. BABYLON.CylinderGeometry = CylinderGeometry;
  35725. /**
  35726. * Creates a new torus geometry
  35727. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  35728. */
  35729. var TorusGeometry = /** @class */ (function (_super) {
  35730. __extends(TorusGeometry, _super);
  35731. /**
  35732. * Creates a new torus geometry
  35733. * @param id defines the unique ID of the geometry
  35734. * @param scene defines the hosting scene
  35735. * @param diameter defines the diameter of the torus
  35736. * @param thickness defines the thickness of the torus (ie. internal diameter)
  35737. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  35738. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35739. * @param mesh defines the hosting mesh (can be null)
  35740. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35741. */
  35742. function TorusGeometry(id, scene,
  35743. /**
  35744. * Defines the diameter of the torus
  35745. */
  35746. diameter,
  35747. /**
  35748. * Defines the thickness of the torus (ie. internal diameter)
  35749. */
  35750. thickness,
  35751. /**
  35752. * Defines the tesselation factor to apply to the torus
  35753. */
  35754. tessellation, canBeRegenerated, mesh,
  35755. /**
  35756. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35757. */
  35758. side) {
  35759. if (mesh === void 0) { mesh = null; }
  35760. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35761. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35762. _this.diameter = diameter;
  35763. _this.thickness = thickness;
  35764. _this.tessellation = tessellation;
  35765. _this.side = side;
  35766. return _this;
  35767. }
  35768. TorusGeometry.prototype._regenerateVertexData = function () {
  35769. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35770. };
  35771. TorusGeometry.prototype.copy = function (id) {
  35772. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35773. };
  35774. TorusGeometry.prototype.serialize = function () {
  35775. var serializationObject = _super.prototype.serialize.call(this);
  35776. serializationObject.diameter = this.diameter;
  35777. serializationObject.thickness = this.thickness;
  35778. serializationObject.tessellation = this.tessellation;
  35779. return serializationObject;
  35780. };
  35781. TorusGeometry.Parse = function (parsedTorus, scene) {
  35782. if (scene.getGeometryByID(parsedTorus.id)) {
  35783. return null; // null since geometry could be something else than a torus...
  35784. }
  35785. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35786. if (BABYLON.Tags) {
  35787. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35788. }
  35789. scene.pushGeometry(torus, true);
  35790. return torus;
  35791. };
  35792. return TorusGeometry;
  35793. }(_PrimitiveGeometry));
  35794. BABYLON.TorusGeometry = TorusGeometry;
  35795. /**
  35796. * Creates a new ground geometry
  35797. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  35798. */
  35799. var GroundGeometry = /** @class */ (function (_super) {
  35800. __extends(GroundGeometry, _super);
  35801. /**
  35802. * Creates a new ground geometry
  35803. * @param id defines the unique ID of the geometry
  35804. * @param scene defines the hosting scene
  35805. * @param width defines the width of the ground
  35806. * @param height defines the height of the ground
  35807. * @param subdivisions defines the subdivisions to apply to the ground
  35808. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35809. * @param mesh defines the hosting mesh (can be null)
  35810. */
  35811. function GroundGeometry(id, scene,
  35812. /**
  35813. * Defines the width of the ground
  35814. */
  35815. width,
  35816. /**
  35817. * Defines the height of the ground
  35818. */
  35819. height,
  35820. /**
  35821. * Defines the subdivisions to apply to the ground
  35822. */
  35823. subdivisions, canBeRegenerated, mesh) {
  35824. if (mesh === void 0) { mesh = null; }
  35825. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35826. _this.width = width;
  35827. _this.height = height;
  35828. _this.subdivisions = subdivisions;
  35829. return _this;
  35830. }
  35831. GroundGeometry.prototype._regenerateVertexData = function () {
  35832. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35833. };
  35834. GroundGeometry.prototype.copy = function (id) {
  35835. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35836. };
  35837. GroundGeometry.prototype.serialize = function () {
  35838. var serializationObject = _super.prototype.serialize.call(this);
  35839. serializationObject.width = this.width;
  35840. serializationObject.height = this.height;
  35841. serializationObject.subdivisions = this.subdivisions;
  35842. return serializationObject;
  35843. };
  35844. GroundGeometry.Parse = function (parsedGround, scene) {
  35845. if (scene.getGeometryByID(parsedGround.id)) {
  35846. return null; // null since geometry could be something else than a ground...
  35847. }
  35848. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35849. if (BABYLON.Tags) {
  35850. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35851. }
  35852. scene.pushGeometry(ground, true);
  35853. return ground;
  35854. };
  35855. return GroundGeometry;
  35856. }(_PrimitiveGeometry));
  35857. BABYLON.GroundGeometry = GroundGeometry;
  35858. /**
  35859. * Creates a tiled ground geometry
  35860. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  35861. */
  35862. var TiledGroundGeometry = /** @class */ (function (_super) {
  35863. __extends(TiledGroundGeometry, _super);
  35864. /**
  35865. * Creates a tiled ground geometry
  35866. * @param id defines the unique ID of the geometry
  35867. * @param scene defines the hosting scene
  35868. * @param xmin defines the minimum value on X axis
  35869. * @param zmin defines the minimum value on Z axis
  35870. * @param xmax defines the maximum value on X axis
  35871. * @param zmax defines the maximum value on Z axis
  35872. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  35873. * @param precision defines the precision to use when computing the tiles
  35874. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35875. * @param mesh defines the hosting mesh (can be null)
  35876. */
  35877. function TiledGroundGeometry(id, scene,
  35878. /**
  35879. * Defines the minimum value on X axis
  35880. */
  35881. xmin,
  35882. /**
  35883. * Defines the minimum value on Z axis
  35884. */
  35885. zmin,
  35886. /**
  35887. * Defines the maximum value on X axis
  35888. */
  35889. xmax,
  35890. /**
  35891. * Defines the maximum value on Z axis
  35892. */
  35893. zmax,
  35894. /**
  35895. * Defines the subdivisions to apply to the ground
  35896. */
  35897. subdivisions,
  35898. /**
  35899. * Defines the precision to use when computing the tiles
  35900. */
  35901. precision, canBeRegenerated, mesh) {
  35902. if (mesh === void 0) { mesh = null; }
  35903. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35904. _this.xmin = xmin;
  35905. _this.zmin = zmin;
  35906. _this.xmax = xmax;
  35907. _this.zmax = zmax;
  35908. _this.subdivisions = subdivisions;
  35909. _this.precision = precision;
  35910. return _this;
  35911. }
  35912. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  35913. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35914. };
  35915. TiledGroundGeometry.prototype.copy = function (id) {
  35916. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35917. };
  35918. return TiledGroundGeometry;
  35919. }(_PrimitiveGeometry));
  35920. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  35921. /**
  35922. * Creates a plane geometry
  35923. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  35924. */
  35925. var PlaneGeometry = /** @class */ (function (_super) {
  35926. __extends(PlaneGeometry, _super);
  35927. /**
  35928. * Creates a plane geometry
  35929. * @param id defines the unique ID of the geometry
  35930. * @param scene defines the hosting scene
  35931. * @param size defines the size of the plane (width === height)
  35932. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35933. * @param mesh defines the hosting mesh (can be null)
  35934. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35935. */
  35936. function PlaneGeometry(id, scene,
  35937. /**
  35938. * Defines the size of the plane (width === height)
  35939. */
  35940. size, canBeRegenerated, mesh,
  35941. /**
  35942. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35943. */
  35944. side) {
  35945. if (mesh === void 0) { mesh = null; }
  35946. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35947. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  35948. _this.size = size;
  35949. _this.side = side;
  35950. return _this;
  35951. }
  35952. PlaneGeometry.prototype._regenerateVertexData = function () {
  35953. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  35954. };
  35955. PlaneGeometry.prototype.copy = function (id) {
  35956. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35957. };
  35958. PlaneGeometry.prototype.serialize = function () {
  35959. var serializationObject = _super.prototype.serialize.call(this);
  35960. serializationObject.size = this.size;
  35961. return serializationObject;
  35962. };
  35963. PlaneGeometry.Parse = function (parsedPlane, scene) {
  35964. if (scene.getGeometryByID(parsedPlane.id)) {
  35965. return null; // null since geometry could be something else than a ground...
  35966. }
  35967. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  35968. if (BABYLON.Tags) {
  35969. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  35970. }
  35971. scene.pushGeometry(plane, true);
  35972. return plane;
  35973. };
  35974. return PlaneGeometry;
  35975. }(_PrimitiveGeometry));
  35976. BABYLON.PlaneGeometry = PlaneGeometry;
  35977. /**
  35978. * Creates a torus knot geometry
  35979. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  35980. */
  35981. var TorusKnotGeometry = /** @class */ (function (_super) {
  35982. __extends(TorusKnotGeometry, _super);
  35983. /**
  35984. * Creates a torus knot geometry
  35985. * @param id defines the unique ID of the geometry
  35986. * @param scene defines the hosting scene
  35987. * @param radius defines the radius of the torus knot
  35988. * @param tube defines the thickness of the torus knot tube
  35989. * @param radialSegments defines the number of radial segments
  35990. * @param tubularSegments defines the number of tubular segments
  35991. * @param p defines the first number of windings
  35992. * @param q defines the second number of windings
  35993. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  35994. * @param mesh defines the hosting mesh (can be null)
  35995. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  35996. */
  35997. function TorusKnotGeometry(id, scene,
  35998. /**
  35999. * Defines the radius of the torus knot
  36000. */
  36001. radius,
  36002. /**
  36003. * Defines the thickness of the torus knot tube
  36004. */
  36005. tube,
  36006. /**
  36007. * Defines the number of radial segments
  36008. */
  36009. radialSegments,
  36010. /**
  36011. * Defines the number of tubular segments
  36012. */
  36013. tubularSegments,
  36014. /**
  36015. * Defines the first number of windings
  36016. */
  36017. p,
  36018. /**
  36019. * Defines the second number of windings
  36020. */
  36021. q, canBeRegenerated, mesh,
  36022. /**
  36023. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36024. */
  36025. side) {
  36026. if (mesh === void 0) { mesh = null; }
  36027. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36028. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36029. _this.radius = radius;
  36030. _this.tube = tube;
  36031. _this.radialSegments = radialSegments;
  36032. _this.tubularSegments = tubularSegments;
  36033. _this.p = p;
  36034. _this.q = q;
  36035. _this.side = side;
  36036. return _this;
  36037. }
  36038. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36039. 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 });
  36040. };
  36041. TorusKnotGeometry.prototype.copy = function (id) {
  36042. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  36043. };
  36044. TorusKnotGeometry.prototype.serialize = function () {
  36045. var serializationObject = _super.prototype.serialize.call(this);
  36046. serializationObject.radius = this.radius;
  36047. serializationObject.tube = this.tube;
  36048. serializationObject.radialSegments = this.radialSegments;
  36049. serializationObject.tubularSegments = this.tubularSegments;
  36050. serializationObject.p = this.p;
  36051. serializationObject.q = this.q;
  36052. return serializationObject;
  36053. };
  36054. ;
  36055. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  36056. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  36057. return null; // null since geometry could be something else than a ground...
  36058. }
  36059. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  36060. if (BABYLON.Tags) {
  36061. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  36062. }
  36063. scene.pushGeometry(torusKnot, true);
  36064. return torusKnot;
  36065. };
  36066. return TorusKnotGeometry;
  36067. }(_PrimitiveGeometry));
  36068. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  36069. //}
  36070. })(BABYLON || (BABYLON = {}));
  36071. //# sourceMappingURL=babylon.geometry.js.map
  36072. var BABYLON;
  36073. (function (BABYLON) {
  36074. /**
  36075. * PostProcessManager is used to manage one or more post processes or post process pipelines
  36076. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  36077. */
  36078. var PostProcessManager = /** @class */ (function () {
  36079. /**
  36080. * Creates a new instance of @see PostProcess
  36081. * @param scene The scene that the post process is associated with.
  36082. */
  36083. function PostProcessManager(scene) {
  36084. this._vertexBuffers = {};
  36085. this._scene = scene;
  36086. }
  36087. PostProcessManager.prototype._prepareBuffers = function () {
  36088. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  36089. return;
  36090. }
  36091. // VBO
  36092. var vertices = [];
  36093. vertices.push(1, 1);
  36094. vertices.push(-1, 1);
  36095. vertices.push(-1, -1);
  36096. vertices.push(1, -1);
  36097. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  36098. this._buildIndexBuffer();
  36099. };
  36100. PostProcessManager.prototype._buildIndexBuffer = function () {
  36101. // Indices
  36102. var indices = [];
  36103. indices.push(0);
  36104. indices.push(1);
  36105. indices.push(2);
  36106. indices.push(0);
  36107. indices.push(2);
  36108. indices.push(3);
  36109. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  36110. };
  36111. /**
  36112. * Rebuilds the vertex buffers of the manager.
  36113. */
  36114. PostProcessManager.prototype._rebuild = function () {
  36115. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36116. if (!vb) {
  36117. return;
  36118. }
  36119. vb._rebuild();
  36120. this._buildIndexBuffer();
  36121. };
  36122. // Methods
  36123. /**
  36124. * Prepares a frame to be run through a post process.
  36125. * @param sourceTexture The input texture to the post procesess. (default: null)
  36126. * @param postProcesses An array of post processes to be run. (default: null)
  36127. * @returns True if the post processes were able to be run.
  36128. */
  36129. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  36130. if (sourceTexture === void 0) { sourceTexture = null; }
  36131. if (postProcesses === void 0) { postProcesses = null; }
  36132. var camera = this._scene.activeCamera;
  36133. if (!camera) {
  36134. return false;
  36135. }
  36136. var postProcesses = postProcesses || camera._postProcesses;
  36137. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36138. return false;
  36139. }
  36140. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  36141. return true;
  36142. };
  36143. /**
  36144. * Manually render a set of post processes to a texture.
  36145. * @param postProcesses An array of post processes to be run.
  36146. * @param targetTexture The target texture to render to.
  36147. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  36148. */
  36149. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  36150. if (targetTexture === void 0) { targetTexture = null; }
  36151. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36152. var engine = this._scene.getEngine();
  36153. for (var index = 0; index < postProcesses.length; index++) {
  36154. if (index < postProcesses.length - 1) {
  36155. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  36156. }
  36157. else {
  36158. if (targetTexture) {
  36159. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  36160. }
  36161. else {
  36162. engine.restoreDefaultFramebuffer();
  36163. }
  36164. }
  36165. var pp = postProcesses[index];
  36166. var effect = pp.apply();
  36167. if (effect) {
  36168. pp.onBeforeRenderObservable.notifyObservers(effect);
  36169. // VBOs
  36170. this._prepareBuffers();
  36171. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36172. // Draw order
  36173. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36174. pp.onAfterRenderObservable.notifyObservers(effect);
  36175. }
  36176. }
  36177. // Restore depth buffer
  36178. engine.setDepthBuffer(true);
  36179. engine.setDepthWrite(true);
  36180. };
  36181. /**
  36182. * Finalize the result of the output of the postprocesses.
  36183. * @param doNotPresent If true the result will not be displayed to the screen.
  36184. * @param targetTexture The target texture to render to.
  36185. * @param faceIndex The index of the face to bind the target texture to.
  36186. * @param postProcesses The array of post processes to render.
  36187. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  36188. */
  36189. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  36190. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  36191. var camera = this._scene.activeCamera;
  36192. if (!camera) {
  36193. return;
  36194. }
  36195. postProcesses = postProcesses || camera._postProcesses;
  36196. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  36197. return;
  36198. }
  36199. var engine = this._scene.getEngine();
  36200. for (var index = 0, len = postProcesses.length; index < len; index++) {
  36201. if (index < len - 1) {
  36202. postProcesses[index + 1].activate(camera, targetTexture);
  36203. }
  36204. else {
  36205. if (targetTexture) {
  36206. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  36207. }
  36208. else {
  36209. engine.restoreDefaultFramebuffer();
  36210. }
  36211. }
  36212. if (doNotPresent) {
  36213. break;
  36214. }
  36215. var pp = postProcesses[index];
  36216. var effect = pp.apply();
  36217. if (effect) {
  36218. pp.onBeforeRenderObservable.notifyObservers(effect);
  36219. // VBOs
  36220. this._prepareBuffers();
  36221. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  36222. // Draw order
  36223. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  36224. pp.onAfterRenderObservable.notifyObservers(effect);
  36225. }
  36226. }
  36227. // Restore states
  36228. engine.setDepthBuffer(true);
  36229. engine.setDepthWrite(true);
  36230. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  36231. };
  36232. /**
  36233. * Disposes of the post process manager.
  36234. */
  36235. PostProcessManager.prototype.dispose = function () {
  36236. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36237. if (buffer) {
  36238. buffer.dispose();
  36239. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36240. }
  36241. if (this._indexBuffer) {
  36242. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36243. this._indexBuffer = null;
  36244. }
  36245. };
  36246. return PostProcessManager;
  36247. }());
  36248. BABYLON.PostProcessManager = PostProcessManager;
  36249. })(BABYLON || (BABYLON = {}));
  36250. //# sourceMappingURL=babylon.postProcessManager.js.map
  36251. var BABYLON;
  36252. (function (BABYLON) {
  36253. /**
  36254. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  36255. */
  36256. var PerformanceMonitor = /** @class */ (function () {
  36257. /**
  36258. * constructor
  36259. * @param frameSampleSize The number of samples required to saturate the sliding window
  36260. */
  36261. function PerformanceMonitor(frameSampleSize) {
  36262. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  36263. this._enabled = true;
  36264. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  36265. }
  36266. /**
  36267. * Samples current frame
  36268. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  36269. */
  36270. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  36271. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  36272. if (!this._enabled)
  36273. return;
  36274. if (this._lastFrameTimeMs != null) {
  36275. var dt = timeMs - this._lastFrameTimeMs;
  36276. this._rollingFrameTime.add(dt);
  36277. }
  36278. this._lastFrameTimeMs = timeMs;
  36279. };
  36280. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  36281. /**
  36282. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36283. * @return Average frame time in milliseconds
  36284. */
  36285. get: function () {
  36286. return this._rollingFrameTime.average;
  36287. },
  36288. enumerable: true,
  36289. configurable: true
  36290. });
  36291. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  36292. /**
  36293. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  36294. * @return Frame time variance in milliseconds squared
  36295. */
  36296. get: function () {
  36297. return this._rollingFrameTime.variance;
  36298. },
  36299. enumerable: true,
  36300. configurable: true
  36301. });
  36302. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  36303. /**
  36304. * Returns the frame time of the most recent frame
  36305. * @return Frame time in milliseconds
  36306. */
  36307. get: function () {
  36308. return this._rollingFrameTime.history(0);
  36309. },
  36310. enumerable: true,
  36311. configurable: true
  36312. });
  36313. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  36314. /**
  36315. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  36316. * @return Framerate in frames per second
  36317. */
  36318. get: function () {
  36319. return 1000.0 / this._rollingFrameTime.average;
  36320. },
  36321. enumerable: true,
  36322. configurable: true
  36323. });
  36324. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  36325. /**
  36326. * Returns the average framerate in frames per second using the most recent frame time
  36327. * @return Framerate in frames per second
  36328. */
  36329. get: function () {
  36330. var history = this._rollingFrameTime.history(0);
  36331. if (history === 0) {
  36332. return 0;
  36333. }
  36334. return 1000.0 / history;
  36335. },
  36336. enumerable: true,
  36337. configurable: true
  36338. });
  36339. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  36340. /**
  36341. * Returns true if enough samples have been taken to completely fill the sliding window
  36342. * @return true if saturated
  36343. */
  36344. get: function () {
  36345. return this._rollingFrameTime.isSaturated();
  36346. },
  36347. enumerable: true,
  36348. configurable: true
  36349. });
  36350. /**
  36351. * Enables contributions to the sliding window sample set
  36352. */
  36353. PerformanceMonitor.prototype.enable = function () {
  36354. this._enabled = true;
  36355. };
  36356. /**
  36357. * Disables contributions to the sliding window sample set
  36358. * Samples will not be interpolated over the disabled period
  36359. */
  36360. PerformanceMonitor.prototype.disable = function () {
  36361. this._enabled = false;
  36362. //clear last sample to avoid interpolating over the disabled period when next enabled
  36363. this._lastFrameTimeMs = null;
  36364. };
  36365. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  36366. /**
  36367. * Returns true if sampling is enabled
  36368. * @return true if enabled
  36369. */
  36370. get: function () {
  36371. return this._enabled;
  36372. },
  36373. enumerable: true,
  36374. configurable: true
  36375. });
  36376. /**
  36377. * Resets performance monitor
  36378. */
  36379. PerformanceMonitor.prototype.reset = function () {
  36380. //clear last sample to avoid interpolating over the disabled period when next enabled
  36381. this._lastFrameTimeMs = null;
  36382. //wipe record
  36383. this._rollingFrameTime.reset();
  36384. };
  36385. return PerformanceMonitor;
  36386. }());
  36387. BABYLON.PerformanceMonitor = PerformanceMonitor;
  36388. /**
  36389. * RollingAverage
  36390. *
  36391. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  36392. */
  36393. var RollingAverage = /** @class */ (function () {
  36394. /**
  36395. * constructor
  36396. * @param length The number of samples required to saturate the sliding window
  36397. */
  36398. function RollingAverage(length) {
  36399. this._samples = new Array(length);
  36400. this.reset();
  36401. }
  36402. /**
  36403. * Adds a sample to the sample set
  36404. * @param v The sample value
  36405. */
  36406. RollingAverage.prototype.add = function (v) {
  36407. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  36408. var delta;
  36409. //we need to check if we've already wrapped round
  36410. if (this.isSaturated()) {
  36411. //remove bottom of stack from mean
  36412. var bottomValue = this._samples[this._pos];
  36413. delta = bottomValue - this.average;
  36414. this.average -= delta / (this._sampleCount - 1);
  36415. this._m2 -= delta * (bottomValue - this.average);
  36416. }
  36417. else {
  36418. this._sampleCount++;
  36419. }
  36420. //add new value to mean
  36421. delta = v - this.average;
  36422. this.average += delta / (this._sampleCount);
  36423. this._m2 += delta * (v - this.average);
  36424. //set the new variance
  36425. this.variance = this._m2 / (this._sampleCount - 1);
  36426. this._samples[this._pos] = v;
  36427. this._pos++;
  36428. this._pos %= this._samples.length; //positive wrap around
  36429. };
  36430. /**
  36431. * Returns previously added values or null if outside of history or outside the sliding window domain
  36432. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  36433. * @return Value previously recorded with add() or null if outside of range
  36434. */
  36435. RollingAverage.prototype.history = function (i) {
  36436. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  36437. return 0;
  36438. }
  36439. var i0 = this._wrapPosition(this._pos - 1.0);
  36440. return this._samples[this._wrapPosition(i0 - i)];
  36441. };
  36442. /**
  36443. * Returns true if enough samples have been taken to completely fill the sliding window
  36444. * @return true if sample-set saturated
  36445. */
  36446. RollingAverage.prototype.isSaturated = function () {
  36447. return this._sampleCount >= this._samples.length;
  36448. };
  36449. /**
  36450. * Resets the rolling average (equivalent to 0 samples taken so far)
  36451. */
  36452. RollingAverage.prototype.reset = function () {
  36453. this.average = 0;
  36454. this.variance = 0;
  36455. this._sampleCount = 0;
  36456. this._pos = 0;
  36457. this._m2 = 0;
  36458. };
  36459. /**
  36460. * Wraps a value around the sample range boundaries
  36461. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  36462. * @return Wrapped position in sample range
  36463. */
  36464. RollingAverage.prototype._wrapPosition = function (i) {
  36465. var max = this._samples.length;
  36466. return ((i % max) + max) % max;
  36467. };
  36468. return RollingAverage;
  36469. }());
  36470. BABYLON.RollingAverage = RollingAverage;
  36471. })(BABYLON || (BABYLON = {}));
  36472. //# sourceMappingURL=babylon.performanceMonitor.js.map
  36473. var BABYLON;
  36474. (function (BABYLON) {
  36475. /**
  36476. * This groups together the common properties used for image processing either in direct forward pass
  36477. * or through post processing effect depending on the use of the image processing pipeline in your scene
  36478. * or not.
  36479. */
  36480. var ImageProcessingConfiguration = /** @class */ (function () {
  36481. function ImageProcessingConfiguration() {
  36482. /**
  36483. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  36484. */
  36485. this.colorCurves = new BABYLON.ColorCurves();
  36486. this._colorCurvesEnabled = false;
  36487. this._colorGradingEnabled = false;
  36488. this._colorGradingWithGreenDepth = true;
  36489. this._colorGradingBGR = true;
  36490. this._exposure = 1.0;
  36491. this._toneMappingEnabled = false;
  36492. this._contrast = 1.0;
  36493. /**
  36494. * Vignette stretch size.
  36495. */
  36496. this.vignetteStretch = 0;
  36497. /**
  36498. * Vignette centre X Offset.
  36499. */
  36500. this.vignetteCentreX = 0;
  36501. /**
  36502. * Vignette centre Y Offset.
  36503. */
  36504. this.vignetteCentreY = 0;
  36505. /**
  36506. * Vignette weight or intensity of the vignette effect.
  36507. */
  36508. this.vignetteWeight = 1.5;
  36509. /**
  36510. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  36511. * if vignetteEnabled is set to true.
  36512. */
  36513. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  36514. /**
  36515. * Camera field of view used by the Vignette effect.
  36516. */
  36517. this.vignetteCameraFov = 0.5;
  36518. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  36519. this._vignetteEnabled = false;
  36520. this._applyByPostProcess = false;
  36521. this._isEnabled = true;
  36522. /**
  36523. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  36524. * @type {BABYLON.Observable}
  36525. */
  36526. this.onUpdateParameters = new BABYLON.Observable();
  36527. }
  36528. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  36529. /**
  36530. * Gets wether the color curves effect is enabled.
  36531. */
  36532. get: function () {
  36533. return this._colorCurvesEnabled;
  36534. },
  36535. /**
  36536. * Sets wether the color curves effect is enabled.
  36537. */
  36538. set: function (value) {
  36539. if (this._colorCurvesEnabled === value) {
  36540. return;
  36541. }
  36542. this._colorCurvesEnabled = value;
  36543. this._updateParameters();
  36544. },
  36545. enumerable: true,
  36546. configurable: true
  36547. });
  36548. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  36549. /**
  36550. * Gets wether the color grading effect is enabled.
  36551. */
  36552. get: function () {
  36553. return this._colorGradingEnabled;
  36554. },
  36555. /**
  36556. * Sets wether the color grading effect is enabled.
  36557. */
  36558. set: function (value) {
  36559. if (this._colorGradingEnabled === value) {
  36560. return;
  36561. }
  36562. this._colorGradingEnabled = value;
  36563. this._updateParameters();
  36564. },
  36565. enumerable: true,
  36566. configurable: true
  36567. });
  36568. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  36569. /**
  36570. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  36571. */
  36572. get: function () {
  36573. return this._colorGradingWithGreenDepth;
  36574. },
  36575. /**
  36576. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  36577. */
  36578. set: function (value) {
  36579. if (this._colorGradingWithGreenDepth === value) {
  36580. return;
  36581. }
  36582. this._colorGradingWithGreenDepth = value;
  36583. this._updateParameters();
  36584. },
  36585. enumerable: true,
  36586. configurable: true
  36587. });
  36588. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  36589. /**
  36590. * Gets wether the color grading texture contains BGR values.
  36591. */
  36592. get: function () {
  36593. return this._colorGradingBGR;
  36594. },
  36595. /**
  36596. * Sets wether the color grading texture contains BGR values.
  36597. */
  36598. set: function (value) {
  36599. if (this._colorGradingBGR === value) {
  36600. return;
  36601. }
  36602. this._colorGradingBGR = value;
  36603. this._updateParameters();
  36604. },
  36605. enumerable: true,
  36606. configurable: true
  36607. });
  36608. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  36609. /**
  36610. * Gets the Exposure used in the effect.
  36611. */
  36612. get: function () {
  36613. return this._exposure;
  36614. },
  36615. /**
  36616. * Sets the Exposure used in the effect.
  36617. */
  36618. set: function (value) {
  36619. if (this._exposure === value) {
  36620. return;
  36621. }
  36622. this._exposure = value;
  36623. this._updateParameters();
  36624. },
  36625. enumerable: true,
  36626. configurable: true
  36627. });
  36628. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  36629. /**
  36630. * Gets wether the tone mapping effect is enabled.
  36631. */
  36632. get: function () {
  36633. return this._toneMappingEnabled;
  36634. },
  36635. /**
  36636. * Sets wether the tone mapping effect is enabled.
  36637. */
  36638. set: function (value) {
  36639. if (this._toneMappingEnabled === value) {
  36640. return;
  36641. }
  36642. this._toneMappingEnabled = value;
  36643. this._updateParameters();
  36644. },
  36645. enumerable: true,
  36646. configurable: true
  36647. });
  36648. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  36649. /**
  36650. * Gets the contrast used in the effect.
  36651. */
  36652. get: function () {
  36653. return this._contrast;
  36654. },
  36655. /**
  36656. * Sets the contrast used in the effect.
  36657. */
  36658. set: function (value) {
  36659. if (this._contrast === value) {
  36660. return;
  36661. }
  36662. this._contrast = value;
  36663. this._updateParameters();
  36664. },
  36665. enumerable: true,
  36666. configurable: true
  36667. });
  36668. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  36669. /**
  36670. * Gets the vignette blend mode allowing different kind of effect.
  36671. */
  36672. get: function () {
  36673. return this._vignetteBlendMode;
  36674. },
  36675. /**
  36676. * Sets the vignette blend mode allowing different kind of effect.
  36677. */
  36678. set: function (value) {
  36679. if (this._vignetteBlendMode === value) {
  36680. return;
  36681. }
  36682. this._vignetteBlendMode = value;
  36683. this._updateParameters();
  36684. },
  36685. enumerable: true,
  36686. configurable: true
  36687. });
  36688. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  36689. /**
  36690. * Gets wether the vignette effect is enabled.
  36691. */
  36692. get: function () {
  36693. return this._vignetteEnabled;
  36694. },
  36695. /**
  36696. * Sets wether the vignette effect is enabled.
  36697. */
  36698. set: function (value) {
  36699. if (this._vignetteEnabled === value) {
  36700. return;
  36701. }
  36702. this._vignetteEnabled = value;
  36703. this._updateParameters();
  36704. },
  36705. enumerable: true,
  36706. configurable: true
  36707. });
  36708. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  36709. /**
  36710. * Gets wether the image processing is applied through a post process or not.
  36711. */
  36712. get: function () {
  36713. return this._applyByPostProcess;
  36714. },
  36715. /**
  36716. * Sets wether the image processing is applied through a post process or not.
  36717. */
  36718. set: function (value) {
  36719. if (this._applyByPostProcess === value) {
  36720. return;
  36721. }
  36722. this._applyByPostProcess = value;
  36723. this._updateParameters();
  36724. },
  36725. enumerable: true,
  36726. configurable: true
  36727. });
  36728. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  36729. /**
  36730. * Gets wether the image processing is enabled or not.
  36731. */
  36732. get: function () {
  36733. return this._isEnabled;
  36734. },
  36735. /**
  36736. * Sets wether the image processing is enabled or not.
  36737. */
  36738. set: function (value) {
  36739. if (this._isEnabled === value) {
  36740. return;
  36741. }
  36742. this._isEnabled = value;
  36743. this._updateParameters();
  36744. },
  36745. enumerable: true,
  36746. configurable: true
  36747. });
  36748. /**
  36749. * Method called each time the image processing information changes requires to recompile the effect.
  36750. */
  36751. ImageProcessingConfiguration.prototype._updateParameters = function () {
  36752. this.onUpdateParameters.notifyObservers(this);
  36753. };
  36754. ImageProcessingConfiguration.prototype.getClassName = function () {
  36755. return "ImageProcessingConfiguration";
  36756. };
  36757. /**
  36758. * Prepare the list of uniforms associated with the Image Processing effects.
  36759. * @param uniformsList The list of uniforms used in the effect
  36760. * @param defines the list of defines currently in use
  36761. */
  36762. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  36763. if (defines.EXPOSURE) {
  36764. uniforms.push("exposureLinear");
  36765. }
  36766. if (defines.CONTRAST) {
  36767. uniforms.push("contrast");
  36768. }
  36769. if (defines.COLORGRADING) {
  36770. uniforms.push("colorTransformSettings");
  36771. }
  36772. if (defines.VIGNETTE) {
  36773. uniforms.push("vInverseScreenSize");
  36774. uniforms.push("vignetteSettings1");
  36775. uniforms.push("vignetteSettings2");
  36776. }
  36777. if (defines.COLORCURVES) {
  36778. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  36779. }
  36780. };
  36781. /**
  36782. * Prepare the list of samplers associated with the Image Processing effects.
  36783. * @param uniformsList The list of uniforms used in the effect
  36784. * @param defines the list of defines currently in use
  36785. */
  36786. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  36787. if (defines.COLORGRADING) {
  36788. samplersList.push("txColorTransform");
  36789. }
  36790. };
  36791. /**
  36792. * Prepare the list of defines associated to the shader.
  36793. * @param defines the list of defines to complete
  36794. */
  36795. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  36796. if (forPostProcess === void 0) { forPostProcess = false; }
  36797. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  36798. defines.VIGNETTE = false;
  36799. defines.TONEMAPPING = false;
  36800. defines.CONTRAST = false;
  36801. defines.EXPOSURE = false;
  36802. defines.COLORCURVES = false;
  36803. defines.COLORGRADING = false;
  36804. defines.COLORGRADING3D = false;
  36805. defines.IMAGEPROCESSING = false;
  36806. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  36807. return;
  36808. }
  36809. defines.VIGNETTE = this.vignetteEnabled;
  36810. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  36811. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  36812. defines.TONEMAPPING = this.toneMappingEnabled;
  36813. defines.CONTRAST = (this.contrast !== 1.0);
  36814. defines.EXPOSURE = (this.exposure !== 1.0);
  36815. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  36816. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  36817. if (defines.COLORGRADING) {
  36818. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  36819. }
  36820. else {
  36821. defines.COLORGRADING3D = false;
  36822. }
  36823. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  36824. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  36825. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  36826. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  36827. };
  36828. /**
  36829. * Returns true if all the image processing information are ready.
  36830. */
  36831. ImageProcessingConfiguration.prototype.isReady = function () {
  36832. // Color Grading texure can not be none blocking.
  36833. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  36834. };
  36835. /**
  36836. * Binds the image processing to the shader.
  36837. * @param effect The effect to bind to
  36838. */
  36839. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  36840. if (aspectRatio === void 0) { aspectRatio = 1; }
  36841. // Color Curves
  36842. if (this._colorCurvesEnabled && this.colorCurves) {
  36843. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  36844. }
  36845. // Vignette
  36846. if (this._vignetteEnabled) {
  36847. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  36848. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  36849. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  36850. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  36851. var vignetteScaleX = vignetteScaleY * aspectRatio;
  36852. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  36853. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  36854. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  36855. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  36856. var vignettePower = -2.0 * this.vignetteWeight;
  36857. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  36858. }
  36859. // Exposure
  36860. effect.setFloat("exposureLinear", this.exposure);
  36861. // Contrast
  36862. effect.setFloat("contrast", this.contrast);
  36863. // Color transform settings
  36864. if (this.colorGradingTexture) {
  36865. effect.setTexture("txColorTransform", this.colorGradingTexture);
  36866. var textureSize = this.colorGradingTexture.getSize().height;
  36867. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  36868. 0.5 / textureSize, // textureOffset
  36869. textureSize, // textureSize
  36870. this.colorGradingTexture.level // weight
  36871. );
  36872. }
  36873. };
  36874. /**
  36875. * Clones the current image processing instance.
  36876. * @return The cloned image processing
  36877. */
  36878. ImageProcessingConfiguration.prototype.clone = function () {
  36879. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  36880. };
  36881. /**
  36882. * Serializes the current image processing instance to a json representation.
  36883. * @return a JSON representation
  36884. */
  36885. ImageProcessingConfiguration.prototype.serialize = function () {
  36886. return BABYLON.SerializationHelper.Serialize(this);
  36887. };
  36888. /**
  36889. * Parses the image processing from a json representation.
  36890. * @param source the JSON source to parse
  36891. * @return The parsed image processing
  36892. */
  36893. ImageProcessingConfiguration.Parse = function (source) {
  36894. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  36895. };
  36896. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  36897. /**
  36898. * Used to apply the vignette as a mix with the pixel color.
  36899. */
  36900. get: function () {
  36901. return this._VIGNETTEMODE_MULTIPLY;
  36902. },
  36903. enumerable: true,
  36904. configurable: true
  36905. });
  36906. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  36907. /**
  36908. * Used to apply the vignette as a replacement of the pixel color.
  36909. */
  36910. get: function () {
  36911. return this._VIGNETTEMODE_OPAQUE;
  36912. },
  36913. enumerable: true,
  36914. configurable: true
  36915. });
  36916. // Static constants associated to the image processing.
  36917. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  36918. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  36919. __decorate([
  36920. BABYLON.serializeAsColorCurves()
  36921. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  36922. __decorate([
  36923. BABYLON.serialize()
  36924. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  36925. __decorate([
  36926. BABYLON.serializeAsTexture()
  36927. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  36928. __decorate([
  36929. BABYLON.serialize()
  36930. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  36931. __decorate([
  36932. BABYLON.serialize()
  36933. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  36934. __decorate([
  36935. BABYLON.serialize()
  36936. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  36937. __decorate([
  36938. BABYLON.serialize()
  36939. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  36940. __decorate([
  36941. BABYLON.serialize()
  36942. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  36943. __decorate([
  36944. BABYLON.serialize()
  36945. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  36946. __decorate([
  36947. BABYLON.serialize()
  36948. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  36949. __decorate([
  36950. BABYLON.serialize()
  36951. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  36952. __decorate([
  36953. BABYLON.serialize()
  36954. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  36955. __decorate([
  36956. BABYLON.serialize()
  36957. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  36958. __decorate([
  36959. BABYLON.serializeAsColor4()
  36960. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  36961. __decorate([
  36962. BABYLON.serialize()
  36963. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  36964. __decorate([
  36965. BABYLON.serialize()
  36966. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  36967. __decorate([
  36968. BABYLON.serialize()
  36969. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  36970. __decorate([
  36971. BABYLON.serialize()
  36972. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  36973. __decorate([
  36974. BABYLON.serialize()
  36975. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  36976. return ImageProcessingConfiguration;
  36977. }());
  36978. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  36979. })(BABYLON || (BABYLON = {}));
  36980. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  36981. var BABYLON;
  36982. (function (BABYLON) {
  36983. /**
  36984. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  36985. * It can help converting any input color in a desired output one. This can then be used to create effects
  36986. * from sepia, black and white to sixties or futuristic rendering...
  36987. *
  36988. * The only supported format is currently 3dl.
  36989. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  36990. */
  36991. var ColorGradingTexture = /** @class */ (function (_super) {
  36992. __extends(ColorGradingTexture, _super);
  36993. /**
  36994. * Instantiates a ColorGradingTexture from the following parameters.
  36995. *
  36996. * @param url The location of the color gradind data (currently only supporting 3dl)
  36997. * @param scene The scene the texture will be used in
  36998. */
  36999. function ColorGradingTexture(url, scene) {
  37000. var _this = _super.call(this, scene) || this;
  37001. if (!url) {
  37002. return _this;
  37003. }
  37004. _this._engine = scene.getEngine();
  37005. _this._textureMatrix = BABYLON.Matrix.Identity();
  37006. _this.name = url;
  37007. _this.url = url;
  37008. _this.hasAlpha = false;
  37009. _this.isCube = false;
  37010. _this.is3D = _this._engine.webGLVersion > 1;
  37011. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37012. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37013. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37014. _this.anisotropicFilteringLevel = 1;
  37015. _this._texture = _this._getFromCache(url, true);
  37016. if (!_this._texture) {
  37017. if (!scene.useDelayedTextureLoading) {
  37018. _this.loadTexture();
  37019. }
  37020. else {
  37021. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37022. }
  37023. }
  37024. return _this;
  37025. }
  37026. /**
  37027. * Returns the texture matrix used in most of the material.
  37028. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  37029. */
  37030. ColorGradingTexture.prototype.getTextureMatrix = function () {
  37031. return this._textureMatrix;
  37032. };
  37033. /**
  37034. * Occurs when the file being loaded is a .3dl LUT file.
  37035. */
  37036. ColorGradingTexture.prototype.load3dlTexture = function () {
  37037. var engine = this._engine;
  37038. var texture;
  37039. if (engine.webGLVersion === 1) {
  37040. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37041. }
  37042. else {
  37043. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37044. }
  37045. this._texture = texture;
  37046. var callback = function (text) {
  37047. if (typeof text !== "string") {
  37048. return;
  37049. }
  37050. var data = null;
  37051. var tempData = null;
  37052. var line;
  37053. var lines = text.split('\n');
  37054. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  37055. var maxColor = 0;
  37056. for (var i = 0; i < lines.length; i++) {
  37057. line = lines[i];
  37058. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  37059. continue;
  37060. if (line.indexOf('#') === 0)
  37061. continue;
  37062. var words = line.split(" ");
  37063. if (size === 0) {
  37064. // Number of space + one
  37065. size = words.length;
  37066. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  37067. tempData = new Float32Array(size * size * size * 4);
  37068. continue;
  37069. }
  37070. if (size != 0) {
  37071. var r = Math.max(parseInt(words[0]), 0);
  37072. var g = Math.max(parseInt(words[1]), 0);
  37073. var b = Math.max(parseInt(words[2]), 0);
  37074. maxColor = Math.max(r, maxColor);
  37075. maxColor = Math.max(g, maxColor);
  37076. maxColor = Math.max(b, maxColor);
  37077. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  37078. if (tempData) {
  37079. tempData[pixelStorageIndex + 0] = r;
  37080. tempData[pixelStorageIndex + 1] = g;
  37081. tempData[pixelStorageIndex + 2] = b;
  37082. }
  37083. pixelIndexSlice++;
  37084. if (pixelIndexSlice % size == 0) {
  37085. pixelIndexH++;
  37086. pixelIndexSlice = 0;
  37087. if (pixelIndexH % size == 0) {
  37088. pixelIndexW++;
  37089. pixelIndexH = 0;
  37090. }
  37091. }
  37092. }
  37093. }
  37094. if (tempData && data) {
  37095. for (var i = 0; i < tempData.length; i++) {
  37096. if (i > 0 && (i + 1) % 4 === 0) {
  37097. data[i] = 255;
  37098. }
  37099. else {
  37100. var value = tempData[i];
  37101. data[i] = (value / maxColor * 255);
  37102. }
  37103. }
  37104. }
  37105. if (texture.is3D) {
  37106. texture.updateSize(size, size, size);
  37107. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37108. }
  37109. else {
  37110. texture.updateSize(size * size, size);
  37111. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  37112. }
  37113. };
  37114. var scene = this.getScene();
  37115. if (scene) {
  37116. scene._loadFile(this.url, callback);
  37117. }
  37118. else {
  37119. this._engine._loadFile(this.url, callback);
  37120. }
  37121. return this._texture;
  37122. };
  37123. /**
  37124. * Starts the loading process of the texture.
  37125. */
  37126. ColorGradingTexture.prototype.loadTexture = function () {
  37127. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  37128. this.load3dlTexture();
  37129. }
  37130. };
  37131. /**
  37132. * Clones the color gradind texture.
  37133. */
  37134. ColorGradingTexture.prototype.clone = function () {
  37135. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  37136. // Base texture
  37137. newTexture.level = this.level;
  37138. return newTexture;
  37139. };
  37140. /**
  37141. * Called during delayed load for textures.
  37142. */
  37143. ColorGradingTexture.prototype.delayLoad = function () {
  37144. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  37145. return;
  37146. }
  37147. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37148. this._texture = this._getFromCache(this.url, true);
  37149. if (!this._texture) {
  37150. this.loadTexture();
  37151. }
  37152. };
  37153. /**
  37154. * Parses a color grading texture serialized by Babylon.
  37155. * @param parsedTexture The texture information being parsedTexture
  37156. * @param scene The scene to load the texture in
  37157. * @param rootUrl The root url of the data assets to load
  37158. * @return A color gradind texture
  37159. */
  37160. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  37161. var texture = null;
  37162. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  37163. texture = new ColorGradingTexture(parsedTexture.name, scene);
  37164. texture.name = parsedTexture.name;
  37165. texture.level = parsedTexture.level;
  37166. }
  37167. return texture;
  37168. };
  37169. /**
  37170. * Serializes the LUT texture to json format.
  37171. */
  37172. ColorGradingTexture.prototype.serialize = function () {
  37173. if (!this.name) {
  37174. return null;
  37175. }
  37176. var serializationObject = {};
  37177. serializationObject.name = this.name;
  37178. serializationObject.level = this.level;
  37179. serializationObject.customType = "BABYLON.ColorGradingTexture";
  37180. return serializationObject;
  37181. };
  37182. /**
  37183. * Empty line regex stored for GC.
  37184. */
  37185. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  37186. return ColorGradingTexture;
  37187. }(BABYLON.BaseTexture));
  37188. BABYLON.ColorGradingTexture = ColorGradingTexture;
  37189. })(BABYLON || (BABYLON = {}));
  37190. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  37191. var BABYLON;
  37192. (function (BABYLON) {
  37193. /**
  37194. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  37195. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  37196. * 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;
  37197. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  37198. */
  37199. var ColorCurves = /** @class */ (function () {
  37200. function ColorCurves() {
  37201. this._dirty = true;
  37202. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  37203. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  37204. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37205. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  37206. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  37207. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  37208. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  37209. this._globalHue = 30;
  37210. this._globalDensity = 0;
  37211. this._globalSaturation = 0;
  37212. this._globalExposure = 0;
  37213. this._highlightsHue = 30;
  37214. this._highlightsDensity = 0;
  37215. this._highlightsSaturation = 0;
  37216. this._highlightsExposure = 0;
  37217. this._midtonesHue = 30;
  37218. this._midtonesDensity = 0;
  37219. this._midtonesSaturation = 0;
  37220. this._midtonesExposure = 0;
  37221. this._shadowsHue = 30;
  37222. this._shadowsDensity = 0;
  37223. this._shadowsSaturation = 0;
  37224. this._shadowsExposure = 0;
  37225. }
  37226. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  37227. /**
  37228. * Gets the global Hue value.
  37229. * 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).
  37230. */
  37231. get: function () {
  37232. return this._globalHue;
  37233. },
  37234. /**
  37235. * Sets the global Hue value.
  37236. * 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).
  37237. */
  37238. set: function (value) {
  37239. this._globalHue = value;
  37240. this._dirty = true;
  37241. },
  37242. enumerable: true,
  37243. configurable: true
  37244. });
  37245. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  37246. /**
  37247. * Gets the global Density value.
  37248. * 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.
  37249. * Values less than zero provide a filter of opposite hue.
  37250. */
  37251. get: function () {
  37252. return this._globalDensity;
  37253. },
  37254. /**
  37255. * Sets the global Density value.
  37256. * 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.
  37257. * Values less than zero provide a filter of opposite hue.
  37258. */
  37259. set: function (value) {
  37260. this._globalDensity = value;
  37261. this._dirty = true;
  37262. },
  37263. enumerable: true,
  37264. configurable: true
  37265. });
  37266. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  37267. /**
  37268. * Gets the global Saturation value.
  37269. * 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.
  37270. */
  37271. get: function () {
  37272. return this._globalSaturation;
  37273. },
  37274. /**
  37275. * Sets the global Saturation value.
  37276. * 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.
  37277. */
  37278. set: function (value) {
  37279. this._globalSaturation = value;
  37280. this._dirty = true;
  37281. },
  37282. enumerable: true,
  37283. configurable: true
  37284. });
  37285. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  37286. /**
  37287. * Gets the highlights Hue value.
  37288. * 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).
  37289. */
  37290. get: function () {
  37291. return this._highlightsHue;
  37292. },
  37293. /**
  37294. * Sets the highlights Hue value.
  37295. * 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).
  37296. */
  37297. set: function (value) {
  37298. this._highlightsHue = value;
  37299. this._dirty = true;
  37300. },
  37301. enumerable: true,
  37302. configurable: true
  37303. });
  37304. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  37305. /**
  37306. * Gets the highlights Density value.
  37307. * 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.
  37308. * Values less than zero provide a filter of opposite hue.
  37309. */
  37310. get: function () {
  37311. return this._highlightsDensity;
  37312. },
  37313. /**
  37314. * Sets the highlights Density value.
  37315. * 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.
  37316. * Values less than zero provide a filter of opposite hue.
  37317. */
  37318. set: function (value) {
  37319. this._highlightsDensity = value;
  37320. this._dirty = true;
  37321. },
  37322. enumerable: true,
  37323. configurable: true
  37324. });
  37325. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  37326. /**
  37327. * Gets the highlights Saturation value.
  37328. * 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.
  37329. */
  37330. get: function () {
  37331. return this._highlightsSaturation;
  37332. },
  37333. /**
  37334. * Sets the highlights Saturation value.
  37335. * 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.
  37336. */
  37337. set: function (value) {
  37338. this._highlightsSaturation = value;
  37339. this._dirty = true;
  37340. },
  37341. enumerable: true,
  37342. configurable: true
  37343. });
  37344. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  37345. /**
  37346. * Gets the highlights Exposure value.
  37347. * 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.
  37348. */
  37349. get: function () {
  37350. return this._highlightsExposure;
  37351. },
  37352. /**
  37353. * Sets the highlights Exposure value.
  37354. * 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.
  37355. */
  37356. set: function (value) {
  37357. this._highlightsExposure = value;
  37358. this._dirty = true;
  37359. },
  37360. enumerable: true,
  37361. configurable: true
  37362. });
  37363. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  37364. /**
  37365. * Gets the midtones Hue value.
  37366. * 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).
  37367. */
  37368. get: function () {
  37369. return this._midtonesHue;
  37370. },
  37371. /**
  37372. * Sets the midtones Hue value.
  37373. * 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).
  37374. */
  37375. set: function (value) {
  37376. this._midtonesHue = value;
  37377. this._dirty = true;
  37378. },
  37379. enumerable: true,
  37380. configurable: true
  37381. });
  37382. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  37383. /**
  37384. * Gets the midtones Density value.
  37385. * 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.
  37386. * Values less than zero provide a filter of opposite hue.
  37387. */
  37388. get: function () {
  37389. return this._midtonesDensity;
  37390. },
  37391. /**
  37392. * Sets the midtones Density value.
  37393. * 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.
  37394. * Values less than zero provide a filter of opposite hue.
  37395. */
  37396. set: function (value) {
  37397. this._midtonesDensity = value;
  37398. this._dirty = true;
  37399. },
  37400. enumerable: true,
  37401. configurable: true
  37402. });
  37403. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  37404. /**
  37405. * Gets the midtones Saturation value.
  37406. * 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.
  37407. */
  37408. get: function () {
  37409. return this._midtonesSaturation;
  37410. },
  37411. /**
  37412. * Sets the midtones Saturation value.
  37413. * 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.
  37414. */
  37415. set: function (value) {
  37416. this._midtonesSaturation = value;
  37417. this._dirty = true;
  37418. },
  37419. enumerable: true,
  37420. configurable: true
  37421. });
  37422. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  37423. /**
  37424. * Gets the midtones Exposure value.
  37425. * 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.
  37426. */
  37427. get: function () {
  37428. return this._midtonesExposure;
  37429. },
  37430. /**
  37431. * Sets the midtones Exposure value.
  37432. * 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.
  37433. */
  37434. set: function (value) {
  37435. this._midtonesExposure = value;
  37436. this._dirty = true;
  37437. },
  37438. enumerable: true,
  37439. configurable: true
  37440. });
  37441. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  37442. /**
  37443. * Gets the shadows Hue value.
  37444. * 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).
  37445. */
  37446. get: function () {
  37447. return this._shadowsHue;
  37448. },
  37449. /**
  37450. * Sets the shadows Hue value.
  37451. * 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).
  37452. */
  37453. set: function (value) {
  37454. this._shadowsHue = value;
  37455. this._dirty = true;
  37456. },
  37457. enumerable: true,
  37458. configurable: true
  37459. });
  37460. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  37461. /**
  37462. * Gets the shadows Density value.
  37463. * 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.
  37464. * Values less than zero provide a filter of opposite hue.
  37465. */
  37466. get: function () {
  37467. return this._shadowsDensity;
  37468. },
  37469. /**
  37470. * Sets the shadows Density value.
  37471. * 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.
  37472. * Values less than zero provide a filter of opposite hue.
  37473. */
  37474. set: function (value) {
  37475. this._shadowsDensity = value;
  37476. this._dirty = true;
  37477. },
  37478. enumerable: true,
  37479. configurable: true
  37480. });
  37481. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  37482. /**
  37483. * Gets the shadows Saturation value.
  37484. * 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.
  37485. */
  37486. get: function () {
  37487. return this._shadowsSaturation;
  37488. },
  37489. /**
  37490. * Sets the shadows Saturation value.
  37491. * 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.
  37492. */
  37493. set: function (value) {
  37494. this._shadowsSaturation = value;
  37495. this._dirty = true;
  37496. },
  37497. enumerable: true,
  37498. configurable: true
  37499. });
  37500. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  37501. /**
  37502. * Gets the shadows Exposure value.
  37503. * 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.
  37504. */
  37505. get: function () {
  37506. return this._shadowsExposure;
  37507. },
  37508. /**
  37509. * Sets the shadows Exposure value.
  37510. * 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.
  37511. */
  37512. set: function (value) {
  37513. this._shadowsExposure = value;
  37514. this._dirty = true;
  37515. },
  37516. enumerable: true,
  37517. configurable: true
  37518. });
  37519. ColorCurves.prototype.getClassName = function () {
  37520. return "ColorCurves";
  37521. };
  37522. /**
  37523. * Binds the color curves to the shader.
  37524. * @param colorCurves The color curve to bind
  37525. * @param effect The effect to bind to
  37526. */
  37527. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  37528. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  37529. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  37530. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  37531. if (colorCurves._dirty) {
  37532. colorCurves._dirty = false;
  37533. // Fill in global info.
  37534. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  37535. // Compute highlights info.
  37536. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  37537. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  37538. // Compute midtones info.
  37539. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  37540. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  37541. // Compute shadows info.
  37542. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  37543. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  37544. // Compute deltas (neutral is midtones).
  37545. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  37546. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  37547. }
  37548. if (effect) {
  37549. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  37550. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  37551. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  37552. }
  37553. };
  37554. /**
  37555. * Prepare the list of uniforms associated with the ColorCurves effects.
  37556. * @param uniformsList The list of uniforms used in the effect
  37557. */
  37558. ColorCurves.PrepareUniforms = function (uniformsList) {
  37559. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  37560. };
  37561. /**
  37562. * Returns color grading data based on a hue, density, saturation and exposure value.
  37563. * @param filterHue The hue of the color filter.
  37564. * @param filterDensity The density of the color filter.
  37565. * @param saturation The saturation.
  37566. * @param exposure The exposure.
  37567. * @param result The result data container.
  37568. */
  37569. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  37570. if (hue == null) {
  37571. return;
  37572. }
  37573. hue = ColorCurves.clamp(hue, 0, 360);
  37574. density = ColorCurves.clamp(density, -100, 100);
  37575. saturation = ColorCurves.clamp(saturation, -100, 100);
  37576. exposure = ColorCurves.clamp(exposure, -100, 100);
  37577. // Remap the slider/config filter density with non-linear mapping and also scale by half
  37578. // so that the maximum filter density is only 50% control. This provides fine control
  37579. // for small values and reasonable range.
  37580. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  37581. density *= 0.5;
  37582. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  37583. if (density < 0) {
  37584. density *= -1;
  37585. hue = (hue + 180) % 360;
  37586. }
  37587. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  37588. result.scaleToRef(2, result);
  37589. result.a = 1 + 0.01 * saturation;
  37590. };
  37591. /**
  37592. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  37593. * @param value The input slider value in range [-100,100].
  37594. * @returns Adjusted value.
  37595. */
  37596. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  37597. value /= 100;
  37598. var x = Math.abs(value);
  37599. x = Math.pow(x, 2);
  37600. if (value < 0) {
  37601. x *= -1;
  37602. }
  37603. x *= 100;
  37604. return x;
  37605. };
  37606. /**
  37607. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  37608. * @param hue The hue (H) input.
  37609. * @param saturation The saturation (S) input.
  37610. * @param brightness The brightness (B) input.
  37611. * @result An RGBA color represented as Vector4.
  37612. */
  37613. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  37614. var h = ColorCurves.clamp(hue, 0, 360);
  37615. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  37616. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  37617. if (s === 0) {
  37618. result.r = v;
  37619. result.g = v;
  37620. result.b = v;
  37621. }
  37622. else {
  37623. // sector 0 to 5
  37624. h /= 60;
  37625. var i = Math.floor(h);
  37626. // fractional part of h
  37627. var f = h - i;
  37628. var p = v * (1 - s);
  37629. var q = v * (1 - s * f);
  37630. var t = v * (1 - s * (1 - f));
  37631. switch (i) {
  37632. case 0:
  37633. result.r = v;
  37634. result.g = t;
  37635. result.b = p;
  37636. break;
  37637. case 1:
  37638. result.r = q;
  37639. result.g = v;
  37640. result.b = p;
  37641. break;
  37642. case 2:
  37643. result.r = p;
  37644. result.g = v;
  37645. result.b = t;
  37646. break;
  37647. case 3:
  37648. result.r = p;
  37649. result.g = q;
  37650. result.b = v;
  37651. break;
  37652. case 4:
  37653. result.r = t;
  37654. result.g = p;
  37655. result.b = v;
  37656. break;
  37657. default:// case 5:
  37658. result.r = v;
  37659. result.g = p;
  37660. result.b = q;
  37661. break;
  37662. }
  37663. }
  37664. result.a = 1;
  37665. };
  37666. /**
  37667. * Returns a value clamped between min and max
  37668. * @param value The value to clamp
  37669. * @param min The minimum of value
  37670. * @param max The maximum of value
  37671. * @returns The clamped value.
  37672. */
  37673. ColorCurves.clamp = function (value, min, max) {
  37674. return Math.min(Math.max(value, min), max);
  37675. };
  37676. /**
  37677. * Clones the current color curve instance.
  37678. * @return The cloned curves
  37679. */
  37680. ColorCurves.prototype.clone = function () {
  37681. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  37682. };
  37683. /**
  37684. * Serializes the current color curve instance to a json representation.
  37685. * @return a JSON representation
  37686. */
  37687. ColorCurves.prototype.serialize = function () {
  37688. return BABYLON.SerializationHelper.Serialize(this);
  37689. };
  37690. /**
  37691. * Parses the color curve from a json representation.
  37692. * @param source the JSON source to parse
  37693. * @return The parsed curves
  37694. */
  37695. ColorCurves.Parse = function (source) {
  37696. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  37697. };
  37698. __decorate([
  37699. BABYLON.serialize()
  37700. ], ColorCurves.prototype, "_globalHue", void 0);
  37701. __decorate([
  37702. BABYLON.serialize()
  37703. ], ColorCurves.prototype, "_globalDensity", void 0);
  37704. __decorate([
  37705. BABYLON.serialize()
  37706. ], ColorCurves.prototype, "_globalSaturation", void 0);
  37707. __decorate([
  37708. BABYLON.serialize()
  37709. ], ColorCurves.prototype, "_globalExposure", void 0);
  37710. __decorate([
  37711. BABYLON.serialize()
  37712. ], ColorCurves.prototype, "_highlightsHue", void 0);
  37713. __decorate([
  37714. BABYLON.serialize()
  37715. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  37716. __decorate([
  37717. BABYLON.serialize()
  37718. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  37719. __decorate([
  37720. BABYLON.serialize()
  37721. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  37722. __decorate([
  37723. BABYLON.serialize()
  37724. ], ColorCurves.prototype, "_midtonesHue", void 0);
  37725. __decorate([
  37726. BABYLON.serialize()
  37727. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  37728. __decorate([
  37729. BABYLON.serialize()
  37730. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  37731. __decorate([
  37732. BABYLON.serialize()
  37733. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  37734. return ColorCurves;
  37735. }());
  37736. BABYLON.ColorCurves = ColorCurves;
  37737. })(BABYLON || (BABYLON = {}));
  37738. //# sourceMappingURL=babylon.colorCurves.js.map
  37739. //# sourceMappingURL=babylon.behavior.js.map
  37740. var BABYLON;
  37741. (function (BABYLON) {
  37742. /**
  37743. * "Static Class" containing the most commonly used helper while dealing with material for
  37744. * rendering purpose.
  37745. *
  37746. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  37747. *
  37748. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  37749. */
  37750. var MaterialHelper = /** @class */ (function () {
  37751. function MaterialHelper() {
  37752. }
  37753. /**
  37754. * Bind the current view position to an effect.
  37755. * @param effect The effect to be bound
  37756. * @param scene The scene the eyes position is used from
  37757. */
  37758. MaterialHelper.BindEyePosition = function (effect, scene) {
  37759. if (scene._forcedViewPosition) {
  37760. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  37761. return;
  37762. }
  37763. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  37764. };
  37765. /**
  37766. * Helps preparing the defines values about the UVs in used in the effect.
  37767. * UVs are shared as much as we can accross chanels in the shaders.
  37768. * @param texture The texture we are preparing the UVs for
  37769. * @param defines The defines to update
  37770. * @param key The chanel key "diffuse", "specular"... used in the shader
  37771. */
  37772. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  37773. defines._needUVs = true;
  37774. defines[key] = true;
  37775. if (texture.getTextureMatrix().isIdentity(true)) {
  37776. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  37777. if (texture.coordinatesIndex === 0) {
  37778. defines["MAINUV1"] = true;
  37779. }
  37780. else {
  37781. defines["MAINUV2"] = true;
  37782. }
  37783. }
  37784. else {
  37785. defines[key + "DIRECTUV"] = 0;
  37786. }
  37787. };
  37788. /**
  37789. * Binds a texture matrix value to its corrsponding uniform
  37790. * @param texture The texture to bind the matrix for
  37791. * @param uniformBuffer The uniform buffer receivin the data
  37792. * @param key The chanel key "diffuse", "specular"... used in the shader
  37793. */
  37794. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  37795. var matrix = texture.getTextureMatrix();
  37796. if (!matrix.isIdentity(true)) {
  37797. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  37798. }
  37799. };
  37800. /**
  37801. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  37802. * @param mesh defines the current mesh
  37803. * @param scene defines the current scene
  37804. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  37805. * @param pointsCloud defines if point cloud rendering has to be turned on
  37806. * @param fogEnabled defines if fog has to be turned on
  37807. * @param alphaTest defines if alpha testing has to be turned on
  37808. * @param defines defines the current list of defines
  37809. */
  37810. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  37811. if (defines._areMiscDirty) {
  37812. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  37813. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  37814. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  37815. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  37816. defines["ALPHATEST"] = alphaTest;
  37817. }
  37818. };
  37819. /**
  37820. * Helper used to prepare the list of defines associated with frame values for shader compilation
  37821. * @param scene defines the current scene
  37822. * @param engine defines the current engine
  37823. * @param defines specifies the list of active defines
  37824. * @param useInstances defines if instances have to be turned on
  37825. * @param useClipPlane defines if clip plane have to be turned on
  37826. */
  37827. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  37828. if (useClipPlane === void 0) { useClipPlane = null; }
  37829. var changed = false;
  37830. if (useClipPlane == null) {
  37831. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  37832. }
  37833. if (defines["CLIPPLANE"] !== useClipPlane) {
  37834. defines["CLIPPLANE"] = useClipPlane;
  37835. changed = true;
  37836. }
  37837. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  37838. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  37839. changed = true;
  37840. }
  37841. if (defines["INSTANCES"] !== useInstances) {
  37842. defines["INSTANCES"] = useInstances;
  37843. changed = true;
  37844. }
  37845. if (changed) {
  37846. defines.markAsUnprocessed();
  37847. }
  37848. };
  37849. /**
  37850. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  37851. * @param mesh The mesh containing the geometry data we will draw
  37852. * @param defines The defines to update
  37853. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  37854. * @param useBones Precise whether bones should be used or not (override mesh info)
  37855. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  37856. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  37857. * @returns false if defines are considered not dirty and have not been checked
  37858. */
  37859. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  37860. if (useMorphTargets === void 0) { useMorphTargets = false; }
  37861. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  37862. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  37863. return false;
  37864. }
  37865. defines._normals = defines._needNormals;
  37866. defines._uvs = defines._needUVs;
  37867. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  37868. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37869. defines["TANGENT"] = true;
  37870. }
  37871. if (defines._needUVs) {
  37872. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  37873. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  37874. }
  37875. else {
  37876. defines["UV1"] = false;
  37877. defines["UV2"] = false;
  37878. }
  37879. if (useVertexColor) {
  37880. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  37881. defines["VERTEXCOLOR"] = hasVertexColors;
  37882. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  37883. }
  37884. if (useBones) {
  37885. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  37886. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  37887. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  37888. }
  37889. else {
  37890. defines["NUM_BONE_INFLUENCERS"] = 0;
  37891. defines["BonesPerMesh"] = 0;
  37892. }
  37893. }
  37894. if (useMorphTargets) {
  37895. var manager = mesh.morphTargetManager;
  37896. if (manager) {
  37897. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  37898. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  37899. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  37900. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  37901. }
  37902. else {
  37903. defines["MORPHTARGETS_TANGENT"] = false;
  37904. defines["MORPHTARGETS_NORMAL"] = false;
  37905. defines["MORPHTARGETS"] = false;
  37906. defines["NUM_MORPH_INFLUENCERS"] = 0;
  37907. }
  37908. }
  37909. return true;
  37910. };
  37911. /**
  37912. * Prepares the defines related to the light information passed in parameter
  37913. * @param scene The scene we are intending to draw
  37914. * @param mesh The mesh the effect is compiling for
  37915. * @param defines The defines to update
  37916. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  37917. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  37918. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  37919. * @returns true if normals will be required for the rest of the effect
  37920. */
  37921. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  37922. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  37923. if (disableLighting === void 0) { disableLighting = false; }
  37924. if (!defines._areLightsDirty) {
  37925. return defines._needNormals;
  37926. }
  37927. var lightIndex = 0;
  37928. var needNormals = false;
  37929. var needRebuild = false;
  37930. var lightmapMode = false;
  37931. var shadowEnabled = false;
  37932. var specularEnabled = false;
  37933. if (scene.lightsEnabled && !disableLighting) {
  37934. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  37935. var light = _a[_i];
  37936. needNormals = true;
  37937. if (defines["LIGHT" + lightIndex] === undefined) {
  37938. needRebuild = true;
  37939. }
  37940. defines["LIGHT" + lightIndex] = true;
  37941. defines["SPOTLIGHT" + lightIndex] = false;
  37942. defines["HEMILIGHT" + lightIndex] = false;
  37943. defines["POINTLIGHT" + lightIndex] = false;
  37944. defines["DIRLIGHT" + lightIndex] = false;
  37945. var type;
  37946. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  37947. type = "SPOTLIGHT" + lightIndex;
  37948. var spotLight = light;
  37949. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  37950. }
  37951. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  37952. type = "HEMILIGHT" + lightIndex;
  37953. }
  37954. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  37955. type = "POINTLIGHT" + lightIndex;
  37956. }
  37957. else {
  37958. type = "DIRLIGHT" + lightIndex;
  37959. }
  37960. defines[type] = true;
  37961. // Specular
  37962. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  37963. specularEnabled = true;
  37964. }
  37965. // Shadows
  37966. defines["SHADOW" + lightIndex] = false;
  37967. defines["SHADOWPCF" + lightIndex] = false;
  37968. defines["SHADOWESM" + lightIndex] = false;
  37969. defines["SHADOWCUBE" + lightIndex] = false;
  37970. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  37971. var shadowGenerator = light.getShadowGenerator();
  37972. if (shadowGenerator) {
  37973. shadowEnabled = true;
  37974. shadowGenerator.prepareDefines(defines, lightIndex);
  37975. }
  37976. }
  37977. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  37978. lightmapMode = true;
  37979. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  37980. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  37981. }
  37982. else {
  37983. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  37984. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  37985. }
  37986. lightIndex++;
  37987. if (lightIndex === maxSimultaneousLights)
  37988. break;
  37989. }
  37990. }
  37991. defines["SPECULARTERM"] = specularEnabled;
  37992. defines["SHADOWS"] = shadowEnabled;
  37993. // Resetting all other lights if any
  37994. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  37995. if (defines["LIGHT" + index] !== undefined) {
  37996. defines["LIGHT" + index] = false;
  37997. defines["HEMILIGHT" + lightIndex] = false;
  37998. defines["POINTLIGHT" + lightIndex] = false;
  37999. defines["DIRLIGHT" + lightIndex] = false;
  38000. defines["SPOTLIGHT" + lightIndex] = false;
  38001. defines["SHADOW" + lightIndex] = false;
  38002. }
  38003. }
  38004. var caps = scene.getEngine().getCaps();
  38005. if (defines["SHADOWFLOAT"] === undefined) {
  38006. needRebuild = true;
  38007. }
  38008. defines["SHADOWFLOAT"] = shadowEnabled &&
  38009. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  38010. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  38011. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  38012. if (needRebuild) {
  38013. defines.rebuild();
  38014. }
  38015. return needNormals;
  38016. };
  38017. /**
  38018. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  38019. * that won t be acctive due to defines being turned off.
  38020. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  38021. * @param samplersList The samplers list
  38022. * @param defines The defines helping in the list generation
  38023. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  38024. */
  38025. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  38026. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38027. var uniformsList;
  38028. var uniformBuffersList = null;
  38029. if (uniformsListOrOptions.uniformsNames) {
  38030. var options = uniformsListOrOptions;
  38031. uniformsList = options.uniformsNames;
  38032. uniformBuffersList = options.uniformBuffersNames;
  38033. samplersList = options.samplers;
  38034. defines = options.defines;
  38035. maxSimultaneousLights = options.maxSimultaneousLights;
  38036. }
  38037. else {
  38038. uniformsList = uniformsListOrOptions;
  38039. if (!samplersList) {
  38040. samplersList = [];
  38041. }
  38042. }
  38043. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38044. if (!defines["LIGHT" + lightIndex]) {
  38045. break;
  38046. }
  38047. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  38048. if (uniformBuffersList) {
  38049. uniformBuffersList.push("Light" + lightIndex);
  38050. }
  38051. samplersList.push("shadowSampler" + lightIndex);
  38052. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  38053. samplersList.push("projectionLightSampler" + lightIndex);
  38054. uniformsList.push("textureProjectionMatrix" + lightIndex);
  38055. }
  38056. }
  38057. if (defines["NUM_MORPH_INFLUENCERS"]) {
  38058. uniformsList.push("morphTargetInfluences");
  38059. }
  38060. };
  38061. /**
  38062. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  38063. * @param defines The defines to update while falling back
  38064. * @param fallbacks The authorized effect fallbacks
  38065. * @param maxSimultaneousLights The maximum number of lights allowed
  38066. * @param rank the current rank of the Effect
  38067. * @returns The newly affected rank
  38068. */
  38069. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  38070. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38071. if (rank === void 0) { rank = 0; }
  38072. var lightFallbackRank = 0;
  38073. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  38074. if (!defines["LIGHT" + lightIndex]) {
  38075. break;
  38076. }
  38077. if (lightIndex > 0) {
  38078. lightFallbackRank = rank + lightIndex;
  38079. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  38080. }
  38081. if (!defines["SHADOWS"]) {
  38082. if (defines["SHADOW" + lightIndex]) {
  38083. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  38084. }
  38085. if (defines["SHADOWPCF" + lightIndex]) {
  38086. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  38087. }
  38088. if (defines["SHADOWESM" + lightIndex]) {
  38089. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  38090. }
  38091. }
  38092. }
  38093. return lightFallbackRank++;
  38094. };
  38095. /**
  38096. * Prepares the list of attributes required for morph targets according to the effect defines.
  38097. * @param attribs The current list of supported attribs
  38098. * @param mesh The mesh to prepare the morph targets attributes for
  38099. * @param defines The current Defines of the effect
  38100. */
  38101. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  38102. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  38103. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  38104. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  38105. var manager = mesh.morphTargetManager;
  38106. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  38107. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  38108. for (var index = 0; index < influencers; index++) {
  38109. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  38110. if (normal) {
  38111. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  38112. }
  38113. if (tangent) {
  38114. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  38115. }
  38116. if (attribs.length > maxAttributesCount) {
  38117. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  38118. }
  38119. }
  38120. }
  38121. };
  38122. /**
  38123. * Prepares the list of attributes required for bones according to the effect defines.
  38124. * @param attribs The current list of supported attribs
  38125. * @param mesh The mesh to prepare the bones attributes for
  38126. * @param defines The current Defines of the effect
  38127. * @param fallbacks The current efffect fallback strategy
  38128. */
  38129. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  38130. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  38131. fallbacks.addCPUSkinningFallback(0, mesh);
  38132. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38133. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38134. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  38135. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38136. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38137. }
  38138. }
  38139. };
  38140. /**
  38141. * Prepares the list of attributes required for instances according to the effect defines.
  38142. * @param attribs The current list of supported attribs
  38143. * @param defines The current Defines of the effect
  38144. */
  38145. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  38146. if (defines["INSTANCES"]) {
  38147. attribs.push("world0");
  38148. attribs.push("world1");
  38149. attribs.push("world2");
  38150. attribs.push("world3");
  38151. }
  38152. };
  38153. /**
  38154. * Binds the light shadow information to the effect for the given mesh.
  38155. * @param light The light containing the generator
  38156. * @param scene The scene the lights belongs to
  38157. * @param mesh The mesh we are binding the information to render
  38158. * @param lightIndex The light index in the effect used to render the mesh
  38159. * @param effect The effect we are binding the data to
  38160. */
  38161. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  38162. if (light.shadowEnabled && mesh.receiveShadows) {
  38163. var shadowGenerator = light.getShadowGenerator();
  38164. if (shadowGenerator) {
  38165. shadowGenerator.bindShadowLight(lightIndex, effect);
  38166. }
  38167. }
  38168. };
  38169. /**
  38170. * Binds the light information to the effect.
  38171. * @param light The light containing the generator
  38172. * @param effect The effect we are binding the data to
  38173. * @param lightIndex The light index in the effect used to render
  38174. */
  38175. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  38176. light.transferToEffect(effect, lightIndex + "");
  38177. };
  38178. /**
  38179. * Binds the lights information from the scene to the effect for the given mesh.
  38180. * @param scene The scene the lights belongs to
  38181. * @param mesh The mesh we are binding the information to render
  38182. * @param effect The effect we are binding the data to
  38183. * @param defines The generated defines for the effect
  38184. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  38185. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  38186. */
  38187. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  38188. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38189. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  38190. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  38191. for (var i = 0; i < len; i++) {
  38192. var light = mesh._lightSources[i];
  38193. var iAsString = i.toString();
  38194. var scaledIntensity = light.getScaledIntensity();
  38195. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  38196. MaterialHelper.BindLightProperties(light, effect, i);
  38197. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  38198. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  38199. if (defines["SPECULARTERM"]) {
  38200. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  38201. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  38202. }
  38203. // Shadows
  38204. if (scene.shadowsEnabled) {
  38205. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  38206. }
  38207. light._uniformBuffer.update();
  38208. }
  38209. };
  38210. /**
  38211. * Binds the fog information from the scene to the effect for the given mesh.
  38212. * @param scene The scene the lights belongs to
  38213. * @param mesh The mesh we are binding the information to render
  38214. * @param effect The effect we are binding the data to
  38215. */
  38216. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  38217. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  38218. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  38219. effect.setColor3("vFogColor", scene.fogColor);
  38220. }
  38221. };
  38222. /**
  38223. * Binds the bones information from the mesh to the effect.
  38224. * @param mesh The mesh we are binding the information to render
  38225. * @param effect The effect we are binding the data to
  38226. */
  38227. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  38228. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38229. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  38230. if (matrices && effect) {
  38231. effect.setMatrices("mBones", matrices);
  38232. }
  38233. }
  38234. };
  38235. /**
  38236. * Binds the morph targets information from the mesh to the effect.
  38237. * @param abstractMesh The mesh we are binding the information to render
  38238. * @param effect The effect we are binding the data to
  38239. */
  38240. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  38241. var manager = abstractMesh.morphTargetManager;
  38242. if (!abstractMesh || !manager) {
  38243. return;
  38244. }
  38245. effect.setFloatArray("morphTargetInfluences", manager.influences);
  38246. };
  38247. /**
  38248. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  38249. * @param defines The generated defines used in the effect
  38250. * @param effect The effect we are binding the data to
  38251. * @param scene The scene we are willing to render with logarithmic scale for
  38252. */
  38253. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  38254. if (defines["LOGARITHMICDEPTH"]) {
  38255. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  38256. }
  38257. };
  38258. /**
  38259. * Binds the clip plane information from the scene to the effect.
  38260. * @param scene The scene the clip plane information are extracted from
  38261. * @param effect The effect we are binding the data to
  38262. */
  38263. MaterialHelper.BindClipPlane = function (effect, scene) {
  38264. if (scene.clipPlane) {
  38265. var clipPlane = scene.clipPlane;
  38266. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  38267. }
  38268. };
  38269. return MaterialHelper;
  38270. }());
  38271. BABYLON.MaterialHelper = MaterialHelper;
  38272. })(BABYLON || (BABYLON = {}));
  38273. //# sourceMappingURL=babylon.materialHelper.js.map
  38274. var BABYLON;
  38275. (function (BABYLON) {
  38276. var PushMaterial = /** @class */ (function (_super) {
  38277. __extends(PushMaterial, _super);
  38278. function PushMaterial(name, scene) {
  38279. var _this = _super.call(this, name, scene) || this;
  38280. _this._normalMatrix = new BABYLON.Matrix();
  38281. _this.storeEffectOnSubMeshes = true;
  38282. return _this;
  38283. }
  38284. PushMaterial.prototype.getEffect = function () {
  38285. return this._activeEffect;
  38286. };
  38287. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  38288. if (!mesh) {
  38289. return false;
  38290. }
  38291. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  38292. return true;
  38293. }
  38294. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  38295. };
  38296. /**
  38297. * Binds the given world matrix to the active effect
  38298. *
  38299. * @param world the matrix to bind
  38300. */
  38301. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  38302. this._activeEffect.setMatrix("world", world);
  38303. };
  38304. /**
  38305. * Binds the given normal matrix to the active effect
  38306. *
  38307. * @param normalMatrix the matrix to bind
  38308. */
  38309. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  38310. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  38311. };
  38312. PushMaterial.prototype.bind = function (world, mesh) {
  38313. if (!mesh) {
  38314. return;
  38315. }
  38316. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  38317. };
  38318. PushMaterial.prototype._afterBind = function (mesh, effect) {
  38319. if (effect === void 0) { effect = null; }
  38320. _super.prototype._afterBind.call(this, mesh);
  38321. this.getScene()._cachedEffect = effect;
  38322. };
  38323. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  38324. if (visibility === void 0) { visibility = 1; }
  38325. return scene.isCachedMaterialInvalid(this, effect, visibility);
  38326. };
  38327. return PushMaterial;
  38328. }(BABYLON.Material));
  38329. BABYLON.PushMaterial = PushMaterial;
  38330. })(BABYLON || (BABYLON = {}));
  38331. //# sourceMappingURL=babylon.pushMaterial.js.map
  38332. var BABYLON;
  38333. (function (BABYLON) {
  38334. /** @ignore */
  38335. var StandardMaterialDefines = /** @class */ (function (_super) {
  38336. __extends(StandardMaterialDefines, _super);
  38337. function StandardMaterialDefines() {
  38338. var _this = _super.call(this) || this;
  38339. _this.MAINUV1 = false;
  38340. _this.MAINUV2 = false;
  38341. _this.DIFFUSE = false;
  38342. _this.DIFFUSEDIRECTUV = 0;
  38343. _this.AMBIENT = false;
  38344. _this.AMBIENTDIRECTUV = 0;
  38345. _this.OPACITY = false;
  38346. _this.OPACITYDIRECTUV = 0;
  38347. _this.OPACITYRGB = false;
  38348. _this.REFLECTION = false;
  38349. _this.EMISSIVE = false;
  38350. _this.EMISSIVEDIRECTUV = 0;
  38351. _this.SPECULAR = false;
  38352. _this.SPECULARDIRECTUV = 0;
  38353. _this.BUMP = false;
  38354. _this.BUMPDIRECTUV = 0;
  38355. _this.PARALLAX = false;
  38356. _this.PARALLAXOCCLUSION = false;
  38357. _this.SPECULAROVERALPHA = false;
  38358. _this.CLIPPLANE = false;
  38359. _this.ALPHATEST = false;
  38360. _this.DEPTHPREPASS = false;
  38361. _this.ALPHAFROMDIFFUSE = false;
  38362. _this.POINTSIZE = false;
  38363. _this.FOG = false;
  38364. _this.SPECULARTERM = false;
  38365. _this.DIFFUSEFRESNEL = false;
  38366. _this.OPACITYFRESNEL = false;
  38367. _this.REFLECTIONFRESNEL = false;
  38368. _this.REFRACTIONFRESNEL = false;
  38369. _this.EMISSIVEFRESNEL = false;
  38370. _this.FRESNEL = false;
  38371. _this.NORMAL = false;
  38372. _this.UV1 = false;
  38373. _this.UV2 = false;
  38374. _this.VERTEXCOLOR = false;
  38375. _this.VERTEXALPHA = false;
  38376. _this.NUM_BONE_INFLUENCERS = 0;
  38377. _this.BonesPerMesh = 0;
  38378. _this.INSTANCES = false;
  38379. _this.GLOSSINESS = false;
  38380. _this.ROUGHNESS = false;
  38381. _this.EMISSIVEASILLUMINATION = false;
  38382. _this.LINKEMISSIVEWITHDIFFUSE = false;
  38383. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  38384. _this.LIGHTMAP = false;
  38385. _this.LIGHTMAPDIRECTUV = 0;
  38386. _this.OBJECTSPACE_NORMALMAP = false;
  38387. _this.USELIGHTMAPASSHADOWMAP = false;
  38388. _this.REFLECTIONMAP_3D = false;
  38389. _this.REFLECTIONMAP_SPHERICAL = false;
  38390. _this.REFLECTIONMAP_PLANAR = false;
  38391. _this.REFLECTIONMAP_CUBIC = false;
  38392. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  38393. _this.REFLECTIONMAP_PROJECTION = false;
  38394. _this.REFLECTIONMAP_SKYBOX = false;
  38395. _this.REFLECTIONMAP_EXPLICIT = false;
  38396. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  38397. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  38398. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  38399. _this.INVERTCUBICMAP = false;
  38400. _this.LOGARITHMICDEPTH = false;
  38401. _this.REFRACTION = false;
  38402. _this.REFRACTIONMAP_3D = false;
  38403. _this.REFLECTIONOVERALPHA = false;
  38404. _this.TWOSIDEDLIGHTING = false;
  38405. _this.SHADOWFLOAT = false;
  38406. _this.MORPHTARGETS = false;
  38407. _this.MORPHTARGETS_NORMAL = false;
  38408. _this.MORPHTARGETS_TANGENT = false;
  38409. _this.NUM_MORPH_INFLUENCERS = 0;
  38410. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  38411. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  38412. _this.IMAGEPROCESSING = false;
  38413. _this.VIGNETTE = false;
  38414. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  38415. _this.VIGNETTEBLENDMODEOPAQUE = false;
  38416. _this.TONEMAPPING = false;
  38417. _this.CONTRAST = false;
  38418. _this.COLORCURVES = false;
  38419. _this.COLORGRADING = false;
  38420. _this.COLORGRADING3D = false;
  38421. _this.SAMPLER3DGREENDEPTH = false;
  38422. _this.SAMPLER3DBGRMAP = false;
  38423. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  38424. _this.EXPOSURE = false;
  38425. _this.rebuild();
  38426. return _this;
  38427. }
  38428. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  38429. var modes = [
  38430. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  38431. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  38432. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  38433. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  38434. ];
  38435. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  38436. var mode = modes_1[_i];
  38437. this[mode] = (mode === modeToEnable);
  38438. }
  38439. };
  38440. return StandardMaterialDefines;
  38441. }(BABYLON.MaterialDefines));
  38442. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  38443. var StandardMaterial = /** @class */ (function (_super) {
  38444. __extends(StandardMaterial, _super);
  38445. function StandardMaterial(name, scene) {
  38446. var _this = _super.call(this, name, scene) || this;
  38447. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  38448. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  38449. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  38450. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  38451. _this.specularPower = 64;
  38452. _this._useAlphaFromDiffuseTexture = false;
  38453. _this._useEmissiveAsIllumination = false;
  38454. _this._linkEmissiveWithDiffuse = false;
  38455. _this._useSpecularOverAlpha = false;
  38456. _this._useReflectionOverAlpha = false;
  38457. _this._disableLighting = false;
  38458. _this._useObjectSpaceNormalMap = false;
  38459. _this._useParallax = false;
  38460. _this._useParallaxOcclusion = false;
  38461. _this.parallaxScaleBias = 0.05;
  38462. _this._roughness = 0;
  38463. _this.indexOfRefraction = 0.98;
  38464. _this.invertRefractionY = true;
  38465. _this._useLightmapAsShadowmap = false;
  38466. _this._useReflectionFresnelFromSpecular = false;
  38467. _this._useGlossinessFromSpecularMapAlpha = false;
  38468. _this._maxSimultaneousLights = 4;
  38469. /**
  38470. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  38471. */
  38472. _this._invertNormalMapX = false;
  38473. /**
  38474. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  38475. */
  38476. _this._invertNormalMapY = false;
  38477. /**
  38478. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  38479. */
  38480. _this._twoSidedLighting = false;
  38481. _this._renderTargets = new BABYLON.SmartArray(16);
  38482. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  38483. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  38484. // Setup the default processing configuration to the scene.
  38485. _this._attachImageProcessingConfiguration(null);
  38486. _this.getRenderTargetTextures = function () {
  38487. _this._renderTargets.reset();
  38488. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  38489. _this._renderTargets.push(_this._reflectionTexture);
  38490. }
  38491. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  38492. _this._renderTargets.push(_this._refractionTexture);
  38493. }
  38494. return _this._renderTargets;
  38495. };
  38496. return _this;
  38497. }
  38498. ;
  38499. ;
  38500. ;
  38501. ;
  38502. ;
  38503. ;
  38504. ;
  38505. ;
  38506. ;
  38507. ;
  38508. ;
  38509. ;
  38510. ;
  38511. ;
  38512. ;
  38513. ;
  38514. ;
  38515. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  38516. /**
  38517. * Gets the image processing configuration used either in this material.
  38518. */
  38519. get: function () {
  38520. return this._imageProcessingConfiguration;
  38521. },
  38522. /**
  38523. * Sets the Default image processing configuration used either in the this material.
  38524. *
  38525. * If sets to null, the scene one is in use.
  38526. */
  38527. set: function (value) {
  38528. this._attachImageProcessingConfiguration(value);
  38529. // Ensure the effect will be rebuilt.
  38530. this._markAllSubMeshesAsTexturesDirty();
  38531. },
  38532. enumerable: true,
  38533. configurable: true
  38534. });
  38535. /**
  38536. * Attaches a new image processing configuration to the Standard Material.
  38537. * @param configuration
  38538. */
  38539. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  38540. var _this = this;
  38541. if (configuration === this._imageProcessingConfiguration) {
  38542. return;
  38543. }
  38544. // Detaches observer.
  38545. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  38546. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  38547. }
  38548. // Pick the scene configuration if needed.
  38549. if (!configuration) {
  38550. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  38551. }
  38552. else {
  38553. this._imageProcessingConfiguration = configuration;
  38554. }
  38555. // Attaches observer.
  38556. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  38557. _this._markAllSubMeshesAsImageProcessingDirty();
  38558. });
  38559. };
  38560. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  38561. /**
  38562. * Gets wether the color curves effect is enabled.
  38563. */
  38564. get: function () {
  38565. return this.imageProcessingConfiguration.colorCurvesEnabled;
  38566. },
  38567. /**
  38568. * Sets wether the color curves effect is enabled.
  38569. */
  38570. set: function (value) {
  38571. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  38572. },
  38573. enumerable: true,
  38574. configurable: true
  38575. });
  38576. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  38577. /**
  38578. * Gets wether the color grading effect is enabled.
  38579. */
  38580. get: function () {
  38581. return this.imageProcessingConfiguration.colorGradingEnabled;
  38582. },
  38583. /**
  38584. * Gets wether the color grading effect is enabled.
  38585. */
  38586. set: function (value) {
  38587. this.imageProcessingConfiguration.colorGradingEnabled = value;
  38588. },
  38589. enumerable: true,
  38590. configurable: true
  38591. });
  38592. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  38593. /**
  38594. * Gets wether tonemapping is enabled or not.
  38595. */
  38596. get: function () {
  38597. return this._imageProcessingConfiguration.toneMappingEnabled;
  38598. },
  38599. /**
  38600. * Sets wether tonemapping is enabled or not
  38601. */
  38602. set: function (value) {
  38603. this._imageProcessingConfiguration.toneMappingEnabled = value;
  38604. },
  38605. enumerable: true,
  38606. configurable: true
  38607. });
  38608. ;
  38609. ;
  38610. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  38611. /**
  38612. * The camera exposure used on this material.
  38613. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38614. * This corresponds to a photographic exposure.
  38615. */
  38616. get: function () {
  38617. return this._imageProcessingConfiguration.exposure;
  38618. },
  38619. /**
  38620. * The camera exposure used on this material.
  38621. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  38622. * This corresponds to a photographic exposure.
  38623. */
  38624. set: function (value) {
  38625. this._imageProcessingConfiguration.exposure = value;
  38626. },
  38627. enumerable: true,
  38628. configurable: true
  38629. });
  38630. ;
  38631. ;
  38632. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  38633. /**
  38634. * Gets The camera contrast used on this material.
  38635. */
  38636. get: function () {
  38637. return this._imageProcessingConfiguration.contrast;
  38638. },
  38639. /**
  38640. * Sets The camera contrast used on this material.
  38641. */
  38642. set: function (value) {
  38643. this._imageProcessingConfiguration.contrast = value;
  38644. },
  38645. enumerable: true,
  38646. configurable: true
  38647. });
  38648. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  38649. /**
  38650. * Gets the Color Grading 2D Lookup Texture.
  38651. */
  38652. get: function () {
  38653. return this._imageProcessingConfiguration.colorGradingTexture;
  38654. },
  38655. /**
  38656. * Sets the Color Grading 2D Lookup Texture.
  38657. */
  38658. set: function (value) {
  38659. this._imageProcessingConfiguration.colorGradingTexture = value;
  38660. },
  38661. enumerable: true,
  38662. configurable: true
  38663. });
  38664. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  38665. /**
  38666. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38667. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38668. * 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;
  38669. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38670. */
  38671. get: function () {
  38672. return this._imageProcessingConfiguration.colorCurves;
  38673. },
  38674. /**
  38675. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38676. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38677. * 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;
  38678. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38679. */
  38680. set: function (value) {
  38681. this._imageProcessingConfiguration.colorCurves = value;
  38682. },
  38683. enumerable: true,
  38684. configurable: true
  38685. });
  38686. StandardMaterial.prototype.getClassName = function () {
  38687. return "StandardMaterial";
  38688. };
  38689. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  38690. get: function () {
  38691. return this._useLogarithmicDepth;
  38692. },
  38693. set: function (value) {
  38694. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  38695. this._markAllSubMeshesAsMiscDirty();
  38696. },
  38697. enumerable: true,
  38698. configurable: true
  38699. });
  38700. StandardMaterial.prototype.needAlphaBlending = function () {
  38701. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  38702. };
  38703. StandardMaterial.prototype.needAlphaTesting = function () {
  38704. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  38705. };
  38706. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  38707. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  38708. };
  38709. StandardMaterial.prototype.getAlphaTestTexture = function () {
  38710. return this._diffuseTexture;
  38711. };
  38712. /**
  38713. * Child classes can use it to update shaders
  38714. */
  38715. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  38716. if (useInstances === void 0) { useInstances = false; }
  38717. if (subMesh.effect && this.isFrozen) {
  38718. if (this._wasPreviouslyReady && subMesh.effect) {
  38719. return true;
  38720. }
  38721. }
  38722. if (!subMesh._materialDefines) {
  38723. subMesh._materialDefines = new StandardMaterialDefines();
  38724. }
  38725. var scene = this.getScene();
  38726. var defines = subMesh._materialDefines;
  38727. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  38728. if (defines._renderId === scene.getRenderId()) {
  38729. return true;
  38730. }
  38731. }
  38732. var engine = scene.getEngine();
  38733. // Lights
  38734. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  38735. // Textures
  38736. if (defines._areTexturesDirty) {
  38737. defines._needUVs = false;
  38738. defines.MAINUV1 = false;
  38739. defines.MAINUV2 = false;
  38740. if (scene.texturesEnabled) {
  38741. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  38742. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  38743. return false;
  38744. }
  38745. else {
  38746. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  38747. }
  38748. }
  38749. else {
  38750. defines.DIFFUSE = false;
  38751. }
  38752. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  38753. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  38754. return false;
  38755. }
  38756. else {
  38757. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  38758. }
  38759. }
  38760. else {
  38761. defines.AMBIENT = false;
  38762. }
  38763. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  38764. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  38765. return false;
  38766. }
  38767. else {
  38768. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  38769. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  38770. }
  38771. }
  38772. else {
  38773. defines.OPACITY = false;
  38774. }
  38775. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  38776. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  38777. return false;
  38778. }
  38779. else {
  38780. defines._needNormals = true;
  38781. defines.REFLECTION = true;
  38782. defines.ROUGHNESS = (this._roughness > 0);
  38783. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  38784. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  38785. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  38786. switch (this._reflectionTexture.coordinatesMode) {
  38787. case BABYLON.Texture.CUBIC_MODE:
  38788. case BABYLON.Texture.INVCUBIC_MODE:
  38789. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  38790. break;
  38791. case BABYLON.Texture.EXPLICIT_MODE:
  38792. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  38793. break;
  38794. case BABYLON.Texture.PLANAR_MODE:
  38795. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  38796. break;
  38797. case BABYLON.Texture.PROJECTION_MODE:
  38798. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  38799. break;
  38800. case BABYLON.Texture.SKYBOX_MODE:
  38801. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  38802. break;
  38803. case BABYLON.Texture.SPHERICAL_MODE:
  38804. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  38805. break;
  38806. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  38807. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  38808. break;
  38809. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  38810. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  38811. break;
  38812. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  38813. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  38814. break;
  38815. }
  38816. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  38817. }
  38818. }
  38819. else {
  38820. defines.REFLECTION = false;
  38821. }
  38822. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  38823. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  38824. return false;
  38825. }
  38826. else {
  38827. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  38828. }
  38829. }
  38830. else {
  38831. defines.EMISSIVE = false;
  38832. }
  38833. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  38834. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  38835. return false;
  38836. }
  38837. else {
  38838. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  38839. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  38840. }
  38841. }
  38842. else {
  38843. defines.LIGHTMAP = false;
  38844. }
  38845. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  38846. if (!this._specularTexture.isReadyOrNotBlocking()) {
  38847. return false;
  38848. }
  38849. else {
  38850. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  38851. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  38852. }
  38853. }
  38854. else {
  38855. defines.SPECULAR = false;
  38856. }
  38857. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  38858. // Bump texure can not be not blocking.
  38859. if (!this._bumpTexture.isReady()) {
  38860. return false;
  38861. }
  38862. else {
  38863. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  38864. defines.PARALLAX = this._useParallax;
  38865. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  38866. }
  38867. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  38868. }
  38869. else {
  38870. defines.BUMP = false;
  38871. }
  38872. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  38873. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  38874. return false;
  38875. }
  38876. else {
  38877. defines._needUVs = true;
  38878. defines.REFRACTION = true;
  38879. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  38880. }
  38881. }
  38882. else {
  38883. defines.REFRACTION = false;
  38884. }
  38885. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  38886. }
  38887. else {
  38888. defines.DIFFUSE = false;
  38889. defines.AMBIENT = false;
  38890. defines.OPACITY = false;
  38891. defines.REFLECTION = false;
  38892. defines.EMISSIVE = false;
  38893. defines.LIGHTMAP = false;
  38894. defines.BUMP = false;
  38895. defines.REFRACTION = false;
  38896. }
  38897. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  38898. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  38899. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  38900. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  38901. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  38902. }
  38903. if (defines._areImageProcessingDirty) {
  38904. if (!this._imageProcessingConfiguration.isReady()) {
  38905. return false;
  38906. }
  38907. this._imageProcessingConfiguration.prepareDefines(defines);
  38908. }
  38909. if (defines._areFresnelDirty) {
  38910. if (StandardMaterial.FresnelEnabled) {
  38911. // Fresnel
  38912. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  38913. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  38914. this._reflectionFresnelParameters) {
  38915. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  38916. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  38917. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  38918. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  38919. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  38920. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  38921. defines._needNormals = true;
  38922. defines.FRESNEL = true;
  38923. }
  38924. }
  38925. else {
  38926. defines.FRESNEL = false;
  38927. }
  38928. }
  38929. // Misc.
  38930. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  38931. // Attribs
  38932. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  38933. // Values that need to be evaluated on every frame
  38934. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  38935. // Get correct effect
  38936. if (defines.isDirty) {
  38937. defines.markAsProcessed();
  38938. scene.resetCachedMaterial();
  38939. // Fallbacks
  38940. var fallbacks = new BABYLON.EffectFallbacks();
  38941. if (defines.REFLECTION) {
  38942. fallbacks.addFallback(0, "REFLECTION");
  38943. }
  38944. if (defines.SPECULAR) {
  38945. fallbacks.addFallback(0, "SPECULAR");
  38946. }
  38947. if (defines.BUMP) {
  38948. fallbacks.addFallback(0, "BUMP");
  38949. }
  38950. if (defines.PARALLAX) {
  38951. fallbacks.addFallback(1, "PARALLAX");
  38952. }
  38953. if (defines.PARALLAXOCCLUSION) {
  38954. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  38955. }
  38956. if (defines.SPECULAROVERALPHA) {
  38957. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  38958. }
  38959. if (defines.FOG) {
  38960. fallbacks.addFallback(1, "FOG");
  38961. }
  38962. if (defines.POINTSIZE) {
  38963. fallbacks.addFallback(0, "POINTSIZE");
  38964. }
  38965. if (defines.LOGARITHMICDEPTH) {
  38966. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  38967. }
  38968. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  38969. if (defines.SPECULARTERM) {
  38970. fallbacks.addFallback(0, "SPECULARTERM");
  38971. }
  38972. if (defines.DIFFUSEFRESNEL) {
  38973. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  38974. }
  38975. if (defines.OPACITYFRESNEL) {
  38976. fallbacks.addFallback(2, "OPACITYFRESNEL");
  38977. }
  38978. if (defines.REFLECTIONFRESNEL) {
  38979. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  38980. }
  38981. if (defines.EMISSIVEFRESNEL) {
  38982. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  38983. }
  38984. if (defines.FRESNEL) {
  38985. fallbacks.addFallback(4, "FRESNEL");
  38986. }
  38987. //Attributes
  38988. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38989. if (defines.NORMAL) {
  38990. attribs.push(BABYLON.VertexBuffer.NormalKind);
  38991. }
  38992. if (defines.UV1) {
  38993. attribs.push(BABYLON.VertexBuffer.UVKind);
  38994. }
  38995. if (defines.UV2) {
  38996. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38997. }
  38998. if (defines.VERTEXCOLOR) {
  38999. attribs.push(BABYLON.VertexBuffer.ColorKind);
  39000. }
  39001. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  39002. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  39003. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  39004. var shaderName = "default";
  39005. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  39006. "vFogInfos", "vFogColor", "pointSize",
  39007. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  39008. "mBones",
  39009. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  39010. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  39011. "vReflectionPosition", "vReflectionSize",
  39012. "logarithmicDepthConstant", "vTangentSpaceParams"
  39013. ];
  39014. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  39015. var uniformBuffers = ["Material", "Scene"];
  39016. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  39017. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  39018. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  39019. uniformsNames: uniforms,
  39020. uniformBuffersNames: uniformBuffers,
  39021. samplers: samplers,
  39022. defines: defines,
  39023. maxSimultaneousLights: this._maxSimultaneousLights
  39024. });
  39025. if (this.customShaderNameResolve) {
  39026. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  39027. }
  39028. var join = defines.toString();
  39029. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  39030. attributes: attribs,
  39031. uniformsNames: uniforms,
  39032. uniformBuffersNames: uniformBuffers,
  39033. samplers: samplers,
  39034. defines: join,
  39035. fallbacks: fallbacks,
  39036. onCompiled: this.onCompiled,
  39037. onError: this.onError,
  39038. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  39039. }, engine), defines);
  39040. this.buildUniformLayout();
  39041. }
  39042. if (!subMesh.effect || !subMesh.effect.isReady()) {
  39043. return false;
  39044. }
  39045. defines._renderId = scene.getRenderId();
  39046. this._wasPreviouslyReady = true;
  39047. return true;
  39048. };
  39049. StandardMaterial.prototype.buildUniformLayout = function () {
  39050. // Order is important !
  39051. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  39052. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  39053. this._uniformBuffer.addUniform("opacityParts", 4);
  39054. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  39055. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  39056. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  39057. this._uniformBuffer.addUniform("refractionRightColor", 4);
  39058. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  39059. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  39060. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  39061. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  39062. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  39063. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  39064. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  39065. this._uniformBuffer.addUniform("vReflectionSize", 3);
  39066. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  39067. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  39068. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  39069. this._uniformBuffer.addUniform("vBumpInfos", 3);
  39070. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  39071. this._uniformBuffer.addUniform("ambientMatrix", 16);
  39072. this._uniformBuffer.addUniform("opacityMatrix", 16);
  39073. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  39074. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  39075. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  39076. this._uniformBuffer.addUniform("specularMatrix", 16);
  39077. this._uniformBuffer.addUniform("bumpMatrix", 16);
  39078. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  39079. this._uniformBuffer.addUniform("refractionMatrix", 16);
  39080. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  39081. this._uniformBuffer.addUniform("vSpecularColor", 4);
  39082. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  39083. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  39084. this._uniformBuffer.addUniform("pointSize", 1);
  39085. this._uniformBuffer.create();
  39086. };
  39087. StandardMaterial.prototype.unbind = function () {
  39088. if (this._activeEffect) {
  39089. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  39090. this._activeEffect.setTexture("reflection2DSampler", null);
  39091. }
  39092. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  39093. this._activeEffect.setTexture("refraction2DSampler", null);
  39094. }
  39095. }
  39096. _super.prototype.unbind.call(this);
  39097. };
  39098. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  39099. var scene = this.getScene();
  39100. var defines = subMesh._materialDefines;
  39101. if (!defines) {
  39102. return;
  39103. }
  39104. var effect = subMesh.effect;
  39105. if (!effect) {
  39106. return;
  39107. }
  39108. this._activeEffect = effect;
  39109. // Matrices
  39110. this.bindOnlyWorldMatrix(world);
  39111. // Normal Matrix
  39112. if (defines.OBJECTSPACE_NORMALMAP) {
  39113. world.toNormalMatrix(this._normalMatrix);
  39114. this.bindOnlyNormalMatrix(this._normalMatrix);
  39115. }
  39116. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  39117. // Bones
  39118. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  39119. if (mustRebind) {
  39120. this._uniformBuffer.bindToEffect(effect, "Material");
  39121. this.bindViewProjection(effect);
  39122. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  39123. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  39124. // Fresnel
  39125. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  39126. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  39127. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  39128. }
  39129. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  39130. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  39131. }
  39132. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  39133. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  39134. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  39135. }
  39136. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  39137. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  39138. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  39139. }
  39140. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  39141. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  39142. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  39143. }
  39144. }
  39145. // Textures
  39146. if (scene.texturesEnabled) {
  39147. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39148. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  39149. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  39150. }
  39151. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39152. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  39153. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  39154. }
  39155. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39156. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  39157. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  39158. }
  39159. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39160. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  39161. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  39162. if (this._reflectionTexture.boundingBoxSize) {
  39163. var cubeTexture = this._reflectionTexture;
  39164. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  39165. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  39166. }
  39167. }
  39168. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39169. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  39170. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  39171. }
  39172. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39173. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  39174. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  39175. }
  39176. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39177. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  39178. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  39179. }
  39180. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39181. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  39182. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  39183. if (scene._mirroredCameraPosition) {
  39184. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  39185. }
  39186. else {
  39187. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  39188. }
  39189. }
  39190. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39191. var depth = 1.0;
  39192. if (!this._refractionTexture.isCube) {
  39193. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  39194. if (this._refractionTexture.depth) {
  39195. depth = this._refractionTexture.depth;
  39196. }
  39197. }
  39198. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  39199. }
  39200. }
  39201. // Point size
  39202. if (this.pointsCloud) {
  39203. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  39204. }
  39205. if (defines.SPECULARTERM) {
  39206. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  39207. }
  39208. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  39209. // Diffuse
  39210. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  39211. }
  39212. // Textures
  39213. if (scene.texturesEnabled) {
  39214. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39215. effect.setTexture("diffuseSampler", this._diffuseTexture);
  39216. }
  39217. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39218. effect.setTexture("ambientSampler", this._ambientTexture);
  39219. }
  39220. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39221. effect.setTexture("opacitySampler", this._opacityTexture);
  39222. }
  39223. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39224. if (this._reflectionTexture.isCube) {
  39225. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  39226. }
  39227. else {
  39228. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  39229. }
  39230. }
  39231. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39232. effect.setTexture("emissiveSampler", this._emissiveTexture);
  39233. }
  39234. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39235. effect.setTexture("lightmapSampler", this._lightmapTexture);
  39236. }
  39237. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39238. effect.setTexture("specularSampler", this._specularTexture);
  39239. }
  39240. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  39241. effect.setTexture("bumpSampler", this._bumpTexture);
  39242. }
  39243. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39244. var depth = 1.0;
  39245. if (this._refractionTexture.isCube) {
  39246. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  39247. }
  39248. else {
  39249. effect.setTexture("refraction2DSampler", this._refractionTexture);
  39250. }
  39251. }
  39252. }
  39253. // Clip plane
  39254. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  39255. // Colors
  39256. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  39257. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  39258. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  39259. }
  39260. if (mustRebind || !this.isFrozen) {
  39261. // Lights
  39262. if (scene.lightsEnabled && !this._disableLighting) {
  39263. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  39264. }
  39265. // View
  39266. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  39267. this.bindView(effect);
  39268. }
  39269. // Fog
  39270. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  39271. // Morph targets
  39272. if (defines.NUM_MORPH_INFLUENCERS) {
  39273. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  39274. }
  39275. // Log. depth
  39276. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  39277. // image processing
  39278. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  39279. this._imageProcessingConfiguration.bind(this._activeEffect);
  39280. }
  39281. }
  39282. this._uniformBuffer.update();
  39283. this._afterBind(mesh, this._activeEffect);
  39284. };
  39285. StandardMaterial.prototype.getAnimatables = function () {
  39286. var results = [];
  39287. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  39288. results.push(this._diffuseTexture);
  39289. }
  39290. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  39291. results.push(this._ambientTexture);
  39292. }
  39293. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  39294. results.push(this._opacityTexture);
  39295. }
  39296. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  39297. results.push(this._reflectionTexture);
  39298. }
  39299. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  39300. results.push(this._emissiveTexture);
  39301. }
  39302. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  39303. results.push(this._specularTexture);
  39304. }
  39305. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  39306. results.push(this._bumpTexture);
  39307. }
  39308. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  39309. results.push(this._lightmapTexture);
  39310. }
  39311. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  39312. results.push(this._refractionTexture);
  39313. }
  39314. return results;
  39315. };
  39316. StandardMaterial.prototype.getActiveTextures = function () {
  39317. var activeTextures = _super.prototype.getActiveTextures.call(this);
  39318. if (this._diffuseTexture) {
  39319. activeTextures.push(this._diffuseTexture);
  39320. }
  39321. if (this._ambientTexture) {
  39322. activeTextures.push(this._ambientTexture);
  39323. }
  39324. if (this._opacityTexture) {
  39325. activeTextures.push(this._opacityTexture);
  39326. }
  39327. if (this._reflectionTexture) {
  39328. activeTextures.push(this._reflectionTexture);
  39329. }
  39330. if (this._emissiveTexture) {
  39331. activeTextures.push(this._emissiveTexture);
  39332. }
  39333. if (this._specularTexture) {
  39334. activeTextures.push(this._specularTexture);
  39335. }
  39336. if (this._bumpTexture) {
  39337. activeTextures.push(this._bumpTexture);
  39338. }
  39339. if (this._lightmapTexture) {
  39340. activeTextures.push(this._lightmapTexture);
  39341. }
  39342. if (this._refractionTexture) {
  39343. activeTextures.push(this._refractionTexture);
  39344. }
  39345. return activeTextures;
  39346. };
  39347. StandardMaterial.prototype.hasTexture = function (texture) {
  39348. if (_super.prototype.hasTexture.call(this, texture)) {
  39349. return true;
  39350. }
  39351. if (this._diffuseTexture === texture) {
  39352. return true;
  39353. }
  39354. if (this._ambientTexture === texture) {
  39355. return true;
  39356. }
  39357. if (this._opacityTexture === texture) {
  39358. return true;
  39359. }
  39360. if (this._reflectionTexture === texture) {
  39361. return true;
  39362. }
  39363. if (this._emissiveTexture === texture) {
  39364. return true;
  39365. }
  39366. if (this._specularTexture === texture) {
  39367. return true;
  39368. }
  39369. if (this._bumpTexture === texture) {
  39370. return true;
  39371. }
  39372. if (this._lightmapTexture === texture) {
  39373. return true;
  39374. }
  39375. if (this._refractionTexture === texture) {
  39376. return true;
  39377. }
  39378. return false;
  39379. };
  39380. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39381. if (forceDisposeTextures) {
  39382. if (this._diffuseTexture) {
  39383. this._diffuseTexture.dispose();
  39384. }
  39385. if (this._ambientTexture) {
  39386. this._ambientTexture.dispose();
  39387. }
  39388. if (this._opacityTexture) {
  39389. this._opacityTexture.dispose();
  39390. }
  39391. if (this._reflectionTexture) {
  39392. this._reflectionTexture.dispose();
  39393. }
  39394. if (this._emissiveTexture) {
  39395. this._emissiveTexture.dispose();
  39396. }
  39397. if (this._specularTexture) {
  39398. this._specularTexture.dispose();
  39399. }
  39400. if (this._bumpTexture) {
  39401. this._bumpTexture.dispose();
  39402. }
  39403. if (this._lightmapTexture) {
  39404. this._lightmapTexture.dispose();
  39405. }
  39406. if (this._refractionTexture) {
  39407. this._refractionTexture.dispose();
  39408. }
  39409. }
  39410. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39411. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39412. }
  39413. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39414. };
  39415. StandardMaterial.prototype.clone = function (name) {
  39416. var _this = this;
  39417. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  39418. result.name = name;
  39419. result.id = name;
  39420. return result;
  39421. };
  39422. StandardMaterial.prototype.serialize = function () {
  39423. return BABYLON.SerializationHelper.Serialize(this);
  39424. };
  39425. // Statics
  39426. StandardMaterial.Parse = function (source, scene, rootUrl) {
  39427. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  39428. };
  39429. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  39430. get: function () {
  39431. return StandardMaterial._DiffuseTextureEnabled;
  39432. },
  39433. set: function (value) {
  39434. if (StandardMaterial._DiffuseTextureEnabled === value) {
  39435. return;
  39436. }
  39437. StandardMaterial._DiffuseTextureEnabled = value;
  39438. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39439. },
  39440. enumerable: true,
  39441. configurable: true
  39442. });
  39443. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  39444. get: function () {
  39445. return StandardMaterial._AmbientTextureEnabled;
  39446. },
  39447. set: function (value) {
  39448. if (StandardMaterial._AmbientTextureEnabled === value) {
  39449. return;
  39450. }
  39451. StandardMaterial._AmbientTextureEnabled = value;
  39452. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39453. },
  39454. enumerable: true,
  39455. configurable: true
  39456. });
  39457. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  39458. get: function () {
  39459. return StandardMaterial._OpacityTextureEnabled;
  39460. },
  39461. set: function (value) {
  39462. if (StandardMaterial._OpacityTextureEnabled === value) {
  39463. return;
  39464. }
  39465. StandardMaterial._OpacityTextureEnabled = value;
  39466. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39467. },
  39468. enumerable: true,
  39469. configurable: true
  39470. });
  39471. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  39472. get: function () {
  39473. return StandardMaterial._ReflectionTextureEnabled;
  39474. },
  39475. set: function (value) {
  39476. if (StandardMaterial._ReflectionTextureEnabled === value) {
  39477. return;
  39478. }
  39479. StandardMaterial._ReflectionTextureEnabled = value;
  39480. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39481. },
  39482. enumerable: true,
  39483. configurable: true
  39484. });
  39485. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  39486. get: function () {
  39487. return StandardMaterial._EmissiveTextureEnabled;
  39488. },
  39489. set: function (value) {
  39490. if (StandardMaterial._EmissiveTextureEnabled === value) {
  39491. return;
  39492. }
  39493. StandardMaterial._EmissiveTextureEnabled = value;
  39494. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39495. },
  39496. enumerable: true,
  39497. configurable: true
  39498. });
  39499. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  39500. get: function () {
  39501. return StandardMaterial._SpecularTextureEnabled;
  39502. },
  39503. set: function (value) {
  39504. if (StandardMaterial._SpecularTextureEnabled === value) {
  39505. return;
  39506. }
  39507. StandardMaterial._SpecularTextureEnabled = value;
  39508. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39509. },
  39510. enumerable: true,
  39511. configurable: true
  39512. });
  39513. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  39514. get: function () {
  39515. return StandardMaterial._BumpTextureEnabled;
  39516. },
  39517. set: function (value) {
  39518. if (StandardMaterial._BumpTextureEnabled === value) {
  39519. return;
  39520. }
  39521. StandardMaterial._BumpTextureEnabled = value;
  39522. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39523. },
  39524. enumerable: true,
  39525. configurable: true
  39526. });
  39527. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  39528. get: function () {
  39529. return StandardMaterial._LightmapTextureEnabled;
  39530. },
  39531. set: function (value) {
  39532. if (StandardMaterial._LightmapTextureEnabled === value) {
  39533. return;
  39534. }
  39535. StandardMaterial._LightmapTextureEnabled = value;
  39536. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39537. },
  39538. enumerable: true,
  39539. configurable: true
  39540. });
  39541. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  39542. get: function () {
  39543. return StandardMaterial._RefractionTextureEnabled;
  39544. },
  39545. set: function (value) {
  39546. if (StandardMaterial._RefractionTextureEnabled === value) {
  39547. return;
  39548. }
  39549. StandardMaterial._RefractionTextureEnabled = value;
  39550. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39551. },
  39552. enumerable: true,
  39553. configurable: true
  39554. });
  39555. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  39556. get: function () {
  39557. return StandardMaterial._ColorGradingTextureEnabled;
  39558. },
  39559. set: function (value) {
  39560. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  39561. return;
  39562. }
  39563. StandardMaterial._ColorGradingTextureEnabled = value;
  39564. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  39565. },
  39566. enumerable: true,
  39567. configurable: true
  39568. });
  39569. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  39570. get: function () {
  39571. return StandardMaterial._FresnelEnabled;
  39572. },
  39573. set: function (value) {
  39574. if (StandardMaterial._FresnelEnabled === value) {
  39575. return;
  39576. }
  39577. StandardMaterial._FresnelEnabled = value;
  39578. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  39579. },
  39580. enumerable: true,
  39581. configurable: true
  39582. });
  39583. // Flags used to enable or disable a type of texture for all Standard Materials
  39584. StandardMaterial._DiffuseTextureEnabled = true;
  39585. StandardMaterial._AmbientTextureEnabled = true;
  39586. StandardMaterial._OpacityTextureEnabled = true;
  39587. StandardMaterial._ReflectionTextureEnabled = true;
  39588. StandardMaterial._EmissiveTextureEnabled = true;
  39589. StandardMaterial._SpecularTextureEnabled = true;
  39590. StandardMaterial._BumpTextureEnabled = true;
  39591. StandardMaterial._LightmapTextureEnabled = true;
  39592. StandardMaterial._RefractionTextureEnabled = true;
  39593. StandardMaterial._ColorGradingTextureEnabled = true;
  39594. StandardMaterial._FresnelEnabled = true;
  39595. __decorate([
  39596. BABYLON.serializeAsTexture("diffuseTexture")
  39597. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  39598. __decorate([
  39599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39600. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  39601. __decorate([
  39602. BABYLON.serializeAsTexture("ambientTexture")
  39603. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  39604. __decorate([
  39605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39606. ], StandardMaterial.prototype, "ambientTexture", void 0);
  39607. __decorate([
  39608. BABYLON.serializeAsTexture("opacityTexture")
  39609. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  39610. __decorate([
  39611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  39612. ], StandardMaterial.prototype, "opacityTexture", void 0);
  39613. __decorate([
  39614. BABYLON.serializeAsTexture("reflectionTexture")
  39615. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  39616. __decorate([
  39617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39618. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  39619. __decorate([
  39620. BABYLON.serializeAsTexture("emissiveTexture")
  39621. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  39622. __decorate([
  39623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39624. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  39625. __decorate([
  39626. BABYLON.serializeAsTexture("specularTexture")
  39627. ], StandardMaterial.prototype, "_specularTexture", void 0);
  39628. __decorate([
  39629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39630. ], StandardMaterial.prototype, "specularTexture", void 0);
  39631. __decorate([
  39632. BABYLON.serializeAsTexture("bumpTexture")
  39633. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  39634. __decorate([
  39635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39636. ], StandardMaterial.prototype, "bumpTexture", void 0);
  39637. __decorate([
  39638. BABYLON.serializeAsTexture("lightmapTexture")
  39639. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  39640. __decorate([
  39641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39642. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  39643. __decorate([
  39644. BABYLON.serializeAsTexture("refractionTexture")
  39645. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  39646. __decorate([
  39647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39648. ], StandardMaterial.prototype, "refractionTexture", void 0);
  39649. __decorate([
  39650. BABYLON.serializeAsColor3("ambient")
  39651. ], StandardMaterial.prototype, "ambientColor", void 0);
  39652. __decorate([
  39653. BABYLON.serializeAsColor3("diffuse")
  39654. ], StandardMaterial.prototype, "diffuseColor", void 0);
  39655. __decorate([
  39656. BABYLON.serializeAsColor3("specular")
  39657. ], StandardMaterial.prototype, "specularColor", void 0);
  39658. __decorate([
  39659. BABYLON.serializeAsColor3("emissive")
  39660. ], StandardMaterial.prototype, "emissiveColor", void 0);
  39661. __decorate([
  39662. BABYLON.serialize()
  39663. ], StandardMaterial.prototype, "specularPower", void 0);
  39664. __decorate([
  39665. BABYLON.serialize("useAlphaFromDiffuseTexture")
  39666. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  39667. __decorate([
  39668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39669. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  39670. __decorate([
  39671. BABYLON.serialize("useEmissiveAsIllumination")
  39672. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  39673. __decorate([
  39674. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39675. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  39676. __decorate([
  39677. BABYLON.serialize("linkEmissiveWithDiffuse")
  39678. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  39679. __decorate([
  39680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39681. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  39682. __decorate([
  39683. BABYLON.serialize("useSpecularOverAlpha")
  39684. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  39685. __decorate([
  39686. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39687. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  39688. __decorate([
  39689. BABYLON.serialize("useReflectionOverAlpha")
  39690. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  39691. __decorate([
  39692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39693. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  39694. __decorate([
  39695. BABYLON.serialize("disableLighting")
  39696. ], StandardMaterial.prototype, "_disableLighting", void 0);
  39697. __decorate([
  39698. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39699. ], StandardMaterial.prototype, "disableLighting", void 0);
  39700. __decorate([
  39701. BABYLON.serialize("useObjectSpaceNormalMap")
  39702. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  39703. __decorate([
  39704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39705. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  39706. __decorate([
  39707. BABYLON.serialize("useParallax")
  39708. ], StandardMaterial.prototype, "_useParallax", void 0);
  39709. __decorate([
  39710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39711. ], StandardMaterial.prototype, "useParallax", void 0);
  39712. __decorate([
  39713. BABYLON.serialize("useParallaxOcclusion")
  39714. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  39715. __decorate([
  39716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39717. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  39718. __decorate([
  39719. BABYLON.serialize()
  39720. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  39721. __decorate([
  39722. BABYLON.serialize("roughness")
  39723. ], StandardMaterial.prototype, "_roughness", void 0);
  39724. __decorate([
  39725. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39726. ], StandardMaterial.prototype, "roughness", void 0);
  39727. __decorate([
  39728. BABYLON.serialize()
  39729. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  39730. __decorate([
  39731. BABYLON.serialize()
  39732. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  39733. __decorate([
  39734. BABYLON.serialize("useLightmapAsShadowmap")
  39735. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  39736. __decorate([
  39737. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39738. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  39739. __decorate([
  39740. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  39741. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  39742. __decorate([
  39743. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39744. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  39745. __decorate([
  39746. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  39747. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  39748. __decorate([
  39749. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  39750. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  39751. __decorate([
  39752. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  39753. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  39754. __decorate([
  39755. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39756. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  39757. __decorate([
  39758. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  39759. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  39760. __decorate([
  39761. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39762. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  39763. __decorate([
  39764. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  39765. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  39766. __decorate([
  39767. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39768. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  39769. __decorate([
  39770. BABYLON.serialize("useReflectionFresnelFromSpecular")
  39771. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  39772. __decorate([
  39773. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  39774. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  39775. __decorate([
  39776. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  39777. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  39778. __decorate([
  39779. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39780. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  39781. __decorate([
  39782. BABYLON.serialize("maxSimultaneousLights")
  39783. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  39784. __decorate([
  39785. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  39786. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  39787. __decorate([
  39788. BABYLON.serialize("invertNormalMapX")
  39789. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  39790. __decorate([
  39791. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39792. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  39793. __decorate([
  39794. BABYLON.serialize("invertNormalMapY")
  39795. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  39796. __decorate([
  39797. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39798. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  39799. __decorate([
  39800. BABYLON.serialize("twoSidedLighting")
  39801. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  39802. __decorate([
  39803. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  39804. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  39805. __decorate([
  39806. BABYLON.serialize()
  39807. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  39808. return StandardMaterial;
  39809. }(BABYLON.PushMaterial));
  39810. BABYLON.StandardMaterial = StandardMaterial;
  39811. })(BABYLON || (BABYLON = {}));
  39812. //# sourceMappingURL=babylon.standardMaterial.js.map
  39813. var BABYLON;
  39814. (function (BABYLON) {
  39815. /**
  39816. * Manages the defines for the PBR Material.
  39817. */
  39818. var PBRMaterialDefines = /** @class */ (function (_super) {
  39819. __extends(PBRMaterialDefines, _super);
  39820. /**
  39821. * Initializes the PBR Material defines.
  39822. */
  39823. function PBRMaterialDefines() {
  39824. var _this = _super.call(this) || this;
  39825. _this.PBR = true;
  39826. _this.MAINUV1 = false;
  39827. _this.MAINUV2 = false;
  39828. _this.UV1 = false;
  39829. _this.UV2 = false;
  39830. _this.ALBEDO = false;
  39831. _this.ALBEDODIRECTUV = 0;
  39832. _this.VERTEXCOLOR = false;
  39833. _this.AMBIENT = false;
  39834. _this.AMBIENTDIRECTUV = 0;
  39835. _this.AMBIENTINGRAYSCALE = false;
  39836. _this.OPACITY = false;
  39837. _this.VERTEXALPHA = false;
  39838. _this.OPACITYDIRECTUV = 0;
  39839. _this.OPACITYRGB = false;
  39840. _this.ALPHATEST = false;
  39841. _this.DEPTHPREPASS = false;
  39842. _this.ALPHABLEND = false;
  39843. _this.ALPHAFROMALBEDO = false;
  39844. _this.ALPHATESTVALUE = 0.5;
  39845. _this.SPECULAROVERALPHA = false;
  39846. _this.RADIANCEOVERALPHA = false;
  39847. _this.ALPHAFRESNEL = false;
  39848. _this.LINEARALPHAFRESNEL = false;
  39849. _this.PREMULTIPLYALPHA = false;
  39850. _this.EMISSIVE = false;
  39851. _this.EMISSIVEDIRECTUV = 0;
  39852. _this.REFLECTIVITY = false;
  39853. _this.REFLECTIVITYDIRECTUV = 0;
  39854. _this.SPECULARTERM = false;
  39855. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  39856. _this.MICROSURFACEAUTOMATIC = false;
  39857. _this.LODBASEDMICROSFURACE = false;
  39858. _this.MICROSURFACEMAP = false;
  39859. _this.MICROSURFACEMAPDIRECTUV = 0;
  39860. _this.METALLICWORKFLOW = false;
  39861. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  39862. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  39863. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  39864. _this.AOSTOREINMETALMAPRED = false;
  39865. _this.ENVIRONMENTBRDF = false;
  39866. _this.NORMAL = false;
  39867. _this.TANGENT = false;
  39868. _this.BUMP = false;
  39869. _this.BUMPDIRECTUV = 0;
  39870. _this.OBJECTSPACE_NORMALMAP = false;
  39871. _this.PARALLAX = false;
  39872. _this.PARALLAXOCCLUSION = false;
  39873. _this.NORMALXYSCALE = true;
  39874. _this.LIGHTMAP = false;
  39875. _this.LIGHTMAPDIRECTUV = 0;
  39876. _this.USELIGHTMAPASSHADOWMAP = false;
  39877. _this.REFLECTION = false;
  39878. _this.REFLECTIONMAP_3D = false;
  39879. _this.REFLECTIONMAP_SPHERICAL = false;
  39880. _this.REFLECTIONMAP_PLANAR = false;
  39881. _this.REFLECTIONMAP_CUBIC = false;
  39882. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39883. _this.REFLECTIONMAP_PROJECTION = false;
  39884. _this.REFLECTIONMAP_SKYBOX = false;
  39885. _this.REFLECTIONMAP_EXPLICIT = false;
  39886. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39887. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39888. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39889. _this.INVERTCUBICMAP = false;
  39890. _this.USESPHERICALFROMREFLECTIONMAP = false;
  39891. _this.USESPHERICALINVERTEX = false;
  39892. _this.REFLECTIONMAP_OPPOSITEZ = false;
  39893. _this.LODINREFLECTIONALPHA = false;
  39894. _this.GAMMAREFLECTION = false;
  39895. _this.RADIANCEOCCLUSION = false;
  39896. _this.HORIZONOCCLUSION = false;
  39897. _this.REFRACTION = false;
  39898. _this.REFRACTIONMAP_3D = false;
  39899. _this.REFRACTIONMAP_OPPOSITEZ = false;
  39900. _this.LODINREFRACTIONALPHA = false;
  39901. _this.GAMMAREFRACTION = false;
  39902. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  39903. _this.INSTANCES = false;
  39904. _this.NUM_BONE_INFLUENCERS = 0;
  39905. _this.BonesPerMesh = 0;
  39906. _this.NONUNIFORMSCALING = false;
  39907. _this.MORPHTARGETS = false;
  39908. _this.MORPHTARGETS_NORMAL = false;
  39909. _this.MORPHTARGETS_TANGENT = false;
  39910. _this.NUM_MORPH_INFLUENCERS = 0;
  39911. _this.IMAGEPROCESSING = false;
  39912. _this.VIGNETTE = false;
  39913. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39914. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39915. _this.TONEMAPPING = false;
  39916. _this.CONTRAST = false;
  39917. _this.COLORCURVES = false;
  39918. _this.COLORGRADING = false;
  39919. _this.COLORGRADING3D = false;
  39920. _this.SAMPLER3DGREENDEPTH = false;
  39921. _this.SAMPLER3DBGRMAP = false;
  39922. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39923. _this.EXPOSURE = false;
  39924. _this.USEPHYSICALLIGHTFALLOFF = false;
  39925. _this.TWOSIDEDLIGHTING = false;
  39926. _this.SHADOWFLOAT = false;
  39927. _this.CLIPPLANE = false;
  39928. _this.POINTSIZE = false;
  39929. _this.FOG = false;
  39930. _this.LOGARITHMICDEPTH = false;
  39931. _this.FORCENORMALFORWARD = false;
  39932. _this.rebuild();
  39933. return _this;
  39934. }
  39935. /**
  39936. * Resets the PBR Material defines.
  39937. */
  39938. PBRMaterialDefines.prototype.reset = function () {
  39939. _super.prototype.reset.call(this);
  39940. this.ALPHATESTVALUE = 0.5;
  39941. this.PBR = true;
  39942. };
  39943. return PBRMaterialDefines;
  39944. }(BABYLON.MaterialDefines));
  39945. /**
  39946. * The Physically based material base class of BJS.
  39947. *
  39948. * This offers the main features of a standard PBR material.
  39949. * For more information, please refer to the documentation :
  39950. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  39951. */
  39952. var PBRBaseMaterial = /** @class */ (function (_super) {
  39953. __extends(PBRBaseMaterial, _super);
  39954. /**
  39955. * Instantiates a new PBRMaterial instance.
  39956. *
  39957. * @param name The material name
  39958. * @param scene The scene the material will be use in.
  39959. */
  39960. function PBRBaseMaterial(name, scene) {
  39961. var _this = _super.call(this, name, scene) || this;
  39962. /**
  39963. * Intensity of the direct lights e.g. the four lights available in your scene.
  39964. * This impacts both the direct diffuse and specular highlights.
  39965. */
  39966. _this._directIntensity = 1.0;
  39967. /**
  39968. * Intensity of the emissive part of the material.
  39969. * This helps controlling the emissive effect without modifying the emissive color.
  39970. */
  39971. _this._emissiveIntensity = 1.0;
  39972. /**
  39973. * Intensity of the environment e.g. how much the environment will light the object
  39974. * either through harmonics for rough material or through the refelction for shiny ones.
  39975. */
  39976. _this._environmentIntensity = 1.0;
  39977. /**
  39978. * This is a special control allowing the reduction of the specular highlights coming from the
  39979. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  39980. */
  39981. _this._specularIntensity = 1.0;
  39982. /**
  39983. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  39984. */
  39985. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  39986. /**
  39987. * Debug Control allowing disabling the bump map on this material.
  39988. */
  39989. _this._disableBumpMap = false;
  39990. /**
  39991. * AKA Occlusion Texture Intensity in other nomenclature.
  39992. */
  39993. _this._ambientTextureStrength = 1.0;
  39994. /**
  39995. * The color of a material in ambient lighting.
  39996. */
  39997. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  39998. /**
  39999. * AKA Diffuse Color in other nomenclature.
  40000. */
  40001. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  40002. /**
  40003. * AKA Specular Color in other nomenclature.
  40004. */
  40005. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  40006. /**
  40007. * The color applied when light is reflected from a material.
  40008. */
  40009. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  40010. /**
  40011. * The color applied when light is emitted from a material.
  40012. */
  40013. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  40014. /**
  40015. * AKA Glossiness in other nomenclature.
  40016. */
  40017. _this._microSurface = 0.9;
  40018. /**
  40019. * source material index of refraction (IOR)' / 'destination material IOR.
  40020. */
  40021. _this._indexOfRefraction = 0.66;
  40022. /**
  40023. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  40024. */
  40025. _this._invertRefractionY = false;
  40026. /**
  40027. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  40028. * Materials half opaque for instance using refraction could benefit from this control.
  40029. */
  40030. _this._linkRefractionWithTransparency = false;
  40031. /**
  40032. * Specifies that the material will use the light map as a show map.
  40033. */
  40034. _this._useLightmapAsShadowmap = false;
  40035. /**
  40036. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  40037. * makes the reflect vector face the model (under horizon).
  40038. */
  40039. _this._useHorizonOcclusion = true;
  40040. /**
  40041. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  40042. * too much the area relying on ambient texture to define their ambient occlusion.
  40043. */
  40044. _this._useRadianceOcclusion = true;
  40045. /**
  40046. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  40047. */
  40048. _this._useAlphaFromAlbedoTexture = false;
  40049. /**
  40050. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  40051. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  40052. */
  40053. _this._useSpecularOverAlpha = true;
  40054. /**
  40055. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  40056. */
  40057. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  40058. /**
  40059. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  40060. */
  40061. _this._useRoughnessFromMetallicTextureAlpha = true;
  40062. /**
  40063. * Specifies if the metallic texture contains the roughness information in its green channel.
  40064. */
  40065. _this._useRoughnessFromMetallicTextureGreen = false;
  40066. /**
  40067. * Specifies if the metallic texture contains the metallness information in its blue channel.
  40068. */
  40069. _this._useMetallnessFromMetallicTextureBlue = false;
  40070. /**
  40071. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  40072. */
  40073. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  40074. /**
  40075. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  40076. */
  40077. _this._useAmbientInGrayScale = false;
  40078. /**
  40079. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  40080. * The material will try to infer what glossiness each pixel should be.
  40081. */
  40082. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  40083. /**
  40084. * BJS is using an harcoded light falloff based on a manually sets up range.
  40085. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  40086. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  40087. */
  40088. _this._usePhysicalLightFalloff = true;
  40089. /**
  40090. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  40091. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  40092. */
  40093. _this._useRadianceOverAlpha = true;
  40094. /**
  40095. * Allows using an object space normal map (instead of tangent space).
  40096. */
  40097. _this._useObjectSpaceNormalMap = false;
  40098. /**
  40099. * Allows using the bump map in parallax mode.
  40100. */
  40101. _this._useParallax = false;
  40102. /**
  40103. * Allows using the bump map in parallax occlusion mode.
  40104. */
  40105. _this._useParallaxOcclusion = false;
  40106. /**
  40107. * Controls the scale bias of the parallax mode.
  40108. */
  40109. _this._parallaxScaleBias = 0.05;
  40110. /**
  40111. * If sets to true, disables all the lights affecting the material.
  40112. */
  40113. _this._disableLighting = false;
  40114. /**
  40115. * Number of Simultaneous lights allowed on the material.
  40116. */
  40117. _this._maxSimultaneousLights = 4;
  40118. /**
  40119. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  40120. */
  40121. _this._invertNormalMapX = false;
  40122. /**
  40123. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  40124. */
  40125. _this._invertNormalMapY = false;
  40126. /**
  40127. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  40128. */
  40129. _this._twoSidedLighting = false;
  40130. /**
  40131. * Defines the alpha limits in alpha test mode.
  40132. */
  40133. _this._alphaCutOff = 0.4;
  40134. /**
  40135. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  40136. */
  40137. _this._forceAlphaTest = false;
  40138. /**
  40139. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40140. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  40141. */
  40142. _this._useAlphaFresnel = false;
  40143. /**
  40144. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  40145. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  40146. */
  40147. _this._useLinearAlphaFresnel = false;
  40148. /**
  40149. * The transparency mode of the material.
  40150. */
  40151. _this._transparencyMode = null;
  40152. /**
  40153. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  40154. * from cos thetav and roughness:
  40155. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  40156. */
  40157. _this._environmentBRDFTexture = null;
  40158. /**
  40159. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  40160. */
  40161. _this._forceIrradianceInFragment = false;
  40162. /**
  40163. * Force normal to face away from face.
  40164. */
  40165. _this._forceNormalForward = false;
  40166. /**
  40167. * Force metallic workflow.
  40168. */
  40169. _this._forceMetallicWorkflow = false;
  40170. /**
  40171. * Stores the available render targets.
  40172. */
  40173. _this._renderTargets = new BABYLON.SmartArray(16);
  40174. /**
  40175. * Sets the global ambient color for the material used in lighting calculations.
  40176. */
  40177. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  40178. // Setup the default processing configuration to the scene.
  40179. _this._attachImageProcessingConfiguration(null);
  40180. _this.getRenderTargetTextures = function () {
  40181. _this._renderTargets.reset();
  40182. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  40183. _this._renderTargets.push(_this._reflectionTexture);
  40184. }
  40185. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  40186. _this._renderTargets.push(_this._refractionTexture);
  40187. }
  40188. return _this._renderTargets;
  40189. };
  40190. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  40191. return _this;
  40192. }
  40193. /**
  40194. * Attaches a new image processing configuration to the PBR Material.
  40195. * @param configuration
  40196. */
  40197. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  40198. var _this = this;
  40199. if (configuration === this._imageProcessingConfiguration) {
  40200. return;
  40201. }
  40202. // Detaches observer.
  40203. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40204. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40205. }
  40206. // Pick the scene configuration if needed.
  40207. if (!configuration) {
  40208. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  40209. }
  40210. else {
  40211. this._imageProcessingConfiguration = configuration;
  40212. }
  40213. // Attaches observer.
  40214. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  40215. _this._markAllSubMeshesAsImageProcessingDirty();
  40216. });
  40217. };
  40218. /**
  40219. * Gets the name of the material class.
  40220. */
  40221. PBRBaseMaterial.prototype.getClassName = function () {
  40222. return "PBRBaseMaterial";
  40223. };
  40224. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  40225. /**
  40226. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40227. */
  40228. get: function () {
  40229. return this._useLogarithmicDepth;
  40230. },
  40231. /**
  40232. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  40233. */
  40234. set: function (value) {
  40235. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  40236. },
  40237. enumerable: true,
  40238. configurable: true
  40239. });
  40240. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  40241. /**
  40242. * Gets the current transparency mode.
  40243. */
  40244. get: function () {
  40245. return this._transparencyMode;
  40246. },
  40247. /**
  40248. * Sets the transparency mode of the material.
  40249. */
  40250. set: function (value) {
  40251. if (this._transparencyMode === value) {
  40252. return;
  40253. }
  40254. this._transparencyMode = value;
  40255. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  40256. this._markAllSubMeshesAsTexturesAndMiscDirty();
  40257. },
  40258. enumerable: true,
  40259. configurable: true
  40260. });
  40261. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  40262. /**
  40263. * Returns true if alpha blending should be disabled.
  40264. */
  40265. get: function () {
  40266. return (this._linkRefractionWithTransparency ||
  40267. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  40268. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40269. },
  40270. enumerable: true,
  40271. configurable: true
  40272. });
  40273. /**
  40274. * Specifies whether or not this material should be rendered in alpha blend mode.
  40275. */
  40276. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  40277. if (this._disableAlphaBlending) {
  40278. return false;
  40279. }
  40280. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  40281. };
  40282. /**
  40283. * Specifies if the mesh will require alpha blending.
  40284. * @param mesh - BJS mesh.
  40285. */
  40286. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  40287. if (this._disableAlphaBlending) {
  40288. return false;
  40289. }
  40290. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  40291. };
  40292. /**
  40293. * Specifies whether or not this material should be rendered in alpha test mode.
  40294. */
  40295. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  40296. if (this._forceAlphaTest) {
  40297. return true;
  40298. }
  40299. if (this._linkRefractionWithTransparency) {
  40300. return false;
  40301. }
  40302. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  40303. };
  40304. /**
  40305. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  40306. */
  40307. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  40308. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  40309. };
  40310. /**
  40311. * Gets the texture used for the alpha test.
  40312. */
  40313. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  40314. return this._albedoTexture;
  40315. };
  40316. /**
  40317. * Specifies that the submesh is ready to be used.
  40318. * @param mesh - BJS mesh.
  40319. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  40320. * @param useInstances - Specifies that instances should be used.
  40321. * @returns - boolean indicating that the submesh is ready or not.
  40322. */
  40323. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  40324. if (subMesh.effect && this.isFrozen) {
  40325. if (this._wasPreviouslyReady) {
  40326. return true;
  40327. }
  40328. }
  40329. if (!subMesh._materialDefines) {
  40330. subMesh._materialDefines = new PBRMaterialDefines();
  40331. }
  40332. var defines = subMesh._materialDefines;
  40333. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  40334. if (defines._renderId === this.getScene().getRenderId()) {
  40335. return true;
  40336. }
  40337. }
  40338. var scene = this.getScene();
  40339. var engine = scene.getEngine();
  40340. if (defines._areTexturesDirty) {
  40341. if (scene.texturesEnabled) {
  40342. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40343. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  40344. return false;
  40345. }
  40346. }
  40347. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40348. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  40349. return false;
  40350. }
  40351. }
  40352. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40353. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  40354. return false;
  40355. }
  40356. }
  40357. var reflectionTexture = this._getReflectionTexture();
  40358. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40359. if (!reflectionTexture.isReadyOrNotBlocking()) {
  40360. return false;
  40361. }
  40362. }
  40363. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40364. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  40365. return false;
  40366. }
  40367. }
  40368. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40369. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  40370. return false;
  40371. }
  40372. }
  40373. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40374. if (this._metallicTexture) {
  40375. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  40376. return false;
  40377. }
  40378. }
  40379. else if (this._reflectivityTexture) {
  40380. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  40381. return false;
  40382. }
  40383. }
  40384. if (this._microSurfaceTexture) {
  40385. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  40386. return false;
  40387. }
  40388. }
  40389. }
  40390. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40391. // Bump texture cannot be not blocking.
  40392. if (!this._bumpTexture.isReady()) {
  40393. return false;
  40394. }
  40395. }
  40396. var refractionTexture = this._getRefractionTexture();
  40397. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40398. if (!refractionTexture.isReadyOrNotBlocking()) {
  40399. return false;
  40400. }
  40401. }
  40402. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40403. // This is blocking.
  40404. if (!this._environmentBRDFTexture.isReady()) {
  40405. return false;
  40406. }
  40407. }
  40408. }
  40409. }
  40410. if (defines._areImageProcessingDirty) {
  40411. if (!this._imageProcessingConfiguration.isReady()) {
  40412. return false;
  40413. }
  40414. }
  40415. if (!engine.getCaps().standardDerivatives) {
  40416. var bufferMesh = null;
  40417. if (mesh.getClassName() === "InstancedMesh") {
  40418. bufferMesh = mesh.sourceMesh;
  40419. }
  40420. else if (mesh.getClassName() === "Mesh") {
  40421. bufferMesh = mesh;
  40422. }
  40423. if (bufferMesh && bufferMesh.geometry && bufferMesh.geometry.isReady() && !bufferMesh.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40424. bufferMesh.createNormals(true);
  40425. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + bufferMesh.name);
  40426. }
  40427. }
  40428. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  40429. if (effect) {
  40430. scene.resetCachedMaterial();
  40431. subMesh.setEffect(effect, defines);
  40432. this.buildUniformLayout();
  40433. }
  40434. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40435. return false;
  40436. }
  40437. defines._renderId = scene.getRenderId();
  40438. this._wasPreviouslyReady = true;
  40439. return true;
  40440. };
  40441. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  40442. if (onCompiled === void 0) { onCompiled = null; }
  40443. if (onError === void 0) { onError = null; }
  40444. if (useInstances === void 0) { useInstances = null; }
  40445. if (useClipPlane === void 0) { useClipPlane = null; }
  40446. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  40447. if (!defines.isDirty) {
  40448. return null;
  40449. }
  40450. defines.markAsProcessed();
  40451. var scene = this.getScene();
  40452. var engine = scene.getEngine();
  40453. // Fallbacks
  40454. var fallbacks = new BABYLON.EffectFallbacks();
  40455. var fallbackRank = 0;
  40456. if (defines.USESPHERICALINVERTEX) {
  40457. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  40458. }
  40459. if (defines.FOG) {
  40460. fallbacks.addFallback(fallbackRank, "FOG");
  40461. }
  40462. if (defines.POINTSIZE) {
  40463. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  40464. }
  40465. if (defines.LOGARITHMICDEPTH) {
  40466. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  40467. }
  40468. if (defines.PARALLAX) {
  40469. fallbacks.addFallback(fallbackRank, "PARALLAX");
  40470. }
  40471. if (defines.PARALLAXOCCLUSION) {
  40472. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  40473. }
  40474. if (defines.ENVIRONMENTBRDF) {
  40475. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  40476. }
  40477. if (defines.TANGENT) {
  40478. fallbacks.addFallback(fallbackRank++, "TANGENT");
  40479. }
  40480. if (defines.BUMP) {
  40481. fallbacks.addFallback(fallbackRank++, "BUMP");
  40482. }
  40483. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  40484. if (defines.SPECULARTERM) {
  40485. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  40486. }
  40487. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  40488. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  40489. }
  40490. if (defines.LIGHTMAP) {
  40491. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  40492. }
  40493. if (defines.NORMAL) {
  40494. fallbacks.addFallback(fallbackRank++, "NORMAL");
  40495. }
  40496. if (defines.AMBIENT) {
  40497. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  40498. }
  40499. if (defines.EMISSIVE) {
  40500. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  40501. }
  40502. if (defines.VERTEXCOLOR) {
  40503. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  40504. }
  40505. if (defines.NUM_BONE_INFLUENCERS > 0) {
  40506. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  40507. }
  40508. if (defines.MORPHTARGETS) {
  40509. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  40510. }
  40511. //Attributes
  40512. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40513. if (defines.NORMAL) {
  40514. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40515. }
  40516. if (defines.TANGENT) {
  40517. attribs.push(BABYLON.VertexBuffer.TangentKind);
  40518. }
  40519. if (defines.UV1) {
  40520. attribs.push(BABYLON.VertexBuffer.UVKind);
  40521. }
  40522. if (defines.UV2) {
  40523. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40524. }
  40525. if (defines.VERTEXCOLOR) {
  40526. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40527. }
  40528. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40529. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40530. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40531. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  40532. "vFogInfos", "vFogColor", "pointSize",
  40533. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  40534. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40535. "mBones",
  40536. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  40537. "vLightingIntensity",
  40538. "logarithmicDepthConstant",
  40539. "vSphericalX", "vSphericalY", "vSphericalZ",
  40540. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  40541. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  40542. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  40543. "vTangentSpaceParams"
  40544. ];
  40545. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  40546. "bumpSampler", "lightmapSampler", "opacitySampler",
  40547. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  40548. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  40549. "microSurfaceSampler", "environmentBrdfSampler"];
  40550. var uniformBuffers = ["Material", "Scene"];
  40551. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40552. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40553. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40554. uniformsNames: uniforms,
  40555. uniformBuffersNames: uniformBuffers,
  40556. samplers: samplers,
  40557. defines: defines,
  40558. maxSimultaneousLights: this._maxSimultaneousLights
  40559. });
  40560. var join = defines.toString();
  40561. return engine.createEffect("pbr", {
  40562. attributes: attribs,
  40563. uniformsNames: uniforms,
  40564. uniformBuffersNames: uniformBuffers,
  40565. samplers: samplers,
  40566. defines: join,
  40567. fallbacks: fallbacks,
  40568. onCompiled: onCompiled,
  40569. onError: onError,
  40570. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40571. }, engine);
  40572. };
  40573. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  40574. if (useInstances === void 0) { useInstances = null; }
  40575. if (useClipPlane === void 0) { useClipPlane = null; }
  40576. var scene = this.getScene();
  40577. var engine = scene.getEngine();
  40578. // Lights
  40579. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  40580. defines._needNormals = true;
  40581. // Textures
  40582. if (defines._areTexturesDirty) {
  40583. defines._needUVs = false;
  40584. if (scene.texturesEnabled) {
  40585. if (scene.getEngine().getCaps().textureLOD) {
  40586. defines.LODBASEDMICROSFURACE = true;
  40587. }
  40588. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40589. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  40590. }
  40591. else {
  40592. defines.ALBEDO = false;
  40593. }
  40594. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40595. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  40596. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  40597. }
  40598. else {
  40599. defines.AMBIENT = false;
  40600. }
  40601. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40602. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  40603. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  40604. }
  40605. else {
  40606. defines.OPACITY = false;
  40607. }
  40608. var reflectionTexture = this._getReflectionTexture();
  40609. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40610. defines.REFLECTION = true;
  40611. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  40612. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  40613. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  40614. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  40615. defines.INVERTCUBICMAP = true;
  40616. }
  40617. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  40618. switch (reflectionTexture.coordinatesMode) {
  40619. case BABYLON.Texture.CUBIC_MODE:
  40620. case BABYLON.Texture.INVCUBIC_MODE:
  40621. defines.REFLECTIONMAP_CUBIC = true;
  40622. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  40623. break;
  40624. case BABYLON.Texture.EXPLICIT_MODE:
  40625. defines.REFLECTIONMAP_EXPLICIT = true;
  40626. break;
  40627. case BABYLON.Texture.PLANAR_MODE:
  40628. defines.REFLECTIONMAP_PLANAR = true;
  40629. break;
  40630. case BABYLON.Texture.PROJECTION_MODE:
  40631. defines.REFLECTIONMAP_PROJECTION = true;
  40632. break;
  40633. case BABYLON.Texture.SKYBOX_MODE:
  40634. defines.REFLECTIONMAP_SKYBOX = true;
  40635. break;
  40636. case BABYLON.Texture.SPHERICAL_MODE:
  40637. defines.REFLECTIONMAP_SPHERICAL = true;
  40638. break;
  40639. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  40640. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  40641. break;
  40642. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  40643. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  40644. break;
  40645. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  40646. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  40647. break;
  40648. }
  40649. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  40650. if (reflectionTexture.sphericalPolynomial) {
  40651. defines.USESPHERICALFROMREFLECTIONMAP = true;
  40652. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  40653. defines.USESPHERICALINVERTEX = false;
  40654. }
  40655. else {
  40656. defines.USESPHERICALINVERTEX = true;
  40657. }
  40658. }
  40659. }
  40660. }
  40661. else {
  40662. defines.REFLECTION = false;
  40663. defines.REFLECTIONMAP_3D = false;
  40664. defines.REFLECTIONMAP_SPHERICAL = false;
  40665. defines.REFLECTIONMAP_PLANAR = false;
  40666. defines.REFLECTIONMAP_CUBIC = false;
  40667. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40668. defines.REFLECTIONMAP_PROJECTION = false;
  40669. defines.REFLECTIONMAP_SKYBOX = false;
  40670. defines.REFLECTIONMAP_EXPLICIT = false;
  40671. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40672. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40673. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40674. defines.INVERTCUBICMAP = false;
  40675. defines.USESPHERICALFROMREFLECTIONMAP = false;
  40676. defines.USESPHERICALINVERTEX = false;
  40677. defines.REFLECTIONMAP_OPPOSITEZ = false;
  40678. defines.LODINREFLECTIONALPHA = false;
  40679. defines.GAMMAREFLECTION = false;
  40680. }
  40681. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40682. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  40683. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  40684. }
  40685. else {
  40686. defines.LIGHTMAP = false;
  40687. }
  40688. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40689. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  40690. }
  40691. else {
  40692. defines.EMISSIVE = false;
  40693. }
  40694. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40695. if (this._metallicTexture) {
  40696. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  40697. defines.METALLICWORKFLOW = true;
  40698. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  40699. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  40700. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  40701. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  40702. }
  40703. else if (this._reflectivityTexture) {
  40704. defines.METALLICWORKFLOW = false;
  40705. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  40706. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  40707. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  40708. }
  40709. else {
  40710. defines.METALLICWORKFLOW = false;
  40711. defines.REFLECTIVITY = false;
  40712. }
  40713. if (this._microSurfaceTexture) {
  40714. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  40715. }
  40716. else {
  40717. defines.MICROSURFACEMAP = false;
  40718. }
  40719. }
  40720. else {
  40721. defines.REFLECTIVITY = false;
  40722. defines.MICROSURFACEMAP = false;
  40723. }
  40724. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40725. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  40726. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40727. defines.PARALLAX = true;
  40728. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  40729. }
  40730. else {
  40731. defines.PARALLAX = false;
  40732. }
  40733. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  40734. }
  40735. else {
  40736. defines.BUMP = false;
  40737. }
  40738. var refractionTexture = this._getRefractionTexture();
  40739. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40740. defines.REFRACTION = true;
  40741. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  40742. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  40743. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  40744. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  40745. if (this._linkRefractionWithTransparency) {
  40746. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  40747. }
  40748. }
  40749. else {
  40750. defines.REFRACTION = false;
  40751. }
  40752. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40753. defines.ENVIRONMENTBRDF = true;
  40754. }
  40755. else {
  40756. defines.ENVIRONMENTBRDF = false;
  40757. }
  40758. if (this._shouldUseAlphaFromAlbedoTexture()) {
  40759. defines.ALPHAFROMALBEDO = true;
  40760. }
  40761. else {
  40762. defines.ALPHAFROMALBEDO = false;
  40763. }
  40764. }
  40765. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  40766. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  40767. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  40768. if (this._forceMetallicWorkflow || (this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  40769. defines.METALLICWORKFLOW = true;
  40770. }
  40771. else {
  40772. defines.METALLICWORKFLOW = false;
  40773. }
  40774. if (!this.backFaceCulling && this._twoSidedLighting) {
  40775. defines.TWOSIDEDLIGHTING = true;
  40776. }
  40777. else {
  40778. defines.TWOSIDEDLIGHTING = false;
  40779. }
  40780. defines.ALPHATESTVALUE = this._alphaCutOff;
  40781. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  40782. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  40783. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  40784. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  40785. }
  40786. if (defines._areImageProcessingDirty) {
  40787. this._imageProcessingConfiguration.prepareDefines(defines);
  40788. }
  40789. defines.FORCENORMALFORWARD = this._forceNormalForward;
  40790. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  40791. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  40792. // Misc.
  40793. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  40794. // Values that need to be evaluated on every frame
  40795. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  40796. // Attribs
  40797. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  40798. };
  40799. /**
  40800. * Force shader compilation
  40801. */
  40802. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  40803. var _this = this;
  40804. var localOptions = __assign({ clipPlane: false }, options);
  40805. var defines = new PBRMaterialDefines();
  40806. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  40807. if (effect.isReady()) {
  40808. if (onCompiled) {
  40809. onCompiled(this);
  40810. }
  40811. }
  40812. else {
  40813. effect.onCompileObservable.add(function () {
  40814. if (onCompiled) {
  40815. onCompiled(_this);
  40816. }
  40817. });
  40818. }
  40819. };
  40820. /**
  40821. * Initializes the uniform buffer layout for the shader.
  40822. */
  40823. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  40824. // Order is important !
  40825. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  40826. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  40827. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40828. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40829. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40830. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  40831. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  40832. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40833. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40834. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40835. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40836. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40837. this._uniformBuffer.addUniform("albedoMatrix", 16);
  40838. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40839. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40840. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40841. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40842. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  40843. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  40844. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40845. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40846. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40847. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40848. this._uniformBuffer.addUniform("vReflectionColor", 3);
  40849. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  40850. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  40851. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  40852. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  40853. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  40854. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40855. this._uniformBuffer.addUniform("pointSize", 1);
  40856. this._uniformBuffer.create();
  40857. };
  40858. /**
  40859. * Unbinds the textures.
  40860. */
  40861. PBRBaseMaterial.prototype.unbind = function () {
  40862. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40863. this._uniformBuffer.setTexture("reflectionSampler", null);
  40864. }
  40865. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40866. this._uniformBuffer.setTexture("refractionSampler", null);
  40867. }
  40868. _super.prototype.unbind.call(this);
  40869. };
  40870. /**
  40871. * Binds the submesh data.
  40872. * @param world - The world matrix.
  40873. * @param mesh - The BJS mesh.
  40874. * @param subMesh - A submesh of the BJS mesh.
  40875. */
  40876. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40877. var scene = this.getScene();
  40878. var defines = subMesh._materialDefines;
  40879. if (!defines) {
  40880. return;
  40881. }
  40882. var effect = subMesh.effect;
  40883. if (!effect) {
  40884. return;
  40885. }
  40886. this._activeEffect = effect;
  40887. // Matrices
  40888. this.bindOnlyWorldMatrix(world);
  40889. // Normal Matrix
  40890. if (defines.OBJECTSPACE_NORMALMAP) {
  40891. world.toNormalMatrix(this._normalMatrix);
  40892. this.bindOnlyNormalMatrix(this._normalMatrix);
  40893. }
  40894. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40895. // Bones
  40896. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  40897. var reflectionTexture = null;
  40898. if (mustRebind) {
  40899. this._uniformBuffer.bindToEffect(effect, "Material");
  40900. this.bindViewProjection(effect);
  40901. reflectionTexture = this._getReflectionTexture();
  40902. var refractionTexture = this._getRefractionTexture();
  40903. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40904. // Texture uniforms
  40905. if (scene.texturesEnabled) {
  40906. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  40907. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  40908. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  40909. }
  40910. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  40911. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  40912. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40913. }
  40914. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  40915. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40916. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40917. }
  40918. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  40919. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  40920. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  40921. if (reflectionTexture.boundingBoxSize) {
  40922. var cubeTexture = reflectionTexture;
  40923. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40924. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40925. }
  40926. var polynomials = reflectionTexture.sphericalPolynomial;
  40927. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  40928. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  40929. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  40930. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  40931. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  40932. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  40933. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  40934. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  40935. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  40936. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  40937. }
  40938. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  40939. }
  40940. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  40941. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40942. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40943. }
  40944. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  40945. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40946. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40947. }
  40948. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  40949. if (this._metallicTexture) {
  40950. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  40951. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  40952. }
  40953. else if (this._reflectivityTexture) {
  40954. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  40955. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  40956. }
  40957. if (this._microSurfaceTexture) {
  40958. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  40959. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  40960. }
  40961. }
  40962. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  40963. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  40964. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40965. if (scene._mirroredCameraPosition) {
  40966. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40967. }
  40968. else {
  40969. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40970. }
  40971. }
  40972. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  40973. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  40974. var depth = 1.0;
  40975. if (!refractionTexture.isCube) {
  40976. if (refractionTexture.depth) {
  40977. depth = refractionTexture.depth;
  40978. }
  40979. }
  40980. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  40981. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  40982. }
  40983. }
  40984. // Point size
  40985. if (this.pointsCloud) {
  40986. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40987. }
  40988. // Colors
  40989. if (defines.METALLICWORKFLOW) {
  40990. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  40991. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  40992. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  40993. }
  40994. else {
  40995. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  40996. }
  40997. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  40998. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  40999. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  41000. // Misc
  41001. this._lightingInfos.x = this._directIntensity;
  41002. this._lightingInfos.y = this._emissiveIntensity;
  41003. this._lightingInfos.z = this._environmentIntensity;
  41004. this._lightingInfos.w = this._specularIntensity;
  41005. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  41006. }
  41007. // Textures
  41008. if (scene.texturesEnabled) {
  41009. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41010. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  41011. }
  41012. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41013. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  41014. }
  41015. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41016. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  41017. }
  41018. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41019. if (defines.LODBASEDMICROSFURACE) {
  41020. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  41021. }
  41022. else {
  41023. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  41024. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  41025. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  41026. }
  41027. }
  41028. if (defines.ENVIRONMENTBRDF) {
  41029. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  41030. }
  41031. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41032. if (defines.LODBASEDMICROSFURACE) {
  41033. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  41034. }
  41035. else {
  41036. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  41037. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  41038. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  41039. }
  41040. }
  41041. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41042. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  41043. }
  41044. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41045. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  41046. }
  41047. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41048. if (this._metallicTexture) {
  41049. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  41050. }
  41051. else if (this._reflectivityTexture) {
  41052. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  41053. }
  41054. if (this._microSurfaceTexture) {
  41055. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  41056. }
  41057. }
  41058. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41059. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  41060. }
  41061. }
  41062. // Clip plane
  41063. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  41064. // Colors
  41065. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  41066. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41067. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  41068. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  41069. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  41070. }
  41071. if (mustRebind || !this.isFrozen) {
  41072. // Lights
  41073. if (scene.lightsEnabled && !this._disableLighting) {
  41074. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  41075. }
  41076. // View
  41077. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  41078. this.bindView(effect);
  41079. }
  41080. // Fog
  41081. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  41082. // Morph targets
  41083. if (defines.NUM_MORPH_INFLUENCERS) {
  41084. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  41085. }
  41086. // image processing
  41087. this._imageProcessingConfiguration.bind(this._activeEffect);
  41088. // Log. depth
  41089. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  41090. }
  41091. this._uniformBuffer.update();
  41092. this._afterBind(mesh);
  41093. };
  41094. /**
  41095. * Returns the animatable textures.
  41096. * @returns - Array of animatable textures.
  41097. */
  41098. PBRBaseMaterial.prototype.getAnimatables = function () {
  41099. var results = [];
  41100. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  41101. results.push(this._albedoTexture);
  41102. }
  41103. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  41104. results.push(this._ambientTexture);
  41105. }
  41106. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  41107. results.push(this._opacityTexture);
  41108. }
  41109. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  41110. results.push(this._reflectionTexture);
  41111. }
  41112. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  41113. results.push(this._emissiveTexture);
  41114. }
  41115. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  41116. results.push(this._metallicTexture);
  41117. }
  41118. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  41119. results.push(this._reflectivityTexture);
  41120. }
  41121. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  41122. results.push(this._bumpTexture);
  41123. }
  41124. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  41125. results.push(this._lightmapTexture);
  41126. }
  41127. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  41128. results.push(this._refractionTexture);
  41129. }
  41130. return results;
  41131. };
  41132. /**
  41133. * Returns the texture used for reflections.
  41134. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  41135. */
  41136. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  41137. if (this._reflectionTexture) {
  41138. return this._reflectionTexture;
  41139. }
  41140. return this.getScene().environmentTexture;
  41141. };
  41142. /**
  41143. * Returns the texture used for refraction or null if none is used.
  41144. * @returns - Refection texture if present. If no refraction texture and refraction
  41145. * is linked with transparency, returns environment texture. Otherwise, returns null.
  41146. */
  41147. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  41148. if (this._refractionTexture) {
  41149. return this._refractionTexture;
  41150. }
  41151. if (this._linkRefractionWithTransparency) {
  41152. return this.getScene().environmentTexture;
  41153. }
  41154. return null;
  41155. };
  41156. /**
  41157. * Disposes the resources of the material.
  41158. * @param forceDisposeEffect - Forces the disposal of effects.
  41159. * @param forceDisposeTextures - Forces the disposal of all textures.
  41160. */
  41161. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41162. if (forceDisposeTextures) {
  41163. if (this._albedoTexture) {
  41164. this._albedoTexture.dispose();
  41165. }
  41166. if (this._ambientTexture) {
  41167. this._ambientTexture.dispose();
  41168. }
  41169. if (this._opacityTexture) {
  41170. this._opacityTexture.dispose();
  41171. }
  41172. if (this._reflectionTexture) {
  41173. this._reflectionTexture.dispose();
  41174. }
  41175. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  41176. this._environmentBRDFTexture.dispose();
  41177. }
  41178. if (this._emissiveTexture) {
  41179. this._emissiveTexture.dispose();
  41180. }
  41181. if (this._metallicTexture) {
  41182. this._metallicTexture.dispose();
  41183. }
  41184. if (this._reflectivityTexture) {
  41185. this._reflectivityTexture.dispose();
  41186. }
  41187. if (this._bumpTexture) {
  41188. this._bumpTexture.dispose();
  41189. }
  41190. if (this._lightmapTexture) {
  41191. this._lightmapTexture.dispose();
  41192. }
  41193. if (this._refractionTexture) {
  41194. this._refractionTexture.dispose();
  41195. }
  41196. }
  41197. this._renderTargets.dispose();
  41198. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41199. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41200. }
  41201. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41202. };
  41203. /**
  41204. * Stores the reflectivity values based on metallic roughness workflow.
  41205. */
  41206. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  41207. __decorate([
  41208. BABYLON.serializeAsImageProcessingConfiguration()
  41209. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  41210. __decorate([
  41211. BABYLON.serialize()
  41212. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  41213. __decorate([
  41214. BABYLON.serialize()
  41215. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  41216. return PBRBaseMaterial;
  41217. }(BABYLON.PushMaterial));
  41218. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  41219. })(BABYLON || (BABYLON = {}));
  41220. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  41221. var BABYLON;
  41222. (function (BABYLON) {
  41223. /**
  41224. * The Physically based simple base material of BJS.
  41225. *
  41226. * This enables better naming and convention enforcements on top of the pbrMaterial.
  41227. * It is used as the base class for both the specGloss and metalRough conventions.
  41228. */
  41229. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  41230. __extends(PBRBaseSimpleMaterial, _super);
  41231. /**
  41232. * Instantiates a new PBRMaterial instance.
  41233. *
  41234. * @param name The material name
  41235. * @param scene The scene the material will be use in.
  41236. */
  41237. function PBRBaseSimpleMaterial(name, scene) {
  41238. var _this = _super.call(this, name, scene) || this;
  41239. /**
  41240. * Number of Simultaneous lights allowed on the material.
  41241. */
  41242. _this.maxSimultaneousLights = 4;
  41243. /**
  41244. * If sets to true, disables all the lights affecting the material.
  41245. */
  41246. _this.disableLighting = false;
  41247. /**
  41248. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41249. */
  41250. _this.invertNormalMapX = false;
  41251. /**
  41252. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41253. */
  41254. _this.invertNormalMapY = false;
  41255. /**
  41256. * Emissivie color used to self-illuminate the model.
  41257. */
  41258. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41259. /**
  41260. * Occlusion Channel Strenght.
  41261. */
  41262. _this.occlusionStrength = 1.0;
  41263. _this.useLightmapAsShadowmap = false;
  41264. _this._useAlphaFromAlbedoTexture = true;
  41265. _this._useAmbientInGrayScale = true;
  41266. return _this;
  41267. }
  41268. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  41269. /**
  41270. * Gets the current double sided mode.
  41271. */
  41272. get: function () {
  41273. return this._twoSidedLighting;
  41274. },
  41275. /**
  41276. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41277. */
  41278. set: function (value) {
  41279. if (this._twoSidedLighting === value) {
  41280. return;
  41281. }
  41282. this._twoSidedLighting = value;
  41283. this.backFaceCulling = !value;
  41284. this._markAllSubMeshesAsTexturesDirty();
  41285. },
  41286. enumerable: true,
  41287. configurable: true
  41288. });
  41289. /**
  41290. * Return the active textures of the material.
  41291. */
  41292. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  41293. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41294. if (this.environmentTexture) {
  41295. activeTextures.push(this.environmentTexture);
  41296. }
  41297. if (this.normalTexture) {
  41298. activeTextures.push(this.normalTexture);
  41299. }
  41300. if (this.emissiveTexture) {
  41301. activeTextures.push(this.emissiveTexture);
  41302. }
  41303. if (this.occlusionTexture) {
  41304. activeTextures.push(this.occlusionTexture);
  41305. }
  41306. if (this.lightmapTexture) {
  41307. activeTextures.push(this.lightmapTexture);
  41308. }
  41309. return activeTextures;
  41310. };
  41311. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  41312. if (_super.prototype.hasTexture.call(this, texture)) {
  41313. return true;
  41314. }
  41315. if (this.lightmapTexture === texture) {
  41316. return true;
  41317. }
  41318. return false;
  41319. };
  41320. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  41321. return "PBRBaseSimpleMaterial";
  41322. };
  41323. __decorate([
  41324. BABYLON.serialize(),
  41325. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41326. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  41327. __decorate([
  41328. BABYLON.serialize(),
  41329. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  41330. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  41331. __decorate([
  41332. BABYLON.serializeAsTexture(),
  41333. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  41334. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  41335. __decorate([
  41336. BABYLON.serialize(),
  41337. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41338. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  41339. __decorate([
  41340. BABYLON.serialize(),
  41341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41342. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  41343. __decorate([
  41344. BABYLON.serializeAsTexture(),
  41345. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  41346. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  41347. __decorate([
  41348. BABYLON.serializeAsColor3("emissive"),
  41349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41350. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  41351. __decorate([
  41352. BABYLON.serializeAsTexture(),
  41353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41354. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  41355. __decorate([
  41356. BABYLON.serialize(),
  41357. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  41358. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  41359. __decorate([
  41360. BABYLON.serializeAsTexture(),
  41361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  41362. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  41363. __decorate([
  41364. BABYLON.serialize(),
  41365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  41366. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  41367. __decorate([
  41368. BABYLON.serialize()
  41369. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  41370. __decorate([
  41371. BABYLON.serializeAsTexture(),
  41372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41373. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  41374. __decorate([
  41375. BABYLON.serialize(),
  41376. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41377. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  41378. return PBRBaseSimpleMaterial;
  41379. }(BABYLON.PBRBaseMaterial));
  41380. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  41381. })(BABYLON || (BABYLON = {}));
  41382. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  41383. var BABYLON;
  41384. (function (BABYLON) {
  41385. /**
  41386. * The Physically based material of BJS.
  41387. *
  41388. * This offers the main features of a standard PBR material.
  41389. * For more information, please refer to the documentation :
  41390. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41391. */
  41392. var PBRMaterial = /** @class */ (function (_super) {
  41393. __extends(PBRMaterial, _super);
  41394. /**
  41395. * Instantiates a new PBRMaterial instance.
  41396. *
  41397. * @param name The material name
  41398. * @param scene The scene the material will be use in.
  41399. */
  41400. function PBRMaterial(name, scene) {
  41401. var _this = _super.call(this, name, scene) || this;
  41402. /**
  41403. * Intensity of the direct lights e.g. the four lights available in your scene.
  41404. * This impacts both the direct diffuse and specular highlights.
  41405. */
  41406. _this.directIntensity = 1.0;
  41407. /**
  41408. * Intensity of the emissive part of the material.
  41409. * This helps controlling the emissive effect without modifying the emissive color.
  41410. */
  41411. _this.emissiveIntensity = 1.0;
  41412. /**
  41413. * Intensity of the environment e.g. how much the environment will light the object
  41414. * either through harmonics for rough material or through the refelction for shiny ones.
  41415. */
  41416. _this.environmentIntensity = 1.0;
  41417. /**
  41418. * This is a special control allowing the reduction of the specular highlights coming from the
  41419. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41420. */
  41421. _this.specularIntensity = 1.0;
  41422. /**
  41423. * Debug Control allowing disabling the bump map on this material.
  41424. */
  41425. _this.disableBumpMap = false;
  41426. /**
  41427. * AKA Occlusion Texture Intensity in other nomenclature.
  41428. */
  41429. _this.ambientTextureStrength = 1.0;
  41430. /**
  41431. * The color of a material in ambient lighting.
  41432. */
  41433. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  41434. /**
  41435. * AKA Diffuse Color in other nomenclature.
  41436. */
  41437. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  41438. /**
  41439. * AKA Specular Color in other nomenclature.
  41440. */
  41441. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41442. /**
  41443. * The color reflected from the material.
  41444. */
  41445. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  41446. /**
  41447. * The color emitted from the material.
  41448. */
  41449. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  41450. /**
  41451. * AKA Glossiness in other nomenclature.
  41452. */
  41453. _this.microSurface = 1.0;
  41454. /**
  41455. * source material index of refraction (IOR)' / 'destination material IOR.
  41456. */
  41457. _this.indexOfRefraction = 0.66;
  41458. /**
  41459. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41460. */
  41461. _this.invertRefractionY = false;
  41462. /**
  41463. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41464. * Materials half opaque for instance using refraction could benefit from this control.
  41465. */
  41466. _this.linkRefractionWithTransparency = false;
  41467. _this.useLightmapAsShadowmap = false;
  41468. /**
  41469. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41470. */
  41471. _this.useAlphaFromAlbedoTexture = false;
  41472. /**
  41473. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41474. */
  41475. _this.forceAlphaTest = false;
  41476. /**
  41477. * Defines the alpha limits in alpha test mode.
  41478. */
  41479. _this.alphaCutOff = 0.4;
  41480. /**
  41481. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41482. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41483. */
  41484. _this.useSpecularOverAlpha = true;
  41485. /**
  41486. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41487. */
  41488. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  41489. /**
  41490. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41491. */
  41492. _this.useRoughnessFromMetallicTextureAlpha = true;
  41493. /**
  41494. * Specifies if the metallic texture contains the roughness information in its green channel.
  41495. */
  41496. _this.useRoughnessFromMetallicTextureGreen = false;
  41497. /**
  41498. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41499. */
  41500. _this.useMetallnessFromMetallicTextureBlue = false;
  41501. /**
  41502. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41503. */
  41504. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  41505. /**
  41506. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41507. */
  41508. _this.useAmbientInGrayScale = false;
  41509. /**
  41510. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41511. * The material will try to infer what glossiness each pixel should be.
  41512. */
  41513. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  41514. /**
  41515. * BJS is using an harcoded light falloff based on a manually sets up range.
  41516. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41517. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41518. */
  41519. _this.usePhysicalLightFalloff = true;
  41520. /**
  41521. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41522. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41523. */
  41524. _this.useRadianceOverAlpha = true;
  41525. /**
  41526. * Allows using an object space normal map (instead of tangent space).
  41527. */
  41528. _this.useObjectSpaceNormalMap = false;
  41529. /**
  41530. * Allows using the bump map in parallax mode.
  41531. */
  41532. _this.useParallax = false;
  41533. /**
  41534. * Allows using the bump map in parallax occlusion mode.
  41535. */
  41536. _this.useParallaxOcclusion = false;
  41537. /**
  41538. * Controls the scale bias of the parallax mode.
  41539. */
  41540. _this.parallaxScaleBias = 0.05;
  41541. /**
  41542. * If sets to true, disables all the lights affecting the material.
  41543. */
  41544. _this.disableLighting = false;
  41545. /**
  41546. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41547. */
  41548. _this.forceIrradianceInFragment = false;
  41549. /**
  41550. * Number of Simultaneous lights allowed on the material.
  41551. */
  41552. _this.maxSimultaneousLights = 4;
  41553. /**
  41554. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  41555. */
  41556. _this.invertNormalMapX = false;
  41557. /**
  41558. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  41559. */
  41560. _this.invertNormalMapY = false;
  41561. /**
  41562. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41563. */
  41564. _this.twoSidedLighting = false;
  41565. /**
  41566. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41567. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41568. */
  41569. _this.useAlphaFresnel = false;
  41570. /**
  41571. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41572. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41573. */
  41574. _this.useLinearAlphaFresnel = false;
  41575. /**
  41576. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41577. * And/Or occlude the blended part.
  41578. */
  41579. _this.environmentBRDFTexture = null;
  41580. /**
  41581. * Force normal to face away from face.
  41582. */
  41583. _this.forceNormalForward = false;
  41584. /**
  41585. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41586. * makes the reflect vector face the model (under horizon).
  41587. */
  41588. _this.useHorizonOcclusion = true;
  41589. /**
  41590. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41591. * too much the area relying on ambient texture to define their ambient occlusion.
  41592. */
  41593. _this.useRadianceOcclusion = true;
  41594. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41595. return _this;
  41596. }
  41597. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  41598. /**
  41599. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  41600. */
  41601. get: function () {
  41602. return this._PBRMATERIAL_OPAQUE;
  41603. },
  41604. enumerable: true,
  41605. configurable: true
  41606. });
  41607. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  41608. /**
  41609. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41610. */
  41611. get: function () {
  41612. return this._PBRMATERIAL_ALPHATEST;
  41613. },
  41614. enumerable: true,
  41615. configurable: true
  41616. });
  41617. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  41618. /**
  41619. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41620. */
  41621. get: function () {
  41622. return this._PBRMATERIAL_ALPHABLEND;
  41623. },
  41624. enumerable: true,
  41625. configurable: true
  41626. });
  41627. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  41628. /**
  41629. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41630. * They are also discarded below the alpha cutoff threshold to improve performances.
  41631. */
  41632. get: function () {
  41633. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  41634. },
  41635. enumerable: true,
  41636. configurable: true
  41637. });
  41638. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  41639. /**
  41640. * Gets the image processing configuration used either in this material.
  41641. */
  41642. get: function () {
  41643. return this._imageProcessingConfiguration;
  41644. },
  41645. /**
  41646. * Sets the Default image processing configuration used either in the this material.
  41647. *
  41648. * If sets to null, the scene one is in use.
  41649. */
  41650. set: function (value) {
  41651. this._attachImageProcessingConfiguration(value);
  41652. // Ensure the effect will be rebuilt.
  41653. this._markAllSubMeshesAsTexturesDirty();
  41654. },
  41655. enumerable: true,
  41656. configurable: true
  41657. });
  41658. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  41659. /**
  41660. * Gets wether the color curves effect is enabled.
  41661. */
  41662. get: function () {
  41663. return this.imageProcessingConfiguration.colorCurvesEnabled;
  41664. },
  41665. /**
  41666. * Sets wether the color curves effect is enabled.
  41667. */
  41668. set: function (value) {
  41669. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  41670. },
  41671. enumerable: true,
  41672. configurable: true
  41673. });
  41674. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  41675. /**
  41676. * Gets wether the color grading effect is enabled.
  41677. */
  41678. get: function () {
  41679. return this.imageProcessingConfiguration.colorGradingEnabled;
  41680. },
  41681. /**
  41682. * Gets wether the color grading effect is enabled.
  41683. */
  41684. set: function (value) {
  41685. this.imageProcessingConfiguration.colorGradingEnabled = value;
  41686. },
  41687. enumerable: true,
  41688. configurable: true
  41689. });
  41690. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  41691. /**
  41692. * Gets wether tonemapping is enabled or not.
  41693. */
  41694. get: function () {
  41695. return this._imageProcessingConfiguration.toneMappingEnabled;
  41696. },
  41697. /**
  41698. * Sets wether tonemapping is enabled or not
  41699. */
  41700. set: function (value) {
  41701. this._imageProcessingConfiguration.toneMappingEnabled = value;
  41702. },
  41703. enumerable: true,
  41704. configurable: true
  41705. });
  41706. ;
  41707. ;
  41708. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  41709. /**
  41710. * The camera exposure used on this material.
  41711. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41712. * This corresponds to a photographic exposure.
  41713. */
  41714. get: function () {
  41715. return this._imageProcessingConfiguration.exposure;
  41716. },
  41717. /**
  41718. * The camera exposure used on this material.
  41719. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  41720. * This corresponds to a photographic exposure.
  41721. */
  41722. set: function (value) {
  41723. this._imageProcessingConfiguration.exposure = value;
  41724. },
  41725. enumerable: true,
  41726. configurable: true
  41727. });
  41728. ;
  41729. ;
  41730. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  41731. /**
  41732. * Gets The camera contrast used on this material.
  41733. */
  41734. get: function () {
  41735. return this._imageProcessingConfiguration.contrast;
  41736. },
  41737. /**
  41738. * Sets The camera contrast used on this material.
  41739. */
  41740. set: function (value) {
  41741. this._imageProcessingConfiguration.contrast = value;
  41742. },
  41743. enumerable: true,
  41744. configurable: true
  41745. });
  41746. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  41747. /**
  41748. * Gets the Color Grading 2D Lookup Texture.
  41749. */
  41750. get: function () {
  41751. return this._imageProcessingConfiguration.colorGradingTexture;
  41752. },
  41753. /**
  41754. * Sets the Color Grading 2D Lookup Texture.
  41755. */
  41756. set: function (value) {
  41757. this._imageProcessingConfiguration.colorGradingTexture = value;
  41758. },
  41759. enumerable: true,
  41760. configurable: true
  41761. });
  41762. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  41763. /**
  41764. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41765. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41766. * 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;
  41767. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41768. */
  41769. get: function () {
  41770. return this._imageProcessingConfiguration.colorCurves;
  41771. },
  41772. /**
  41773. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41774. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41775. * 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;
  41776. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41777. */
  41778. set: function (value) {
  41779. this._imageProcessingConfiguration.colorCurves = value;
  41780. },
  41781. enumerable: true,
  41782. configurable: true
  41783. });
  41784. /**
  41785. * Returns the name of this material class.
  41786. */
  41787. PBRMaterial.prototype.getClassName = function () {
  41788. return "PBRMaterial";
  41789. };
  41790. /**
  41791. * Returns an array of the actively used textures.
  41792. * @returns - Array of BaseTextures
  41793. */
  41794. PBRMaterial.prototype.getActiveTextures = function () {
  41795. var activeTextures = _super.prototype.getActiveTextures.call(this);
  41796. if (this._albedoTexture) {
  41797. activeTextures.push(this._albedoTexture);
  41798. }
  41799. if (this._ambientTexture) {
  41800. activeTextures.push(this._ambientTexture);
  41801. }
  41802. if (this._opacityTexture) {
  41803. activeTextures.push(this._opacityTexture);
  41804. }
  41805. if (this._reflectionTexture) {
  41806. activeTextures.push(this._reflectionTexture);
  41807. }
  41808. if (this._emissiveTexture) {
  41809. activeTextures.push(this._emissiveTexture);
  41810. }
  41811. if (this._reflectivityTexture) {
  41812. activeTextures.push(this._reflectivityTexture);
  41813. }
  41814. if (this._metallicTexture) {
  41815. activeTextures.push(this._metallicTexture);
  41816. }
  41817. if (this._microSurfaceTexture) {
  41818. activeTextures.push(this._microSurfaceTexture);
  41819. }
  41820. if (this._bumpTexture) {
  41821. activeTextures.push(this._bumpTexture);
  41822. }
  41823. if (this._lightmapTexture) {
  41824. activeTextures.push(this._lightmapTexture);
  41825. }
  41826. if (this._refractionTexture) {
  41827. activeTextures.push(this._refractionTexture);
  41828. }
  41829. return activeTextures;
  41830. };
  41831. /**
  41832. * Checks to see if a texture is used in the material.
  41833. * @param texture - Base texture to use.
  41834. * @returns - Boolean specifying if a texture is used in the material.
  41835. */
  41836. PBRMaterial.prototype.hasTexture = function (texture) {
  41837. if (_super.prototype.hasTexture.call(this, texture)) {
  41838. return true;
  41839. }
  41840. if (this._albedoTexture === texture) {
  41841. return true;
  41842. }
  41843. if (this._ambientTexture === texture) {
  41844. return true;
  41845. }
  41846. if (this._opacityTexture === texture) {
  41847. return true;
  41848. }
  41849. if (this._reflectionTexture === texture) {
  41850. return true;
  41851. }
  41852. if (this._reflectivityTexture === texture) {
  41853. return true;
  41854. }
  41855. if (this._metallicTexture === texture) {
  41856. return true;
  41857. }
  41858. if (this._microSurfaceTexture === texture) {
  41859. return true;
  41860. }
  41861. if (this._bumpTexture === texture) {
  41862. return true;
  41863. }
  41864. if (this._lightmapTexture === texture) {
  41865. return true;
  41866. }
  41867. if (this._refractionTexture === texture) {
  41868. return true;
  41869. }
  41870. return false;
  41871. };
  41872. /**
  41873. * Makes a duplicate of the current material.
  41874. * @param name - name to use for the new material.
  41875. */
  41876. PBRMaterial.prototype.clone = function (name) {
  41877. var _this = this;
  41878. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  41879. clone.id = name;
  41880. clone.name = name;
  41881. return clone;
  41882. };
  41883. /**
  41884. * Serializes this PBR Material.
  41885. * @returns - An object with the serialized material.
  41886. */
  41887. PBRMaterial.prototype.serialize = function () {
  41888. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41889. serializationObject.customType = "BABYLON.PBRMaterial";
  41890. return serializationObject;
  41891. };
  41892. // Statics
  41893. /**
  41894. * Parses a PBR Material from a serialized object.
  41895. * @param source - Serialized object.
  41896. * @param scene - BJS scene instance.
  41897. * @param rootUrl - url for the scene object
  41898. * @returns - PBRMaterial
  41899. */
  41900. PBRMaterial.Parse = function (source, scene, rootUrl) {
  41901. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  41902. };
  41903. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  41904. /**
  41905. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  41906. */
  41907. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  41908. /**
  41909. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  41910. */
  41911. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  41912. /**
  41913. * 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.
  41914. * They are also discarded below the alpha cutoff threshold to improve performances.
  41915. */
  41916. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  41917. __decorate([
  41918. BABYLON.serialize(),
  41919. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41920. ], PBRMaterial.prototype, "directIntensity", void 0);
  41921. __decorate([
  41922. BABYLON.serialize(),
  41923. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41924. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  41925. __decorate([
  41926. BABYLON.serialize(),
  41927. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41928. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  41929. __decorate([
  41930. BABYLON.serialize(),
  41931. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41932. ], PBRMaterial.prototype, "specularIntensity", void 0);
  41933. __decorate([
  41934. BABYLON.serialize(),
  41935. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41936. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  41937. __decorate([
  41938. BABYLON.serializeAsTexture(),
  41939. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41940. ], PBRMaterial.prototype, "albedoTexture", void 0);
  41941. __decorate([
  41942. BABYLON.serializeAsTexture(),
  41943. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41944. ], PBRMaterial.prototype, "ambientTexture", void 0);
  41945. __decorate([
  41946. BABYLON.serialize(),
  41947. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41948. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  41949. __decorate([
  41950. BABYLON.serializeAsTexture(),
  41951. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  41952. ], PBRMaterial.prototype, "opacityTexture", void 0);
  41953. __decorate([
  41954. BABYLON.serializeAsTexture(),
  41955. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41956. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  41957. __decorate([
  41958. BABYLON.serializeAsTexture(),
  41959. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41960. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  41961. __decorate([
  41962. BABYLON.serializeAsTexture(),
  41963. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41964. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  41965. __decorate([
  41966. BABYLON.serializeAsTexture(),
  41967. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41968. ], PBRMaterial.prototype, "metallicTexture", void 0);
  41969. __decorate([
  41970. BABYLON.serialize(),
  41971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41972. ], PBRMaterial.prototype, "metallic", void 0);
  41973. __decorate([
  41974. BABYLON.serialize(),
  41975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41976. ], PBRMaterial.prototype, "roughness", void 0);
  41977. __decorate([
  41978. BABYLON.serializeAsTexture(),
  41979. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41980. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  41981. __decorate([
  41982. BABYLON.serializeAsTexture(),
  41983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41984. ], PBRMaterial.prototype, "bumpTexture", void 0);
  41985. __decorate([
  41986. BABYLON.serializeAsTexture(),
  41987. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  41988. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  41989. __decorate([
  41990. BABYLON.serializeAsTexture(),
  41991. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41992. ], PBRMaterial.prototype, "refractionTexture", void 0);
  41993. __decorate([
  41994. BABYLON.serializeAsColor3("ambient"),
  41995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  41996. ], PBRMaterial.prototype, "ambientColor", void 0);
  41997. __decorate([
  41998. BABYLON.serializeAsColor3("albedo"),
  41999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42000. ], PBRMaterial.prototype, "albedoColor", void 0);
  42001. __decorate([
  42002. BABYLON.serializeAsColor3("reflectivity"),
  42003. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42004. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  42005. __decorate([
  42006. BABYLON.serializeAsColor3("reflection"),
  42007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42008. ], PBRMaterial.prototype, "reflectionColor", void 0);
  42009. __decorate([
  42010. BABYLON.serializeAsColor3("emissive"),
  42011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42012. ], PBRMaterial.prototype, "emissiveColor", void 0);
  42013. __decorate([
  42014. BABYLON.serialize(),
  42015. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42016. ], PBRMaterial.prototype, "microSurface", void 0);
  42017. __decorate([
  42018. BABYLON.serialize(),
  42019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42020. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  42021. __decorate([
  42022. BABYLON.serialize(),
  42023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42024. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  42025. __decorate([
  42026. BABYLON.serialize(),
  42027. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42028. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  42029. __decorate([
  42030. BABYLON.serialize(),
  42031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42032. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42033. __decorate([
  42034. BABYLON.serialize(),
  42035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42036. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  42037. __decorate([
  42038. BABYLON.serialize(),
  42039. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42040. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  42041. __decorate([
  42042. BABYLON.serialize(),
  42043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  42044. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  42045. __decorate([
  42046. BABYLON.serialize(),
  42047. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42048. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  42049. __decorate([
  42050. BABYLON.serialize(),
  42051. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42052. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  42053. __decorate([
  42054. BABYLON.serialize(),
  42055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42056. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  42057. __decorate([
  42058. BABYLON.serialize(),
  42059. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42060. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  42061. __decorate([
  42062. BABYLON.serialize(),
  42063. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42064. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  42065. __decorate([
  42066. BABYLON.serialize(),
  42067. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42068. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  42069. __decorate([
  42070. BABYLON.serialize(),
  42071. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42072. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  42073. __decorate([
  42074. BABYLON.serialize(),
  42075. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42076. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  42077. __decorate([
  42078. BABYLON.serialize(),
  42079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42080. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  42081. __decorate([
  42082. BABYLON.serialize(),
  42083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42084. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  42085. __decorate([
  42086. BABYLON.serialize(),
  42087. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42088. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  42089. __decorate([
  42090. BABYLON.serialize(),
  42091. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42092. ], PBRMaterial.prototype, "useParallax", void 0);
  42093. __decorate([
  42094. BABYLON.serialize(),
  42095. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42096. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  42097. __decorate([
  42098. BABYLON.serialize(),
  42099. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42100. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  42101. __decorate([
  42102. BABYLON.serialize(),
  42103. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42104. ], PBRMaterial.prototype, "disableLighting", void 0);
  42105. __decorate([
  42106. BABYLON.serialize(),
  42107. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42108. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  42109. __decorate([
  42110. BABYLON.serialize(),
  42111. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42112. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  42113. __decorate([
  42114. BABYLON.serialize(),
  42115. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42116. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  42117. __decorate([
  42118. BABYLON.serialize(),
  42119. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42120. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  42121. __decorate([
  42122. BABYLON.serialize(),
  42123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42124. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  42125. __decorate([
  42126. BABYLON.serialize(),
  42127. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42128. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  42129. __decorate([
  42130. BABYLON.serialize(),
  42131. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42132. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  42133. __decorate([
  42134. BABYLON.serializeAsTexture(),
  42135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42136. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  42137. __decorate([
  42138. BABYLON.serialize(),
  42139. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42140. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  42141. __decorate([
  42142. BABYLON.serialize(),
  42143. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42144. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  42145. __decorate([
  42146. BABYLON.serialize(),
  42147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42148. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  42149. return PBRMaterial;
  42150. }(BABYLON.PBRBaseMaterial));
  42151. BABYLON.PBRMaterial = PBRMaterial;
  42152. })(BABYLON || (BABYLON = {}));
  42153. //# sourceMappingURL=babylon.pbrMaterial.js.map
  42154. var BABYLON;
  42155. (function (BABYLON) {
  42156. /**
  42157. * The PBR material of BJS following the metal roughness convention.
  42158. *
  42159. * This fits to the PBR convention in the GLTF definition:
  42160. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  42161. */
  42162. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  42163. __extends(PBRMetallicRoughnessMaterial, _super);
  42164. /**
  42165. * Instantiates a new PBRMetalRoughnessMaterial instance.
  42166. *
  42167. * @param name The material name
  42168. * @param scene The scene the material will be use in.
  42169. */
  42170. function PBRMetallicRoughnessMaterial(name, scene) {
  42171. var _this = _super.call(this, name, scene) || this;
  42172. _this._useRoughnessFromMetallicTextureAlpha = false;
  42173. _this._useRoughnessFromMetallicTextureGreen = true;
  42174. _this._useMetallnessFromMetallicTextureBlue = true;
  42175. _this._forceMetallicWorkflow = true;
  42176. return _this;
  42177. }
  42178. /**
  42179. * Return the currrent class name of the material.
  42180. */
  42181. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  42182. return "PBRMetallicRoughnessMaterial";
  42183. };
  42184. /**
  42185. * Return the active textures of the material.
  42186. */
  42187. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  42188. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42189. if (this.baseTexture) {
  42190. activeTextures.push(this.baseTexture);
  42191. }
  42192. if (this.metallicRoughnessTexture) {
  42193. activeTextures.push(this.metallicRoughnessTexture);
  42194. }
  42195. return activeTextures;
  42196. };
  42197. /**
  42198. * Checks to see if a texture is used in the material.
  42199. * @param texture - Base texture to use.
  42200. * @returns - Boolean specifying if a texture is used in the material.
  42201. */
  42202. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  42203. if (_super.prototype.hasTexture.call(this, texture)) {
  42204. return true;
  42205. }
  42206. if (this.baseTexture === texture) {
  42207. return true;
  42208. }
  42209. if (this.metallicRoughnessTexture === texture) {
  42210. return true;
  42211. }
  42212. return false;
  42213. };
  42214. /**
  42215. * Makes a duplicate of the current material.
  42216. * @param name - name to use for the new material.
  42217. */
  42218. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  42219. var _this = this;
  42220. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  42221. clone.id = name;
  42222. clone.name = name;
  42223. return clone;
  42224. };
  42225. /**
  42226. * Serialize the material to a parsable JSON object.
  42227. */
  42228. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  42229. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42230. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  42231. return serializationObject;
  42232. };
  42233. /**
  42234. * Parses a JSON object correponding to the serialize function.
  42235. */
  42236. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  42237. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  42238. };
  42239. __decorate([
  42240. BABYLON.serializeAsColor3(),
  42241. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42242. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  42243. __decorate([
  42244. BABYLON.serializeAsTexture(),
  42245. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42246. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  42247. __decorate([
  42248. BABYLON.serialize(),
  42249. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42250. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  42251. __decorate([
  42252. BABYLON.serialize(),
  42253. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42254. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  42255. __decorate([
  42256. BABYLON.serializeAsTexture(),
  42257. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  42258. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  42259. return PBRMetallicRoughnessMaterial;
  42260. }(BABYLON.PBRBaseSimpleMaterial));
  42261. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  42262. })(BABYLON || (BABYLON = {}));
  42263. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  42264. var BABYLON;
  42265. (function (BABYLON) {
  42266. /**
  42267. * The PBR material of BJS following the specular glossiness convention.
  42268. *
  42269. * This fits to the PBR convention in the GLTF definition:
  42270. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  42271. */
  42272. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  42273. __extends(PBRSpecularGlossinessMaterial, _super);
  42274. /**
  42275. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  42276. *
  42277. * @param name The material name
  42278. * @param scene The scene the material will be use in.
  42279. */
  42280. function PBRSpecularGlossinessMaterial(name, scene) {
  42281. var _this = _super.call(this, name, scene) || this;
  42282. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  42283. return _this;
  42284. }
  42285. /**
  42286. * Return the currrent class name of the material.
  42287. */
  42288. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  42289. return "PBRSpecularGlossinessMaterial";
  42290. };
  42291. /**
  42292. * Return the active textures of the material.
  42293. */
  42294. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  42295. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42296. if (this.diffuseTexture) {
  42297. activeTextures.push(this.diffuseTexture);
  42298. }
  42299. if (this.specularGlossinessTexture) {
  42300. activeTextures.push(this.specularGlossinessTexture);
  42301. }
  42302. return activeTextures;
  42303. };
  42304. /**
  42305. * Checks to see if a texture is used in the material.
  42306. * @param texture - Base texture to use.
  42307. * @returns - Boolean specifying if a texture is used in the material.
  42308. */
  42309. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  42310. if (_super.prototype.hasTexture.call(this, texture)) {
  42311. return true;
  42312. }
  42313. if (this.diffuseTexture === texture) {
  42314. return true;
  42315. }
  42316. if (this.specularGlossinessTexture === texture) {
  42317. return true;
  42318. }
  42319. return false;
  42320. };
  42321. /**
  42322. * Makes a duplicate of the current material.
  42323. * @param name - name to use for the new material.
  42324. */
  42325. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  42326. var _this = this;
  42327. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  42328. clone.id = name;
  42329. clone.name = name;
  42330. return clone;
  42331. };
  42332. /**
  42333. * Serialize the material to a parsable JSON object.
  42334. */
  42335. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  42336. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42337. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  42338. return serializationObject;
  42339. };
  42340. /**
  42341. * Parses a JSON object correponding to the serialize function.
  42342. */
  42343. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  42344. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  42345. };
  42346. __decorate([
  42347. BABYLON.serializeAsColor3("diffuse"),
  42348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  42349. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  42350. __decorate([
  42351. BABYLON.serializeAsTexture(),
  42352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  42353. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  42354. __decorate([
  42355. BABYLON.serializeAsColor3("specular"),
  42356. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  42357. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  42358. __decorate([
  42359. BABYLON.serialize(),
  42360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  42361. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  42362. __decorate([
  42363. BABYLON.serializeAsTexture(),
  42364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  42365. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  42366. return PBRSpecularGlossinessMaterial;
  42367. }(BABYLON.PBRBaseSimpleMaterial));
  42368. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  42369. })(BABYLON || (BABYLON = {}));
  42370. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  42371. var BABYLON;
  42372. (function (BABYLON) {
  42373. BABYLON.CameraInputTypes = {};
  42374. var CameraInputsManager = /** @class */ (function () {
  42375. function CameraInputsManager(camera) {
  42376. this.attached = {};
  42377. this.camera = camera;
  42378. this.checkInputs = function () { };
  42379. }
  42380. /**
  42381. * Add an input method to a camera.
  42382. * builtin inputs example: camera.inputs.addGamepad();
  42383. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  42384. * @param input camera input method
  42385. */
  42386. CameraInputsManager.prototype.add = function (input) {
  42387. var type = input.getSimpleName();
  42388. if (this.attached[type]) {
  42389. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  42390. return;
  42391. }
  42392. this.attached[type] = input;
  42393. input.camera = this.camera;
  42394. //for checkInputs, we are dynamically creating a function
  42395. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  42396. if (input.checkInputs) {
  42397. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42398. }
  42399. if (this.attachedElement) {
  42400. input.attachControl(this.attachedElement);
  42401. }
  42402. };
  42403. /**
  42404. * Remove a specific input method from a camera
  42405. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  42406. * @param inputToRemove camera input method
  42407. */
  42408. CameraInputsManager.prototype.remove = function (inputToRemove) {
  42409. for (var cam in this.attached) {
  42410. var input = this.attached[cam];
  42411. if (input === inputToRemove) {
  42412. input.detachControl(this.attachedElement);
  42413. input.camera = null;
  42414. delete this.attached[cam];
  42415. this.rebuildInputCheck();
  42416. }
  42417. }
  42418. };
  42419. CameraInputsManager.prototype.removeByType = function (inputType) {
  42420. for (var cam in this.attached) {
  42421. var input = this.attached[cam];
  42422. if (input.getClassName() === inputType) {
  42423. input.detachControl(this.attachedElement);
  42424. input.camera = null;
  42425. delete this.attached[cam];
  42426. this.rebuildInputCheck();
  42427. }
  42428. }
  42429. };
  42430. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  42431. var current = this.checkInputs;
  42432. return function () {
  42433. current();
  42434. fn();
  42435. };
  42436. };
  42437. CameraInputsManager.prototype.attachInput = function (input) {
  42438. if (this.attachedElement) {
  42439. input.attachControl(this.attachedElement, this.noPreventDefault);
  42440. }
  42441. };
  42442. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  42443. if (noPreventDefault === void 0) { noPreventDefault = false; }
  42444. if (this.attachedElement) {
  42445. return;
  42446. }
  42447. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  42448. this.attachedElement = element;
  42449. this.noPreventDefault = noPreventDefault;
  42450. for (var cam in this.attached) {
  42451. this.attached[cam].attachControl(element, noPreventDefault);
  42452. }
  42453. };
  42454. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  42455. if (disconnect === void 0) { disconnect = false; }
  42456. if (this.attachedElement !== element) {
  42457. return;
  42458. }
  42459. for (var cam in this.attached) {
  42460. this.attached[cam].detachControl(element);
  42461. if (disconnect) {
  42462. this.attached[cam].camera = null;
  42463. }
  42464. }
  42465. this.attachedElement = null;
  42466. };
  42467. CameraInputsManager.prototype.rebuildInputCheck = function () {
  42468. this.checkInputs = function () { };
  42469. for (var cam in this.attached) {
  42470. var input = this.attached[cam];
  42471. if (input.checkInputs) {
  42472. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  42473. }
  42474. }
  42475. };
  42476. /**
  42477. * Remove all attached input methods from a camera
  42478. */
  42479. CameraInputsManager.prototype.clear = function () {
  42480. if (this.attachedElement) {
  42481. this.detachElement(this.attachedElement, true);
  42482. }
  42483. this.attached = {};
  42484. this.attachedElement = null;
  42485. this.checkInputs = function () { };
  42486. };
  42487. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  42488. var inputs = {};
  42489. for (var cam in this.attached) {
  42490. var input = this.attached[cam];
  42491. var res = BABYLON.SerializationHelper.Serialize(input);
  42492. inputs[input.getClassName()] = res;
  42493. }
  42494. serializedCamera.inputsmgr = inputs;
  42495. };
  42496. CameraInputsManager.prototype.parse = function (parsedCamera) {
  42497. var parsedInputs = parsedCamera.inputsmgr;
  42498. if (parsedInputs) {
  42499. this.clear();
  42500. for (var n in parsedInputs) {
  42501. var construct = BABYLON.CameraInputTypes[n];
  42502. if (construct) {
  42503. var parsedinput = parsedInputs[n];
  42504. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  42505. this.add(input);
  42506. }
  42507. }
  42508. }
  42509. else {
  42510. //2016-03-08 this part is for managing backward compatibility
  42511. for (var n in this.attached) {
  42512. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  42513. if (construct) {
  42514. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  42515. this.remove(this.attached[n]);
  42516. this.add(input);
  42517. }
  42518. }
  42519. }
  42520. };
  42521. return CameraInputsManager;
  42522. }());
  42523. BABYLON.CameraInputsManager = CameraInputsManager;
  42524. })(BABYLON || (BABYLON = {}));
  42525. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  42526. var BABYLON;
  42527. (function (BABYLON) {
  42528. var TargetCamera = /** @class */ (function (_super) {
  42529. __extends(TargetCamera, _super);
  42530. function TargetCamera(name, position, scene) {
  42531. var _this = _super.call(this, name, position, scene) || this;
  42532. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  42533. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  42534. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  42535. _this.speed = 2.0;
  42536. _this.noRotationConstraint = false;
  42537. _this.lockedTarget = null;
  42538. _this._currentTarget = BABYLON.Vector3.Zero();
  42539. _this._viewMatrix = BABYLON.Matrix.Zero();
  42540. _this._camMatrix = BABYLON.Matrix.Zero();
  42541. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  42542. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  42543. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  42544. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  42545. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  42546. _this._lookAtTemp = BABYLON.Matrix.Zero();
  42547. _this._tempMatrix = BABYLON.Matrix.Zero();
  42548. return _this;
  42549. }
  42550. TargetCamera.prototype.getFrontPosition = function (distance) {
  42551. this.getWorldMatrix();
  42552. var direction = this.getTarget().subtract(this.position);
  42553. direction.normalize();
  42554. direction.scaleInPlace(distance);
  42555. return this.globalPosition.add(direction);
  42556. };
  42557. TargetCamera.prototype._getLockedTargetPosition = function () {
  42558. if (!this.lockedTarget) {
  42559. return null;
  42560. }
  42561. if (this.lockedTarget.absolutePosition) {
  42562. this.lockedTarget.computeWorldMatrix();
  42563. }
  42564. return this.lockedTarget.absolutePosition || this.lockedTarget;
  42565. };
  42566. TargetCamera.prototype.storeState = function () {
  42567. this._storedPosition = this.position.clone();
  42568. this._storedRotation = this.rotation.clone();
  42569. if (this.rotationQuaternion) {
  42570. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  42571. }
  42572. return _super.prototype.storeState.call(this);
  42573. };
  42574. /**
  42575. * Restored camera state. You must call storeState() first
  42576. */
  42577. TargetCamera.prototype._restoreStateValues = function () {
  42578. if (!_super.prototype._restoreStateValues.call(this)) {
  42579. return false;
  42580. }
  42581. this.position = this._storedPosition.clone();
  42582. this.rotation = this._storedRotation.clone();
  42583. if (this.rotationQuaternion) {
  42584. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  42585. }
  42586. this.cameraDirection.copyFromFloats(0, 0, 0);
  42587. this.cameraRotation.copyFromFloats(0, 0);
  42588. return true;
  42589. };
  42590. // Cache
  42591. TargetCamera.prototype._initCache = function () {
  42592. _super.prototype._initCache.call(this);
  42593. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42594. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42595. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  42596. };
  42597. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  42598. if (!ignoreParentClass) {
  42599. _super.prototype._updateCache.call(this);
  42600. }
  42601. var lockedTargetPosition = this._getLockedTargetPosition();
  42602. if (!lockedTargetPosition) {
  42603. this._cache.lockedTarget = null;
  42604. }
  42605. else {
  42606. if (!this._cache.lockedTarget) {
  42607. this._cache.lockedTarget = lockedTargetPosition.clone();
  42608. }
  42609. else {
  42610. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  42611. }
  42612. }
  42613. this._cache.rotation.copyFrom(this.rotation);
  42614. if (this.rotationQuaternion)
  42615. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42616. };
  42617. // Synchronized
  42618. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  42619. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  42620. return false;
  42621. }
  42622. var lockedTargetPosition = this._getLockedTargetPosition();
  42623. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  42624. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  42625. };
  42626. // Methods
  42627. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  42628. var engine = this.getEngine();
  42629. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  42630. };
  42631. // Target
  42632. TargetCamera.prototype.setTarget = function (target) {
  42633. this.upVector.normalize();
  42634. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  42635. this._camMatrix.invert();
  42636. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  42637. var vDir = target.subtract(this.position);
  42638. if (vDir.x >= 0.0) {
  42639. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  42640. }
  42641. else {
  42642. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  42643. }
  42644. this.rotation.z = 0;
  42645. if (isNaN(this.rotation.x)) {
  42646. this.rotation.x = 0;
  42647. }
  42648. if (isNaN(this.rotation.y)) {
  42649. this.rotation.y = 0;
  42650. }
  42651. if (isNaN(this.rotation.z)) {
  42652. this.rotation.z = 0;
  42653. }
  42654. if (this.rotationQuaternion) {
  42655. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42656. }
  42657. };
  42658. /**
  42659. * Return the current target position of the camera. This value is expressed in local space.
  42660. */
  42661. TargetCamera.prototype.getTarget = function () {
  42662. return this._currentTarget;
  42663. };
  42664. TargetCamera.prototype._decideIfNeedsToMove = function () {
  42665. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  42666. };
  42667. TargetCamera.prototype._updatePosition = function () {
  42668. if (this.parent) {
  42669. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  42670. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  42671. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  42672. return;
  42673. }
  42674. this.position.addInPlace(this.cameraDirection);
  42675. };
  42676. TargetCamera.prototype._checkInputs = function () {
  42677. var needToMove = this._decideIfNeedsToMove();
  42678. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  42679. // Move
  42680. if (needToMove) {
  42681. this._updatePosition();
  42682. }
  42683. // Rotate
  42684. if (needToRotate) {
  42685. this.rotation.x += this.cameraRotation.x;
  42686. this.rotation.y += this.cameraRotation.y;
  42687. //rotate, if quaternion is set and rotation was used
  42688. if (this.rotationQuaternion) {
  42689. var len = this.rotation.lengthSquared();
  42690. if (len) {
  42691. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  42692. }
  42693. }
  42694. if (!this.noRotationConstraint) {
  42695. var limit = (Math.PI / 2) * 0.95;
  42696. if (this.rotation.x > limit)
  42697. this.rotation.x = limit;
  42698. if (this.rotation.x < -limit)
  42699. this.rotation.x = -limit;
  42700. }
  42701. }
  42702. // Inertia
  42703. if (needToMove) {
  42704. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  42705. this.cameraDirection.x = 0;
  42706. }
  42707. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  42708. this.cameraDirection.y = 0;
  42709. }
  42710. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  42711. this.cameraDirection.z = 0;
  42712. }
  42713. this.cameraDirection.scaleInPlace(this.inertia);
  42714. }
  42715. if (needToRotate) {
  42716. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  42717. this.cameraRotation.x = 0;
  42718. }
  42719. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  42720. this.cameraRotation.y = 0;
  42721. }
  42722. this.cameraRotation.scaleInPlace(this.inertia);
  42723. }
  42724. _super.prototype._checkInputs.call(this);
  42725. };
  42726. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  42727. if (this.rotationQuaternion) {
  42728. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  42729. }
  42730. else {
  42731. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  42732. }
  42733. //update the up vector!
  42734. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  42735. };
  42736. TargetCamera.prototype._getViewMatrix = function () {
  42737. if (this.lockedTarget) {
  42738. this.setTarget(this._getLockedTargetPosition());
  42739. }
  42740. // Compute
  42741. this._updateCameraRotationMatrix();
  42742. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  42743. // Computing target and final matrix
  42744. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  42745. if (this.getScene().useRightHandedSystem) {
  42746. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42747. }
  42748. else {
  42749. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  42750. }
  42751. return this._viewMatrix;
  42752. };
  42753. /**
  42754. * @override
  42755. * Override Camera.createRigCamera
  42756. */
  42757. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  42758. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  42759. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  42760. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  42761. if (!this.rotationQuaternion) {
  42762. this.rotationQuaternion = new BABYLON.Quaternion();
  42763. }
  42764. rigCamera._cameraRigParams = {};
  42765. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  42766. }
  42767. return rigCamera;
  42768. }
  42769. return null;
  42770. };
  42771. /**
  42772. * @override
  42773. * Override Camera._updateRigCameras
  42774. */
  42775. TargetCamera.prototype._updateRigCameras = function () {
  42776. var camLeft = this._rigCameras[0];
  42777. var camRight = this._rigCameras[1];
  42778. switch (this.cameraRigMode) {
  42779. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  42780. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  42781. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  42782. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  42783. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  42784. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  42785. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  42786. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  42787. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  42788. camLeft.setTarget(this.getTarget());
  42789. camRight.setTarget(this.getTarget());
  42790. break;
  42791. case BABYLON.Camera.RIG_MODE_VR:
  42792. if (camLeft.rotationQuaternion) {
  42793. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42794. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  42795. }
  42796. else {
  42797. camLeft.rotation.copyFrom(this.rotation);
  42798. camRight.rotation.copyFrom(this.rotation);
  42799. }
  42800. camLeft.position.copyFrom(this.position);
  42801. camRight.position.copyFrom(this.position);
  42802. break;
  42803. }
  42804. _super.prototype._updateRigCameras.call(this);
  42805. };
  42806. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  42807. if (!this._rigCamTransformMatrix) {
  42808. this._rigCamTransformMatrix = new BABYLON.Matrix();
  42809. }
  42810. var target = this.getTarget();
  42811. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  42812. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  42813. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  42814. };
  42815. TargetCamera.prototype.getClassName = function () {
  42816. return "TargetCamera";
  42817. };
  42818. __decorate([
  42819. BABYLON.serializeAsVector3()
  42820. ], TargetCamera.prototype, "rotation", void 0);
  42821. __decorate([
  42822. BABYLON.serialize()
  42823. ], TargetCamera.prototype, "speed", void 0);
  42824. __decorate([
  42825. BABYLON.serializeAsMeshReference("lockedTargetId")
  42826. ], TargetCamera.prototype, "lockedTarget", void 0);
  42827. return TargetCamera;
  42828. }(BABYLON.Camera));
  42829. BABYLON.TargetCamera = TargetCamera;
  42830. })(BABYLON || (BABYLON = {}));
  42831. //# sourceMappingURL=babylon.targetCamera.js.map
  42832. var BABYLON;
  42833. (function (BABYLON) {
  42834. var FreeCameraMouseInput = /** @class */ (function () {
  42835. function FreeCameraMouseInput(touchEnabled) {
  42836. if (touchEnabled === void 0) { touchEnabled = true; }
  42837. this.touchEnabled = touchEnabled;
  42838. this.buttons = [0, 1, 2];
  42839. this.angularSensibility = 2000.0;
  42840. this.previousPosition = null;
  42841. }
  42842. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  42843. var _this = this;
  42844. var engine = this.camera.getEngine();
  42845. if (!this._pointerInput) {
  42846. this._pointerInput = function (p, s) {
  42847. var evt = p.event;
  42848. if (engine.isInVRExclusivePointerMode) {
  42849. return;
  42850. }
  42851. if (!_this.touchEnabled && evt.pointerType === "touch") {
  42852. return;
  42853. }
  42854. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  42855. return;
  42856. }
  42857. var srcElement = (evt.srcElement || evt.target);
  42858. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  42859. try {
  42860. srcElement.setPointerCapture(evt.pointerId);
  42861. }
  42862. catch (e) {
  42863. //Nothing to do with the error. Execution will continue.
  42864. }
  42865. _this.previousPosition = {
  42866. x: evt.clientX,
  42867. y: evt.clientY
  42868. };
  42869. if (!noPreventDefault) {
  42870. evt.preventDefault();
  42871. element.focus();
  42872. }
  42873. }
  42874. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  42875. try {
  42876. srcElement.releasePointerCapture(evt.pointerId);
  42877. }
  42878. catch (e) {
  42879. //Nothing to do with the error.
  42880. }
  42881. _this.previousPosition = null;
  42882. if (!noPreventDefault) {
  42883. evt.preventDefault();
  42884. }
  42885. }
  42886. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  42887. if (!_this.previousPosition || engine.isPointerLock) {
  42888. return;
  42889. }
  42890. var offsetX = evt.clientX - _this.previousPosition.x;
  42891. var offsetY = evt.clientY - _this.previousPosition.y;
  42892. if (_this.camera.getScene().useRightHandedSystem) {
  42893. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42894. }
  42895. else {
  42896. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42897. }
  42898. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42899. _this.previousPosition = {
  42900. x: evt.clientX,
  42901. y: evt.clientY
  42902. };
  42903. if (!noPreventDefault) {
  42904. evt.preventDefault();
  42905. }
  42906. }
  42907. };
  42908. }
  42909. this._onMouseMove = function (evt) {
  42910. if (!engine.isPointerLock) {
  42911. return;
  42912. }
  42913. if (engine.isInVRExclusivePointerMode) {
  42914. return;
  42915. }
  42916. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  42917. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  42918. if (_this.camera.getScene().useRightHandedSystem) {
  42919. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  42920. }
  42921. else {
  42922. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  42923. }
  42924. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  42925. _this.previousPosition = null;
  42926. if (!noPreventDefault) {
  42927. evt.preventDefault();
  42928. }
  42929. };
  42930. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  42931. element.addEventListener("mousemove", this._onMouseMove, false);
  42932. };
  42933. FreeCameraMouseInput.prototype.detachControl = function (element) {
  42934. if (this._observer && element) {
  42935. this.camera.getScene().onPointerObservable.remove(this._observer);
  42936. if (this._onMouseMove) {
  42937. element.removeEventListener("mousemove", this._onMouseMove);
  42938. }
  42939. this._observer = null;
  42940. this._onMouseMove = null;
  42941. this.previousPosition = null;
  42942. }
  42943. };
  42944. FreeCameraMouseInput.prototype.getClassName = function () {
  42945. return "FreeCameraMouseInput";
  42946. };
  42947. FreeCameraMouseInput.prototype.getSimpleName = function () {
  42948. return "mouse";
  42949. };
  42950. __decorate([
  42951. BABYLON.serialize()
  42952. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  42953. __decorate([
  42954. BABYLON.serialize()
  42955. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  42956. return FreeCameraMouseInput;
  42957. }());
  42958. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  42959. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  42960. })(BABYLON || (BABYLON = {}));
  42961. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  42962. var BABYLON;
  42963. (function (BABYLON) {
  42964. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  42965. function FreeCameraKeyboardMoveInput() {
  42966. this._keys = new Array();
  42967. this.keysUp = [38];
  42968. this.keysDown = [40];
  42969. this.keysLeft = [37];
  42970. this.keysRight = [39];
  42971. }
  42972. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  42973. var _this = this;
  42974. if (this._onCanvasBlurObserver) {
  42975. return;
  42976. }
  42977. this._scene = this.camera.getScene();
  42978. this._engine = this._scene.getEngine();
  42979. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  42980. _this._keys = [];
  42981. });
  42982. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  42983. var evt = info.event;
  42984. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  42985. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  42986. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  42987. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  42988. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  42989. var index = _this._keys.indexOf(evt.keyCode);
  42990. if (index === -1) {
  42991. _this._keys.push(evt.keyCode);
  42992. }
  42993. if (!noPreventDefault) {
  42994. evt.preventDefault();
  42995. }
  42996. }
  42997. }
  42998. else {
  42999. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43000. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43001. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43002. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  43003. var index = _this._keys.indexOf(evt.keyCode);
  43004. if (index >= 0) {
  43005. _this._keys.splice(index, 1);
  43006. }
  43007. if (!noPreventDefault) {
  43008. evt.preventDefault();
  43009. }
  43010. }
  43011. }
  43012. });
  43013. };
  43014. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43015. if (this._scene) {
  43016. if (this._onKeyboardObserver) {
  43017. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43018. }
  43019. if (this._onCanvasBlurObserver) {
  43020. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43021. }
  43022. this._onKeyboardObserver = null;
  43023. this._onCanvasBlurObserver = null;
  43024. }
  43025. this._keys = [];
  43026. };
  43027. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43028. if (this._onKeyboardObserver) {
  43029. var camera = this.camera;
  43030. // Keyboard
  43031. for (var index = 0; index < this._keys.length; index++) {
  43032. var keyCode = this._keys[index];
  43033. var speed = camera._computeLocalCameraSpeed();
  43034. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43035. camera._localDirection.copyFromFloats(-speed, 0, 0);
  43036. }
  43037. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43038. camera._localDirection.copyFromFloats(0, 0, speed);
  43039. }
  43040. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43041. camera._localDirection.copyFromFloats(speed, 0, 0);
  43042. }
  43043. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43044. camera._localDirection.copyFromFloats(0, 0, -speed);
  43045. }
  43046. if (camera.getScene().useRightHandedSystem) {
  43047. camera._localDirection.z *= -1;
  43048. }
  43049. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  43050. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  43051. camera.cameraDirection.addInPlace(camera._transformedDirection);
  43052. }
  43053. }
  43054. };
  43055. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  43056. return "FreeCameraKeyboardMoveInput";
  43057. };
  43058. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  43059. this._keys = [];
  43060. };
  43061. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43062. return "keyboard";
  43063. };
  43064. __decorate([
  43065. BABYLON.serialize()
  43066. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43067. __decorate([
  43068. BABYLON.serialize()
  43069. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43070. __decorate([
  43071. BABYLON.serialize()
  43072. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43073. __decorate([
  43074. BABYLON.serialize()
  43075. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43076. return FreeCameraKeyboardMoveInput;
  43077. }());
  43078. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  43079. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  43080. })(BABYLON || (BABYLON = {}));
  43081. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  43082. var BABYLON;
  43083. (function (BABYLON) {
  43084. var FreeCameraInputsManager = /** @class */ (function (_super) {
  43085. __extends(FreeCameraInputsManager, _super);
  43086. function FreeCameraInputsManager(camera) {
  43087. return _super.call(this, camera) || this;
  43088. }
  43089. FreeCameraInputsManager.prototype.addKeyboard = function () {
  43090. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  43091. return this;
  43092. };
  43093. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  43094. if (touchEnabled === void 0) { touchEnabled = true; }
  43095. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  43096. return this;
  43097. };
  43098. FreeCameraInputsManager.prototype.addGamepad = function () {
  43099. this.add(new BABYLON.FreeCameraGamepadInput());
  43100. return this;
  43101. };
  43102. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  43103. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  43104. return this;
  43105. };
  43106. FreeCameraInputsManager.prototype.addTouch = function () {
  43107. this.add(new BABYLON.FreeCameraTouchInput());
  43108. return this;
  43109. };
  43110. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  43111. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  43112. return this;
  43113. };
  43114. return FreeCameraInputsManager;
  43115. }(BABYLON.CameraInputsManager));
  43116. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  43117. })(BABYLON || (BABYLON = {}));
  43118. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  43119. var BABYLON;
  43120. (function (BABYLON) {
  43121. var FreeCamera = /** @class */ (function (_super) {
  43122. __extends(FreeCamera, _super);
  43123. function FreeCamera(name, position, scene) {
  43124. var _this = _super.call(this, name, position, scene) || this;
  43125. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  43126. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  43127. _this.checkCollisions = false;
  43128. _this.applyGravity = false;
  43129. _this._needMoveForGravity = false;
  43130. _this._oldPosition = BABYLON.Vector3.Zero();
  43131. _this._diffPosition = BABYLON.Vector3.Zero();
  43132. _this._newPosition = BABYLON.Vector3.Zero();
  43133. // Collisions
  43134. _this._collisionMask = -1;
  43135. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43136. if (collidedMesh === void 0) { collidedMesh = null; }
  43137. //TODO move this to the collision coordinator!
  43138. if (_this.getScene().workerCollisions)
  43139. newPosition.multiplyInPlace(_this._collider._radius);
  43140. var updatePosition = function (newPos) {
  43141. _this._newPosition.copyFrom(newPos);
  43142. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  43143. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  43144. _this.position.addInPlace(_this._diffPosition);
  43145. if (_this.onCollide && collidedMesh) {
  43146. _this.onCollide(collidedMesh);
  43147. }
  43148. }
  43149. };
  43150. updatePosition(newPosition);
  43151. };
  43152. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  43153. _this.inputs.addKeyboard().addMouse();
  43154. return _this;
  43155. }
  43156. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  43157. //-- begin properties for backward compatibility for inputs
  43158. /**
  43159. * Gets the input sensibility for a mouse input. (default is 2000.0)
  43160. * Higher values reduce sensitivity.
  43161. */
  43162. get: function () {
  43163. var mouse = this.inputs.attached["mouse"];
  43164. if (mouse)
  43165. return mouse.angularSensibility;
  43166. return 0;
  43167. },
  43168. /**
  43169. * Sets the input sensibility for a mouse input. (default is 2000.0)
  43170. * Higher values reduce sensitivity.
  43171. */
  43172. set: function (value) {
  43173. var mouse = this.inputs.attached["mouse"];
  43174. if (mouse)
  43175. mouse.angularSensibility = value;
  43176. },
  43177. enumerable: true,
  43178. configurable: true
  43179. });
  43180. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  43181. get: function () {
  43182. var keyboard = this.inputs.attached["keyboard"];
  43183. if (keyboard)
  43184. return keyboard.keysUp;
  43185. return [];
  43186. },
  43187. set: function (value) {
  43188. var keyboard = this.inputs.attached["keyboard"];
  43189. if (keyboard)
  43190. keyboard.keysUp = value;
  43191. },
  43192. enumerable: true,
  43193. configurable: true
  43194. });
  43195. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  43196. get: function () {
  43197. var keyboard = this.inputs.attached["keyboard"];
  43198. if (keyboard)
  43199. return keyboard.keysDown;
  43200. return [];
  43201. },
  43202. set: function (value) {
  43203. var keyboard = this.inputs.attached["keyboard"];
  43204. if (keyboard)
  43205. keyboard.keysDown = value;
  43206. },
  43207. enumerable: true,
  43208. configurable: true
  43209. });
  43210. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  43211. get: function () {
  43212. var keyboard = this.inputs.attached["keyboard"];
  43213. if (keyboard)
  43214. return keyboard.keysLeft;
  43215. return [];
  43216. },
  43217. set: function (value) {
  43218. var keyboard = this.inputs.attached["keyboard"];
  43219. if (keyboard)
  43220. keyboard.keysLeft = value;
  43221. },
  43222. enumerable: true,
  43223. configurable: true
  43224. });
  43225. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  43226. get: function () {
  43227. var keyboard = this.inputs.attached["keyboard"];
  43228. if (keyboard)
  43229. return keyboard.keysRight;
  43230. return [];
  43231. },
  43232. set: function (value) {
  43233. var keyboard = this.inputs.attached["keyboard"];
  43234. if (keyboard)
  43235. keyboard.keysRight = value;
  43236. },
  43237. enumerable: true,
  43238. configurable: true
  43239. });
  43240. // Controls
  43241. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43242. this.inputs.attachElement(element, noPreventDefault);
  43243. };
  43244. FreeCamera.prototype.detachControl = function (element) {
  43245. this.inputs.detachElement(element);
  43246. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43247. this.cameraRotation = new BABYLON.Vector2(0, 0);
  43248. };
  43249. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  43250. get: function () {
  43251. return this._collisionMask;
  43252. },
  43253. set: function (mask) {
  43254. this._collisionMask = !isNaN(mask) ? mask : -1;
  43255. },
  43256. enumerable: true,
  43257. configurable: true
  43258. });
  43259. FreeCamera.prototype._collideWithWorld = function (displacement) {
  43260. var globalPosition;
  43261. if (this.parent) {
  43262. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  43263. }
  43264. else {
  43265. globalPosition = this.position;
  43266. }
  43267. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  43268. this._oldPosition.addInPlace(this.ellipsoidOffset);
  43269. if (!this._collider) {
  43270. this._collider = new BABYLON.Collider();
  43271. }
  43272. this._collider._radius = this.ellipsoid;
  43273. this._collider.collisionMask = this._collisionMask;
  43274. //no need for clone, as long as gravity is not on.
  43275. var actualDisplacement = displacement;
  43276. //add gravity to the direction to prevent the dual-collision checking
  43277. if (this.applyGravity) {
  43278. //this prevents mending with cameraDirection, a global variable of the free camera class.
  43279. actualDisplacement = displacement.add(this.getScene().gravity);
  43280. }
  43281. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  43282. };
  43283. FreeCamera.prototype._checkInputs = function () {
  43284. if (!this._localDirection) {
  43285. this._localDirection = BABYLON.Vector3.Zero();
  43286. this._transformedDirection = BABYLON.Vector3.Zero();
  43287. }
  43288. this.inputs.checkInputs();
  43289. _super.prototype._checkInputs.call(this);
  43290. };
  43291. FreeCamera.prototype._decideIfNeedsToMove = function () {
  43292. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43293. };
  43294. FreeCamera.prototype._updatePosition = function () {
  43295. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  43296. this._collideWithWorld(this.cameraDirection);
  43297. }
  43298. else {
  43299. _super.prototype._updatePosition.call(this);
  43300. }
  43301. };
  43302. FreeCamera.prototype.dispose = function () {
  43303. this.inputs.clear();
  43304. _super.prototype.dispose.call(this);
  43305. };
  43306. FreeCamera.prototype.getClassName = function () {
  43307. return "FreeCamera";
  43308. };
  43309. __decorate([
  43310. BABYLON.serializeAsVector3()
  43311. ], FreeCamera.prototype, "ellipsoid", void 0);
  43312. __decorate([
  43313. BABYLON.serializeAsVector3()
  43314. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  43315. __decorate([
  43316. BABYLON.serialize()
  43317. ], FreeCamera.prototype, "checkCollisions", void 0);
  43318. __decorate([
  43319. BABYLON.serialize()
  43320. ], FreeCamera.prototype, "applyGravity", void 0);
  43321. return FreeCamera;
  43322. }(BABYLON.TargetCamera));
  43323. BABYLON.FreeCamera = FreeCamera;
  43324. })(BABYLON || (BABYLON = {}));
  43325. //# sourceMappingURL=babylon.freeCamera.js.map
  43326. var BABYLON;
  43327. (function (BABYLON) {
  43328. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  43329. function ArcRotateCameraKeyboardMoveInput() {
  43330. this._keys = new Array();
  43331. this.keysUp = [38];
  43332. this.keysDown = [40];
  43333. this.keysLeft = [37];
  43334. this.keysRight = [39];
  43335. this.keysReset = [220];
  43336. this.panningSensibility = 50.0;
  43337. this.zoomingSensibility = 25.0;
  43338. this.useAltToZoom = true;
  43339. }
  43340. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  43341. var _this = this;
  43342. if (this._onCanvasBlurObserver) {
  43343. return;
  43344. }
  43345. this._scene = this.camera.getScene();
  43346. this._engine = this._scene.getEngine();
  43347. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  43348. _this._keys = [];
  43349. });
  43350. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  43351. var evt = info.event;
  43352. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  43353. _this._ctrlPressed = evt.ctrlKey;
  43354. _this._altPressed = evt.altKey;
  43355. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43356. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43357. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43358. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43359. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43360. var index = _this._keys.indexOf(evt.keyCode);
  43361. if (index === -1) {
  43362. _this._keys.push(evt.keyCode);
  43363. }
  43364. if (evt.preventDefault) {
  43365. if (!noPreventDefault) {
  43366. evt.preventDefault();
  43367. }
  43368. }
  43369. }
  43370. }
  43371. else {
  43372. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  43373. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  43374. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  43375. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  43376. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  43377. var index = _this._keys.indexOf(evt.keyCode);
  43378. if (index >= 0) {
  43379. _this._keys.splice(index, 1);
  43380. }
  43381. if (evt.preventDefault) {
  43382. if (!noPreventDefault) {
  43383. evt.preventDefault();
  43384. }
  43385. }
  43386. }
  43387. }
  43388. });
  43389. };
  43390. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  43391. if (this._scene) {
  43392. if (this._onKeyboardObserver) {
  43393. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  43394. }
  43395. if (this._onCanvasBlurObserver) {
  43396. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  43397. }
  43398. this._onKeyboardObserver = null;
  43399. this._onCanvasBlurObserver = null;
  43400. }
  43401. this._keys = [];
  43402. };
  43403. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  43404. if (this._onKeyboardObserver) {
  43405. var camera = this.camera;
  43406. for (var index = 0; index < this._keys.length; index++) {
  43407. var keyCode = this._keys[index];
  43408. if (this.keysLeft.indexOf(keyCode) !== -1) {
  43409. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43410. camera.inertialPanningX -= 1 / this.panningSensibility;
  43411. }
  43412. else {
  43413. camera.inertialAlphaOffset -= 0.01;
  43414. }
  43415. }
  43416. else if (this.keysUp.indexOf(keyCode) !== -1) {
  43417. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43418. camera.inertialPanningY += 1 / this.panningSensibility;
  43419. }
  43420. else if (this._altPressed && this.useAltToZoom) {
  43421. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  43422. }
  43423. else {
  43424. camera.inertialBetaOffset -= 0.01;
  43425. }
  43426. }
  43427. else if (this.keysRight.indexOf(keyCode) !== -1) {
  43428. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43429. camera.inertialPanningX += 1 / this.panningSensibility;
  43430. }
  43431. else {
  43432. camera.inertialAlphaOffset += 0.01;
  43433. }
  43434. }
  43435. else if (this.keysDown.indexOf(keyCode) !== -1) {
  43436. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  43437. camera.inertialPanningY -= 1 / this.panningSensibility;
  43438. }
  43439. else if (this._altPressed && this.useAltToZoom) {
  43440. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  43441. }
  43442. else {
  43443. camera.inertialBetaOffset += 0.01;
  43444. }
  43445. }
  43446. else if (this.keysReset.indexOf(keyCode) !== -1) {
  43447. camera.restoreState();
  43448. }
  43449. }
  43450. }
  43451. };
  43452. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  43453. return "ArcRotateCameraKeyboardMoveInput";
  43454. };
  43455. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  43456. return "keyboard";
  43457. };
  43458. __decorate([
  43459. BABYLON.serialize()
  43460. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  43461. __decorate([
  43462. BABYLON.serialize()
  43463. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  43464. __decorate([
  43465. BABYLON.serialize()
  43466. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  43467. __decorate([
  43468. BABYLON.serialize()
  43469. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  43470. __decorate([
  43471. BABYLON.serialize()
  43472. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  43473. __decorate([
  43474. BABYLON.serialize()
  43475. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  43476. __decorate([
  43477. BABYLON.serialize()
  43478. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  43479. __decorate([
  43480. BABYLON.serialize()
  43481. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  43482. return ArcRotateCameraKeyboardMoveInput;
  43483. }());
  43484. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  43485. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  43486. })(BABYLON || (BABYLON = {}));
  43487. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  43488. var BABYLON;
  43489. (function (BABYLON) {
  43490. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  43491. function ArcRotateCameraMouseWheelInput() {
  43492. this.wheelPrecision = 3.0;
  43493. /**
  43494. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  43495. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  43496. */
  43497. this.wheelDeltaPercentage = 0;
  43498. }
  43499. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  43500. var _this = this;
  43501. this._wheel = function (p, s) {
  43502. //sanity check - this should be a PointerWheel event.
  43503. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  43504. return;
  43505. var event = p.event;
  43506. var delta = 0;
  43507. if (event.wheelDelta) {
  43508. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  43509. }
  43510. else if (event.detail) {
  43511. delta = -event.detail / _this.wheelPrecision;
  43512. }
  43513. if (delta)
  43514. _this.camera.inertialRadiusOffset += delta;
  43515. if (event.preventDefault) {
  43516. if (!noPreventDefault) {
  43517. event.preventDefault();
  43518. }
  43519. }
  43520. };
  43521. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  43522. };
  43523. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  43524. if (this._observer && element) {
  43525. this.camera.getScene().onPointerObservable.remove(this._observer);
  43526. this._observer = null;
  43527. this._wheel = null;
  43528. }
  43529. };
  43530. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  43531. return "ArcRotateCameraMouseWheelInput";
  43532. };
  43533. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  43534. return "mousewheel";
  43535. };
  43536. __decorate([
  43537. BABYLON.serialize()
  43538. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  43539. __decorate([
  43540. BABYLON.serialize()
  43541. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  43542. return ArcRotateCameraMouseWheelInput;
  43543. }());
  43544. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  43545. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  43546. })(BABYLON || (BABYLON = {}));
  43547. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  43548. var BABYLON;
  43549. (function (BABYLON) {
  43550. var ArcRotateCameraPointersInput = /** @class */ (function () {
  43551. function ArcRotateCameraPointersInput() {
  43552. this.buttons = [0, 1, 2];
  43553. this.angularSensibilityX = 1000.0;
  43554. this.angularSensibilityY = 1000.0;
  43555. this.pinchPrecision = 12.0;
  43556. /**
  43557. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  43558. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  43559. */
  43560. this.pinchDeltaPercentage = 0;
  43561. this.panningSensibility = 1000.0;
  43562. this.multiTouchPanning = true;
  43563. this.multiTouchPanAndZoom = true;
  43564. this._isPanClick = false;
  43565. this.pinchInwards = true;
  43566. }
  43567. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  43568. var _this = this;
  43569. var engine = this.camera.getEngine();
  43570. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  43571. var pointA = null;
  43572. var pointB = null;
  43573. var previousPinchSquaredDistance = 0;
  43574. var initialDistance = 0;
  43575. var twoFingerActivityCount = 0;
  43576. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  43577. this._pointerInput = function (p, s) {
  43578. var evt = p.event;
  43579. var isTouch = p.event.pointerType === "touch";
  43580. if (engine.isInVRExclusivePointerMode) {
  43581. return;
  43582. }
  43583. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43584. return;
  43585. }
  43586. var srcElement = (evt.srcElement || evt.target);
  43587. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43588. try {
  43589. srcElement.setPointerCapture(evt.pointerId);
  43590. }
  43591. catch (e) {
  43592. //Nothing to do with the error. Execution will continue.
  43593. }
  43594. // Manage panning with pan button click
  43595. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  43596. // manage pointers
  43597. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  43598. if (pointA === null) {
  43599. pointA = cacheSoloPointer;
  43600. }
  43601. else if (pointB === null) {
  43602. pointB = cacheSoloPointer;
  43603. }
  43604. if (!noPreventDefault) {
  43605. evt.preventDefault();
  43606. element.focus();
  43607. }
  43608. }
  43609. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  43610. _this.camera.restoreState();
  43611. }
  43612. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43613. try {
  43614. srcElement.releasePointerCapture(evt.pointerId);
  43615. }
  43616. catch (e) {
  43617. //Nothing to do with the error.
  43618. }
  43619. cacheSoloPointer = null;
  43620. previousPinchSquaredDistance = 0;
  43621. previousMultiTouchPanPosition.isPaning = false;
  43622. previousMultiTouchPanPosition.isPinching = false;
  43623. twoFingerActivityCount = 0;
  43624. initialDistance = 0;
  43625. if (!isTouch) {
  43626. pointB = null; // Mouse and pen are mono pointer
  43627. }
  43628. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  43629. //but emptying completly pointers collection is required to fix a bug on iPhone :
  43630. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  43631. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  43632. if (engine.badOS) {
  43633. pointA = pointB = null;
  43634. }
  43635. else {
  43636. //only remove the impacted pointer in case of multitouch allowing on most
  43637. //platforms switching from rotate to zoom and pan seamlessly.
  43638. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  43639. pointA = pointB;
  43640. pointB = null;
  43641. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43642. }
  43643. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  43644. pointB = null;
  43645. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  43646. }
  43647. else {
  43648. pointA = pointB = null;
  43649. }
  43650. }
  43651. if (!noPreventDefault) {
  43652. evt.preventDefault();
  43653. }
  43654. }
  43655. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43656. if (!noPreventDefault) {
  43657. evt.preventDefault();
  43658. }
  43659. // One button down
  43660. if (pointA && pointB === null && cacheSoloPointer) {
  43661. if (_this.panningSensibility !== 0 &&
  43662. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  43663. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  43664. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  43665. }
  43666. else {
  43667. var offsetX = evt.clientX - cacheSoloPointer.x;
  43668. var offsetY = evt.clientY - cacheSoloPointer.y;
  43669. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43670. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43671. }
  43672. cacheSoloPointer.x = evt.clientX;
  43673. cacheSoloPointer.y = evt.clientY;
  43674. }
  43675. else if (pointA && pointB) {
  43676. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  43677. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  43678. ed.x = evt.clientX;
  43679. ed.y = evt.clientY;
  43680. var direction = _this.pinchInwards ? 1 : -1;
  43681. var distX = pointA.x - pointB.x;
  43682. var distY = pointA.y - pointB.y;
  43683. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  43684. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  43685. if (previousPinchSquaredDistance === 0) {
  43686. initialDistance = pinchDistance;
  43687. previousPinchSquaredDistance = pinchSquaredDistance;
  43688. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  43689. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  43690. return;
  43691. }
  43692. if (_this.multiTouchPanAndZoom) {
  43693. if (_this.pinchDeltaPercentage) {
  43694. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43695. }
  43696. else {
  43697. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43698. (_this.pinchPrecision *
  43699. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43700. direction);
  43701. }
  43702. if (_this.panningSensibility !== 0) {
  43703. var pointersCenterX = (pointA.x + pointB.x) / 2;
  43704. var pointersCenterY = (pointA.y + pointB.y) / 2;
  43705. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  43706. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  43707. previousMultiTouchPanPosition.x = pointersCenterX;
  43708. previousMultiTouchPanPosition.y = pointersCenterY;
  43709. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  43710. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  43711. }
  43712. }
  43713. else {
  43714. twoFingerActivityCount++;
  43715. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  43716. if (_this.pinchDeltaPercentage) {
  43717. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  43718. }
  43719. else {
  43720. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  43721. (_this.pinchPrecision *
  43722. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  43723. direction);
  43724. }
  43725. previousMultiTouchPanPosition.isPaning = false;
  43726. previousMultiTouchPanPosition.isPinching = true;
  43727. }
  43728. else {
  43729. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  43730. if (!previousMultiTouchPanPosition.isPaning) {
  43731. previousMultiTouchPanPosition.isPaning = true;
  43732. previousMultiTouchPanPosition.isPinching = false;
  43733. previousMultiTouchPanPosition.x = ed.x;
  43734. previousMultiTouchPanPosition.y = ed.y;
  43735. return;
  43736. }
  43737. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  43738. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  43739. }
  43740. }
  43741. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  43742. previousMultiTouchPanPosition.x = ed.x;
  43743. previousMultiTouchPanPosition.y = ed.y;
  43744. }
  43745. }
  43746. previousPinchSquaredDistance = pinchSquaredDistance;
  43747. }
  43748. }
  43749. };
  43750. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  43751. this._onContextMenu = function (evt) {
  43752. evt.preventDefault();
  43753. };
  43754. if (!this.camera._useCtrlForPanning) {
  43755. element.addEventListener("contextmenu", this._onContextMenu, false);
  43756. }
  43757. this._onLostFocus = function () {
  43758. //this._keys = [];
  43759. pointA = pointB = null;
  43760. previousPinchSquaredDistance = 0;
  43761. previousMultiTouchPanPosition.isPaning = false;
  43762. previousMultiTouchPanPosition.isPinching = false;
  43763. twoFingerActivityCount = 0;
  43764. cacheSoloPointer = null;
  43765. initialDistance = 0;
  43766. };
  43767. this._onMouseMove = function (evt) {
  43768. if (!engine.isPointerLock) {
  43769. return;
  43770. }
  43771. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43772. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43773. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  43774. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  43775. if (!noPreventDefault) {
  43776. evt.preventDefault();
  43777. }
  43778. };
  43779. this._onGestureStart = function (e) {
  43780. if (window.MSGesture === undefined) {
  43781. return;
  43782. }
  43783. if (!_this._MSGestureHandler) {
  43784. _this._MSGestureHandler = new MSGesture();
  43785. _this._MSGestureHandler.target = element;
  43786. }
  43787. _this._MSGestureHandler.addPointer(e.pointerId);
  43788. };
  43789. this._onGesture = function (e) {
  43790. _this.camera.radius *= e.scale;
  43791. if (e.preventDefault) {
  43792. if (!noPreventDefault) {
  43793. e.stopPropagation();
  43794. e.preventDefault();
  43795. }
  43796. }
  43797. };
  43798. element.addEventListener("mousemove", this._onMouseMove, false);
  43799. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  43800. element.addEventListener("MSGestureChange", this._onGesture, false);
  43801. BABYLON.Tools.RegisterTopRootEvents([
  43802. { name: "blur", handler: this._onLostFocus }
  43803. ]);
  43804. };
  43805. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  43806. if (this._onLostFocus) {
  43807. BABYLON.Tools.UnregisterTopRootEvents([
  43808. { name: "blur", handler: this._onLostFocus }
  43809. ]);
  43810. }
  43811. if (element && this._observer) {
  43812. this.camera.getScene().onPointerObservable.remove(this._observer);
  43813. this._observer = null;
  43814. if (this._onContextMenu) {
  43815. element.removeEventListener("contextmenu", this._onContextMenu);
  43816. }
  43817. if (this._onMouseMove) {
  43818. element.removeEventListener("mousemove", this._onMouseMove);
  43819. }
  43820. if (this._onGestureStart) {
  43821. element.removeEventListener("MSPointerDown", this._onGestureStart);
  43822. }
  43823. if (this._onGesture) {
  43824. element.removeEventListener("MSGestureChange", this._onGesture);
  43825. }
  43826. this._isPanClick = false;
  43827. this.pinchInwards = true;
  43828. this._onMouseMove = null;
  43829. this._onGestureStart = null;
  43830. this._onGesture = null;
  43831. this._MSGestureHandler = null;
  43832. this._onLostFocus = null;
  43833. this._onContextMenu = null;
  43834. }
  43835. };
  43836. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  43837. return "ArcRotateCameraPointersInput";
  43838. };
  43839. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  43840. return "pointers";
  43841. };
  43842. __decorate([
  43843. BABYLON.serialize()
  43844. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  43845. __decorate([
  43846. BABYLON.serialize()
  43847. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  43848. __decorate([
  43849. BABYLON.serialize()
  43850. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  43851. __decorate([
  43852. BABYLON.serialize()
  43853. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  43854. __decorate([
  43855. BABYLON.serialize()
  43856. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  43857. __decorate([
  43858. BABYLON.serialize()
  43859. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  43860. __decorate([
  43861. BABYLON.serialize()
  43862. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  43863. __decorate([
  43864. BABYLON.serialize()
  43865. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  43866. return ArcRotateCameraPointersInput;
  43867. }());
  43868. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  43869. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  43870. })(BABYLON || (BABYLON = {}));
  43871. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  43872. var BABYLON;
  43873. (function (BABYLON) {
  43874. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  43875. __extends(ArcRotateCameraInputsManager, _super);
  43876. function ArcRotateCameraInputsManager(camera) {
  43877. return _super.call(this, camera) || this;
  43878. }
  43879. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  43880. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  43881. return this;
  43882. };
  43883. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  43884. this.add(new BABYLON.ArcRotateCameraPointersInput());
  43885. return this;
  43886. };
  43887. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  43888. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  43889. return this;
  43890. };
  43891. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  43892. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  43893. return this;
  43894. };
  43895. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  43896. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  43897. return this;
  43898. };
  43899. return ArcRotateCameraInputsManager;
  43900. }(BABYLON.CameraInputsManager));
  43901. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  43902. })(BABYLON || (BABYLON = {}));
  43903. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  43904. var BABYLON;
  43905. (function (BABYLON) {
  43906. var ArcRotateCamera = /** @class */ (function (_super) {
  43907. __extends(ArcRotateCamera, _super);
  43908. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  43909. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  43910. _this.inertialAlphaOffset = 0;
  43911. _this.inertialBetaOffset = 0;
  43912. _this.inertialRadiusOffset = 0;
  43913. _this.lowerAlphaLimit = null;
  43914. _this.upperAlphaLimit = null;
  43915. _this.lowerBetaLimit = 0.01;
  43916. _this.upperBetaLimit = Math.PI;
  43917. _this.lowerRadiusLimit = null;
  43918. _this.upperRadiusLimit = null;
  43919. _this.inertialPanningX = 0;
  43920. _this.inertialPanningY = 0;
  43921. _this.pinchToPanMaxDistance = 20;
  43922. _this.panningDistanceLimit = null;
  43923. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  43924. _this.panningInertia = 0.9;
  43925. //-- end properties for backward compatibility for inputs
  43926. _this.zoomOnFactor = 1;
  43927. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  43928. _this.allowUpsideDown = true;
  43929. _this._viewMatrix = new BABYLON.Matrix();
  43930. // Panning
  43931. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  43932. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  43933. _this.checkCollisions = false;
  43934. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  43935. _this._previousPosition = BABYLON.Vector3.Zero();
  43936. _this._collisionVelocity = BABYLON.Vector3.Zero();
  43937. _this._newPosition = BABYLON.Vector3.Zero();
  43938. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  43939. if (collidedMesh === void 0) { collidedMesh = null; }
  43940. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  43941. newPosition.multiplyInPlace(_this._collider._radius);
  43942. }
  43943. if (!collidedMesh) {
  43944. _this._previousPosition.copyFrom(_this.position);
  43945. }
  43946. else {
  43947. _this.setPosition(newPosition);
  43948. if (_this.onCollide) {
  43949. _this.onCollide(collidedMesh);
  43950. }
  43951. }
  43952. // Recompute because of constraints
  43953. var cosa = Math.cos(_this.alpha);
  43954. var sina = Math.sin(_this.alpha);
  43955. var cosb = Math.cos(_this.beta);
  43956. var sinb = Math.sin(_this.beta);
  43957. if (sinb === 0) {
  43958. sinb = 0.0001;
  43959. }
  43960. var target = _this._getTargetPosition();
  43961. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  43962. _this.position.copyFrom(_this._newPosition);
  43963. var up = _this.upVector;
  43964. if (_this.allowUpsideDown && _this.beta < 0) {
  43965. up = up.clone();
  43966. up = up.negate();
  43967. }
  43968. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  43969. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  43970. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  43971. _this._collisionTriggered = false;
  43972. };
  43973. _this._target = BABYLON.Vector3.Zero();
  43974. if (target) {
  43975. _this.setTarget(target);
  43976. }
  43977. _this.alpha = alpha;
  43978. _this.beta = beta;
  43979. _this.radius = radius;
  43980. _this.getViewMatrix();
  43981. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  43982. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  43983. return _this;
  43984. }
  43985. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  43986. get: function () {
  43987. return this._target;
  43988. },
  43989. set: function (value) {
  43990. this.setTarget(value);
  43991. },
  43992. enumerable: true,
  43993. configurable: true
  43994. });
  43995. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  43996. //-- begin properties for backward compatibility for inputs
  43997. get: function () {
  43998. var pointers = this.inputs.attached["pointers"];
  43999. if (pointers)
  44000. return pointers.angularSensibilityX;
  44001. return 0;
  44002. },
  44003. set: function (value) {
  44004. var pointers = this.inputs.attached["pointers"];
  44005. if (pointers) {
  44006. pointers.angularSensibilityX = value;
  44007. }
  44008. },
  44009. enumerable: true,
  44010. configurable: true
  44011. });
  44012. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  44013. get: function () {
  44014. var pointers = this.inputs.attached["pointers"];
  44015. if (pointers)
  44016. return pointers.angularSensibilityY;
  44017. return 0;
  44018. },
  44019. set: function (value) {
  44020. var pointers = this.inputs.attached["pointers"];
  44021. if (pointers) {
  44022. pointers.angularSensibilityY = value;
  44023. }
  44024. },
  44025. enumerable: true,
  44026. configurable: true
  44027. });
  44028. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  44029. get: function () {
  44030. var pointers = this.inputs.attached["pointers"];
  44031. if (pointers)
  44032. return pointers.pinchPrecision;
  44033. return 0;
  44034. },
  44035. set: function (value) {
  44036. var pointers = this.inputs.attached["pointers"];
  44037. if (pointers) {
  44038. pointers.pinchPrecision = value;
  44039. }
  44040. },
  44041. enumerable: true,
  44042. configurable: true
  44043. });
  44044. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  44045. get: function () {
  44046. var pointers = this.inputs.attached["pointers"];
  44047. if (pointers)
  44048. return pointers.pinchDeltaPercentage;
  44049. return 0;
  44050. },
  44051. set: function (value) {
  44052. var pointers = this.inputs.attached["pointers"];
  44053. if (pointers) {
  44054. pointers.pinchDeltaPercentage = value;
  44055. }
  44056. },
  44057. enumerable: true,
  44058. configurable: true
  44059. });
  44060. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  44061. get: function () {
  44062. var pointers = this.inputs.attached["pointers"];
  44063. if (pointers)
  44064. return pointers.panningSensibility;
  44065. return 0;
  44066. },
  44067. set: function (value) {
  44068. var pointers = this.inputs.attached["pointers"];
  44069. if (pointers) {
  44070. pointers.panningSensibility = value;
  44071. }
  44072. },
  44073. enumerable: true,
  44074. configurable: true
  44075. });
  44076. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  44077. get: function () {
  44078. var keyboard = this.inputs.attached["keyboard"];
  44079. if (keyboard)
  44080. return keyboard.keysUp;
  44081. return [];
  44082. },
  44083. set: function (value) {
  44084. var keyboard = this.inputs.attached["keyboard"];
  44085. if (keyboard)
  44086. keyboard.keysUp = value;
  44087. },
  44088. enumerable: true,
  44089. configurable: true
  44090. });
  44091. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  44092. get: function () {
  44093. var keyboard = this.inputs.attached["keyboard"];
  44094. if (keyboard)
  44095. return keyboard.keysDown;
  44096. return [];
  44097. },
  44098. set: function (value) {
  44099. var keyboard = this.inputs.attached["keyboard"];
  44100. if (keyboard)
  44101. keyboard.keysDown = value;
  44102. },
  44103. enumerable: true,
  44104. configurable: true
  44105. });
  44106. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  44107. get: function () {
  44108. var keyboard = this.inputs.attached["keyboard"];
  44109. if (keyboard)
  44110. return keyboard.keysLeft;
  44111. return [];
  44112. },
  44113. set: function (value) {
  44114. var keyboard = this.inputs.attached["keyboard"];
  44115. if (keyboard)
  44116. keyboard.keysLeft = value;
  44117. },
  44118. enumerable: true,
  44119. configurable: true
  44120. });
  44121. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  44122. get: function () {
  44123. var keyboard = this.inputs.attached["keyboard"];
  44124. if (keyboard)
  44125. return keyboard.keysRight;
  44126. return [];
  44127. },
  44128. set: function (value) {
  44129. var keyboard = this.inputs.attached["keyboard"];
  44130. if (keyboard)
  44131. keyboard.keysRight = value;
  44132. },
  44133. enumerable: true,
  44134. configurable: true
  44135. });
  44136. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  44137. get: function () {
  44138. var mousewheel = this.inputs.attached["mousewheel"];
  44139. if (mousewheel)
  44140. return mousewheel.wheelPrecision;
  44141. return 0;
  44142. },
  44143. set: function (value) {
  44144. var mousewheel = this.inputs.attached["mousewheel"];
  44145. if (mousewheel)
  44146. mousewheel.wheelPrecision = value;
  44147. },
  44148. enumerable: true,
  44149. configurable: true
  44150. });
  44151. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  44152. get: function () {
  44153. var mousewheel = this.inputs.attached["mousewheel"];
  44154. if (mousewheel)
  44155. return mousewheel.wheelDeltaPercentage;
  44156. return 0;
  44157. },
  44158. set: function (value) {
  44159. var mousewheel = this.inputs.attached["mousewheel"];
  44160. if (mousewheel)
  44161. mousewheel.wheelDeltaPercentage = value;
  44162. },
  44163. enumerable: true,
  44164. configurable: true
  44165. });
  44166. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  44167. get: function () {
  44168. return this._bouncingBehavior;
  44169. },
  44170. enumerable: true,
  44171. configurable: true
  44172. });
  44173. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  44174. get: function () {
  44175. return this._bouncingBehavior != null;
  44176. },
  44177. set: function (value) {
  44178. if (value === this.useBouncingBehavior) {
  44179. return;
  44180. }
  44181. if (value) {
  44182. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  44183. this.addBehavior(this._bouncingBehavior);
  44184. }
  44185. else if (this._bouncingBehavior) {
  44186. this.removeBehavior(this._bouncingBehavior);
  44187. this._bouncingBehavior = null;
  44188. }
  44189. },
  44190. enumerable: true,
  44191. configurable: true
  44192. });
  44193. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  44194. get: function () {
  44195. return this._framingBehavior;
  44196. },
  44197. enumerable: true,
  44198. configurable: true
  44199. });
  44200. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  44201. get: function () {
  44202. return this._framingBehavior != null;
  44203. },
  44204. set: function (value) {
  44205. if (value === this.useFramingBehavior) {
  44206. return;
  44207. }
  44208. if (value) {
  44209. this._framingBehavior = new BABYLON.FramingBehavior();
  44210. this.addBehavior(this._framingBehavior);
  44211. }
  44212. else if (this._framingBehavior) {
  44213. this.removeBehavior(this._framingBehavior);
  44214. this._framingBehavior = null;
  44215. }
  44216. },
  44217. enumerable: true,
  44218. configurable: true
  44219. });
  44220. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  44221. get: function () {
  44222. return this._autoRotationBehavior;
  44223. },
  44224. enumerable: true,
  44225. configurable: true
  44226. });
  44227. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  44228. get: function () {
  44229. return this._autoRotationBehavior != null;
  44230. },
  44231. set: function (value) {
  44232. if (value === this.useAutoRotationBehavior) {
  44233. return;
  44234. }
  44235. if (value) {
  44236. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  44237. this.addBehavior(this._autoRotationBehavior);
  44238. }
  44239. else if (this._autoRotationBehavior) {
  44240. this.removeBehavior(this._autoRotationBehavior);
  44241. this._autoRotationBehavior = null;
  44242. }
  44243. },
  44244. enumerable: true,
  44245. configurable: true
  44246. });
  44247. // Cache
  44248. ArcRotateCamera.prototype._initCache = function () {
  44249. _super.prototype._initCache.call(this);
  44250. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  44251. this._cache.alpha = undefined;
  44252. this._cache.beta = undefined;
  44253. this._cache.radius = undefined;
  44254. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  44255. };
  44256. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  44257. if (!ignoreParentClass) {
  44258. _super.prototype._updateCache.call(this);
  44259. }
  44260. this._cache._target.copyFrom(this._getTargetPosition());
  44261. this._cache.alpha = this.alpha;
  44262. this._cache.beta = this.beta;
  44263. this._cache.radius = this.radius;
  44264. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  44265. };
  44266. ArcRotateCamera.prototype._getTargetPosition = function () {
  44267. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  44268. var pos = this._targetHost.getAbsolutePosition();
  44269. if (this._targetBoundingCenter) {
  44270. pos.addToRef(this._targetBoundingCenter, this._target);
  44271. }
  44272. else {
  44273. this._target.copyFrom(pos);
  44274. }
  44275. }
  44276. var lockedTargetPosition = this._getLockedTargetPosition();
  44277. if (lockedTargetPosition) {
  44278. return lockedTargetPosition;
  44279. }
  44280. return this._target;
  44281. };
  44282. ArcRotateCamera.prototype.storeState = function () {
  44283. this._storedAlpha = this.alpha;
  44284. this._storedBeta = this.beta;
  44285. this._storedRadius = this.radius;
  44286. this._storedTarget = this._getTargetPosition().clone();
  44287. return _super.prototype.storeState.call(this);
  44288. };
  44289. /**
  44290. * Restored camera state. You must call storeState() first
  44291. */
  44292. ArcRotateCamera.prototype._restoreStateValues = function () {
  44293. if (!_super.prototype._restoreStateValues.call(this)) {
  44294. return false;
  44295. }
  44296. this.alpha = this._storedAlpha;
  44297. this.beta = this._storedBeta;
  44298. this.radius = this._storedRadius;
  44299. this.setTarget(this._storedTarget.clone());
  44300. this.inertialAlphaOffset = 0;
  44301. this.inertialBetaOffset = 0;
  44302. this.inertialRadiusOffset = 0;
  44303. this.inertialPanningX = 0;
  44304. this.inertialPanningY = 0;
  44305. return true;
  44306. };
  44307. // Synchronized
  44308. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  44309. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  44310. return false;
  44311. return this._cache._target.equals(this._getTargetPosition())
  44312. && this._cache.alpha === this.alpha
  44313. && this._cache.beta === this.beta
  44314. && this._cache.radius === this.radius
  44315. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  44316. };
  44317. // Methods
  44318. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  44319. var _this = this;
  44320. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  44321. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  44322. this._useCtrlForPanning = useCtrlForPanning;
  44323. this._panningMouseButton = panningMouseButton;
  44324. this.inputs.attachElement(element, noPreventDefault);
  44325. this._reset = function () {
  44326. _this.inertialAlphaOffset = 0;
  44327. _this.inertialBetaOffset = 0;
  44328. _this.inertialRadiusOffset = 0;
  44329. _this.inertialPanningX = 0;
  44330. _this.inertialPanningY = 0;
  44331. };
  44332. };
  44333. ArcRotateCamera.prototype.detachControl = function (element) {
  44334. this.inputs.detachElement(element);
  44335. if (this._reset) {
  44336. this._reset();
  44337. }
  44338. };
  44339. ArcRotateCamera.prototype._checkInputs = function () {
  44340. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  44341. if (this._collisionTriggered) {
  44342. return;
  44343. }
  44344. this.inputs.checkInputs();
  44345. // Inertia
  44346. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  44347. if (this.getScene().useRightHandedSystem) {
  44348. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44349. }
  44350. else {
  44351. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  44352. }
  44353. this.beta += this.inertialBetaOffset;
  44354. this.radius -= this.inertialRadiusOffset;
  44355. this.inertialAlphaOffset *= this.inertia;
  44356. this.inertialBetaOffset *= this.inertia;
  44357. this.inertialRadiusOffset *= this.inertia;
  44358. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  44359. this.inertialAlphaOffset = 0;
  44360. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  44361. this.inertialBetaOffset = 0;
  44362. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  44363. this.inertialRadiusOffset = 0;
  44364. }
  44365. // Panning inertia
  44366. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  44367. if (!this._localDirection) {
  44368. this._localDirection = BABYLON.Vector3.Zero();
  44369. this._transformedDirection = BABYLON.Vector3.Zero();
  44370. }
  44371. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  44372. this._localDirection.multiplyInPlace(this.panningAxis);
  44373. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  44374. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  44375. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  44376. if (!this.panningAxis.y) {
  44377. this._transformedDirection.y = 0;
  44378. }
  44379. if (!this._targetHost) {
  44380. if (this.panningDistanceLimit) {
  44381. this._transformedDirection.addInPlace(this._target);
  44382. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  44383. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  44384. this._target.copyFrom(this._transformedDirection);
  44385. }
  44386. }
  44387. else {
  44388. this._target.addInPlace(this._transformedDirection);
  44389. }
  44390. }
  44391. this.inertialPanningX *= this.panningInertia;
  44392. this.inertialPanningY *= this.panningInertia;
  44393. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  44394. this.inertialPanningX = 0;
  44395. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  44396. this.inertialPanningY = 0;
  44397. }
  44398. // Limits
  44399. this._checkLimits();
  44400. _super.prototype._checkInputs.call(this);
  44401. };
  44402. ArcRotateCamera.prototype._checkLimits = function () {
  44403. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  44404. if (this.allowUpsideDown && this.beta > Math.PI) {
  44405. this.beta = this.beta - (2 * Math.PI);
  44406. }
  44407. }
  44408. else {
  44409. if (this.beta < this.lowerBetaLimit) {
  44410. this.beta = this.lowerBetaLimit;
  44411. }
  44412. }
  44413. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  44414. if (this.allowUpsideDown && this.beta < -Math.PI) {
  44415. this.beta = this.beta + (2 * Math.PI);
  44416. }
  44417. }
  44418. else {
  44419. if (this.beta > this.upperBetaLimit) {
  44420. this.beta = this.upperBetaLimit;
  44421. }
  44422. }
  44423. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  44424. this.alpha = this.lowerAlphaLimit;
  44425. }
  44426. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  44427. this.alpha = this.upperAlphaLimit;
  44428. }
  44429. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  44430. this.radius = this.lowerRadiusLimit;
  44431. }
  44432. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  44433. this.radius = this.upperRadiusLimit;
  44434. }
  44435. };
  44436. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  44437. var radiusv3 = this.position.subtract(this._getTargetPosition());
  44438. this.radius = radiusv3.length();
  44439. if (this.radius === 0) {
  44440. this.radius = 0.0001; // Just to avoid division by zero
  44441. }
  44442. // Alpha
  44443. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  44444. if (radiusv3.z < 0) {
  44445. this.alpha = 2 * Math.PI - this.alpha;
  44446. }
  44447. // Beta
  44448. this.beta = Math.acos(radiusv3.y / this.radius);
  44449. this._checkLimits();
  44450. };
  44451. ArcRotateCamera.prototype.setPosition = function (position) {
  44452. if (this.position.equals(position)) {
  44453. return;
  44454. }
  44455. this.position.copyFrom(position);
  44456. this.rebuildAnglesAndRadius();
  44457. };
  44458. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  44459. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  44460. if (allowSamePosition === void 0) { allowSamePosition = false; }
  44461. if (target.getBoundingInfo) {
  44462. if (toBoundingCenter) {
  44463. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  44464. }
  44465. else {
  44466. this._targetBoundingCenter = null;
  44467. }
  44468. this._targetHost = target;
  44469. this._target = this._getTargetPosition();
  44470. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  44471. }
  44472. else {
  44473. var newTarget = target;
  44474. var currentTarget = this._getTargetPosition();
  44475. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  44476. return;
  44477. }
  44478. this._targetHost = null;
  44479. this._target = newTarget;
  44480. this._targetBoundingCenter = null;
  44481. this.onMeshTargetChangedObservable.notifyObservers(null);
  44482. }
  44483. this.rebuildAnglesAndRadius();
  44484. };
  44485. ArcRotateCamera.prototype._getViewMatrix = function () {
  44486. // Compute
  44487. var cosa = Math.cos(this.alpha);
  44488. var sina = Math.sin(this.alpha);
  44489. var cosb = Math.cos(this.beta);
  44490. var sinb = Math.sin(this.beta);
  44491. if (sinb === 0) {
  44492. sinb = 0.0001;
  44493. }
  44494. var target = this._getTargetPosition();
  44495. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  44496. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  44497. if (!this._collider) {
  44498. this._collider = new BABYLON.Collider();
  44499. }
  44500. this._collider._radius = this.collisionRadius;
  44501. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  44502. this._collisionTriggered = true;
  44503. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44504. }
  44505. else {
  44506. this.position.copyFrom(this._newPosition);
  44507. var up = this.upVector;
  44508. if (this.allowUpsideDown && sinb < 0) {
  44509. up = up.clone();
  44510. up = up.negate();
  44511. }
  44512. if (this.getScene().useRightHandedSystem) {
  44513. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  44514. }
  44515. else {
  44516. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  44517. }
  44518. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  44519. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  44520. }
  44521. this._currentTarget = target;
  44522. return this._viewMatrix;
  44523. };
  44524. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  44525. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44526. meshes = meshes || this.getScene().meshes;
  44527. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  44528. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  44529. this.radius = distance * this.zoomOnFactor;
  44530. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  44531. };
  44532. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  44533. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  44534. var meshesOrMinMaxVector;
  44535. var distance;
  44536. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  44537. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  44538. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  44539. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  44540. }
  44541. else {
  44542. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  44543. meshesOrMinMaxVector = minMaxVectorAndDistance;
  44544. distance = minMaxVectorAndDistance.distance;
  44545. }
  44546. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  44547. if (!doNotUpdateMaxZ) {
  44548. this.maxZ = distance * 2;
  44549. }
  44550. };
  44551. /**
  44552. * @override
  44553. * Override Camera.createRigCamera
  44554. */
  44555. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  44556. var alphaShift = 0;
  44557. switch (this.cameraRigMode) {
  44558. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44559. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44560. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44561. case BABYLON.Camera.RIG_MODE_VR:
  44562. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  44563. break;
  44564. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44565. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  44566. break;
  44567. }
  44568. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  44569. rigCam._cameraRigParams = {};
  44570. return rigCam;
  44571. };
  44572. /**
  44573. * @override
  44574. * Override Camera._updateRigCameras
  44575. */
  44576. ArcRotateCamera.prototype._updateRigCameras = function () {
  44577. var camLeft = this._rigCameras[0];
  44578. var camRight = this._rigCameras[1];
  44579. camLeft.beta = camRight.beta = this.beta;
  44580. camLeft.radius = camRight.radius = this.radius;
  44581. switch (this.cameraRigMode) {
  44582. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  44583. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  44584. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  44585. case BABYLON.Camera.RIG_MODE_VR:
  44586. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44587. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44588. break;
  44589. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  44590. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  44591. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  44592. break;
  44593. }
  44594. _super.prototype._updateRigCameras.call(this);
  44595. };
  44596. ArcRotateCamera.prototype.dispose = function () {
  44597. this.inputs.clear();
  44598. _super.prototype.dispose.call(this);
  44599. };
  44600. ArcRotateCamera.prototype.getClassName = function () {
  44601. return "ArcRotateCamera";
  44602. };
  44603. __decorate([
  44604. BABYLON.serialize()
  44605. ], ArcRotateCamera.prototype, "alpha", void 0);
  44606. __decorate([
  44607. BABYLON.serialize()
  44608. ], ArcRotateCamera.prototype, "beta", void 0);
  44609. __decorate([
  44610. BABYLON.serialize()
  44611. ], ArcRotateCamera.prototype, "radius", void 0);
  44612. __decorate([
  44613. BABYLON.serializeAsVector3("target")
  44614. ], ArcRotateCamera.prototype, "_target", void 0);
  44615. __decorate([
  44616. BABYLON.serialize()
  44617. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  44618. __decorate([
  44619. BABYLON.serialize()
  44620. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  44621. __decorate([
  44622. BABYLON.serialize()
  44623. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  44624. __decorate([
  44625. BABYLON.serialize()
  44626. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  44627. __decorate([
  44628. BABYLON.serialize()
  44629. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  44630. __decorate([
  44631. BABYLON.serialize()
  44632. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  44633. __decorate([
  44634. BABYLON.serialize()
  44635. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  44636. __decorate([
  44637. BABYLON.serialize()
  44638. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  44639. __decorate([
  44640. BABYLON.serialize()
  44641. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  44642. __decorate([
  44643. BABYLON.serialize()
  44644. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  44645. __decorate([
  44646. BABYLON.serialize()
  44647. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  44648. __decorate([
  44649. BABYLON.serialize()
  44650. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  44651. __decorate([
  44652. BABYLON.serialize()
  44653. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  44654. __decorate([
  44655. BABYLON.serializeAsVector3()
  44656. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  44657. __decorate([
  44658. BABYLON.serialize()
  44659. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  44660. __decorate([
  44661. BABYLON.serialize()
  44662. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  44663. __decorate([
  44664. BABYLON.serialize()
  44665. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  44666. return ArcRotateCamera;
  44667. }(BABYLON.TargetCamera));
  44668. BABYLON.ArcRotateCamera = ArcRotateCamera;
  44669. })(BABYLON || (BABYLON = {}));
  44670. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  44671. var BABYLON;
  44672. (function (BABYLON) {
  44673. /**
  44674. * The HemisphericLight simulates the ambient environment light,
  44675. * so the passed direction is the light reflection direction, not the incoming direction.
  44676. */
  44677. var HemisphericLight = /** @class */ (function (_super) {
  44678. __extends(HemisphericLight, _super);
  44679. /**
  44680. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  44681. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  44682. * The HemisphericLight can't cast shadows.
  44683. * Documentation : http://doc.babylonjs.com/tutorials/lights
  44684. * @param name The friendly name of the light
  44685. * @param direction The direction of the light reflection
  44686. * @param scene The scene the light belongs to
  44687. */
  44688. function HemisphericLight(name, direction, scene) {
  44689. var _this = _super.call(this, name, scene) || this;
  44690. /**
  44691. * The groundColor is the light in the opposite direction to the one specified during creation.
  44692. * 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.
  44693. */
  44694. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  44695. _this.direction = direction || BABYLON.Vector3.Up();
  44696. return _this;
  44697. }
  44698. HemisphericLight.prototype._buildUniformLayout = function () {
  44699. this._uniformBuffer.addUniform("vLightData", 4);
  44700. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  44701. this._uniformBuffer.addUniform("vLightSpecular", 3);
  44702. this._uniformBuffer.addUniform("vLightGround", 3);
  44703. this._uniformBuffer.addUniform("shadowsInfo", 3);
  44704. this._uniformBuffer.addUniform("depthValues", 2);
  44705. this._uniformBuffer.create();
  44706. };
  44707. /**
  44708. * Returns the string "HemisphericLight".
  44709. * @return The class name
  44710. */
  44711. HemisphericLight.prototype.getClassName = function () {
  44712. return "HemisphericLight";
  44713. };
  44714. /**
  44715. * Sets the HemisphericLight direction towards the passed target (Vector3).
  44716. * Returns the updated direction.
  44717. * @param target The target the direction should point to
  44718. * @return The computed direction
  44719. */
  44720. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  44721. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  44722. return this.direction;
  44723. };
  44724. /**
  44725. * Returns the shadow generator associated to the light.
  44726. * @returns Always null for hemispheric lights because it does not support shadows.
  44727. */
  44728. HemisphericLight.prototype.getShadowGenerator = function () {
  44729. return null;
  44730. };
  44731. /**
  44732. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  44733. * @param effect The effect to update
  44734. * @param lightIndex The index of the light in the effect to update
  44735. * @returns The hemispheric light
  44736. */
  44737. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  44738. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  44739. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  44740. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  44741. return this;
  44742. };
  44743. /**
  44744. * @ignore internal use only.
  44745. */
  44746. HemisphericLight.prototype._getWorldMatrix = function () {
  44747. if (!this._worldMatrix) {
  44748. this._worldMatrix = BABYLON.Matrix.Identity();
  44749. }
  44750. return this._worldMatrix;
  44751. };
  44752. /**
  44753. * Returns the integer 3.
  44754. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  44755. */
  44756. HemisphericLight.prototype.getTypeID = function () {
  44757. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  44758. };
  44759. __decorate([
  44760. BABYLON.serializeAsColor3()
  44761. ], HemisphericLight.prototype, "groundColor", void 0);
  44762. __decorate([
  44763. BABYLON.serializeAsVector3()
  44764. ], HemisphericLight.prototype, "direction", void 0);
  44765. return HemisphericLight;
  44766. }(BABYLON.Light));
  44767. BABYLON.HemisphericLight = HemisphericLight;
  44768. })(BABYLON || (BABYLON = {}));
  44769. //# sourceMappingURL=babylon.hemisphericLight.js.map
  44770. var BABYLON;
  44771. (function (BABYLON) {
  44772. /**
  44773. * Base implementation of @see IShadowLight
  44774. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  44775. */
  44776. var ShadowLight = /** @class */ (function (_super) {
  44777. __extends(ShadowLight, _super);
  44778. function ShadowLight() {
  44779. var _this = _super !== null && _super.apply(this, arguments) || this;
  44780. _this._needProjectionMatrixCompute = true;
  44781. return _this;
  44782. }
  44783. ShadowLight.prototype._setPosition = function (value) {
  44784. this._position = value;
  44785. };
  44786. Object.defineProperty(ShadowLight.prototype, "position", {
  44787. /**
  44788. * Sets the position the shadow will be casted from. Also use as the light position for both
  44789. * point and spot lights.
  44790. */
  44791. get: function () {
  44792. return this._position;
  44793. },
  44794. /**
  44795. * Sets the position the shadow will be casted from. Also use as the light position for both
  44796. * point and spot lights.
  44797. */
  44798. set: function (value) {
  44799. this._setPosition(value);
  44800. },
  44801. enumerable: true,
  44802. configurable: true
  44803. });
  44804. ShadowLight.prototype._setDirection = function (value) {
  44805. this._direction = value;
  44806. };
  44807. Object.defineProperty(ShadowLight.prototype, "direction", {
  44808. /**
  44809. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  44810. * Also use as the light direction on spot and directional lights.
  44811. */
  44812. get: function () {
  44813. return this._direction;
  44814. },
  44815. /**
  44816. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  44817. * Also use as the light direction on spot and directional lights.
  44818. */
  44819. set: function (value) {
  44820. this._setDirection(value);
  44821. },
  44822. enumerable: true,
  44823. configurable: true
  44824. });
  44825. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  44826. /**
  44827. * Gets the shadow projection clipping minimum z value.
  44828. */
  44829. get: function () {
  44830. return this._shadowMinZ;
  44831. },
  44832. /**
  44833. * Sets the shadow projection clipping minimum z value.
  44834. */
  44835. set: function (value) {
  44836. this._shadowMinZ = value;
  44837. this.forceProjectionMatrixCompute();
  44838. },
  44839. enumerable: true,
  44840. configurable: true
  44841. });
  44842. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  44843. /**
  44844. * Sets the shadow projection clipping maximum z value.
  44845. */
  44846. get: function () {
  44847. return this._shadowMaxZ;
  44848. },
  44849. /**
  44850. * Gets the shadow projection clipping maximum z value.
  44851. */
  44852. set: function (value) {
  44853. this._shadowMaxZ = value;
  44854. this.forceProjectionMatrixCompute();
  44855. },
  44856. enumerable: true,
  44857. configurable: true
  44858. });
  44859. /**
  44860. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  44861. * @returns true if the information has been computed, false if it does not need to (no parenting)
  44862. */
  44863. ShadowLight.prototype.computeTransformedInformation = function () {
  44864. if (this.parent && this.parent.getWorldMatrix) {
  44865. if (!this.transformedPosition) {
  44866. this.transformedPosition = BABYLON.Vector3.Zero();
  44867. }
  44868. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  44869. // In case the direction is present.
  44870. if (this.direction) {
  44871. if (!this.transformedDirection) {
  44872. this.transformedDirection = BABYLON.Vector3.Zero();
  44873. }
  44874. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  44875. }
  44876. return true;
  44877. }
  44878. return false;
  44879. };
  44880. /**
  44881. * Return the depth scale used for the shadow map.
  44882. * @returns the depth scale.
  44883. */
  44884. ShadowLight.prototype.getDepthScale = function () {
  44885. return 50.0;
  44886. };
  44887. /**
  44888. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  44889. * @param faceIndex The index of the face we are computed the direction to generate shadow
  44890. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  44891. */
  44892. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  44893. return this.transformedDirection ? this.transformedDirection : this.direction;
  44894. };
  44895. /**
  44896. * Returns the ShadowLight absolute position in the World.
  44897. * @returns the position vector in world space
  44898. */
  44899. ShadowLight.prototype.getAbsolutePosition = function () {
  44900. return this.transformedPosition ? this.transformedPosition : this.position;
  44901. };
  44902. /**
  44903. * Sets the ShadowLight direction toward the passed target.
  44904. * @param target The point tot target in local space
  44905. * @returns the updated ShadowLight direction
  44906. */
  44907. ShadowLight.prototype.setDirectionToTarget = function (target) {
  44908. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  44909. return this.direction;
  44910. };
  44911. /**
  44912. * Returns the light rotation in euler definition.
  44913. * @returns the x y z rotation in local space.
  44914. */
  44915. ShadowLight.prototype.getRotation = function () {
  44916. this.direction.normalize();
  44917. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  44918. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  44919. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  44920. };
  44921. /**
  44922. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  44923. * @returns true if a cube texture needs to be use
  44924. */
  44925. ShadowLight.prototype.needCube = function () {
  44926. return false;
  44927. };
  44928. /**
  44929. * Detects if the projection matrix requires to be recomputed this frame.
  44930. * @returns true if it requires to be recomputed otherwise, false.
  44931. */
  44932. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  44933. return this._needProjectionMatrixCompute;
  44934. };
  44935. /**
  44936. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  44937. */
  44938. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  44939. this._needProjectionMatrixCompute = true;
  44940. };
  44941. /**
  44942. * Get the world matrix of the sahdow lights.
  44943. * @ignore Internal Use Only
  44944. */
  44945. ShadowLight.prototype._getWorldMatrix = function () {
  44946. if (!this._worldMatrix) {
  44947. this._worldMatrix = BABYLON.Matrix.Identity();
  44948. }
  44949. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  44950. return this._worldMatrix;
  44951. };
  44952. /**
  44953. * Gets the minZ used for shadow according to both the scene and the light.
  44954. * @param activeCamera The camera we are returning the min for
  44955. * @returns the depth min z
  44956. */
  44957. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  44958. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  44959. };
  44960. /**
  44961. * Gets the maxZ used for shadow according to both the scene and the light.
  44962. * @param activeCamera The camera we are returning the max for
  44963. * @returns the depth max z
  44964. */
  44965. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  44966. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  44967. };
  44968. /**
  44969. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  44970. * @param matrix The materix to updated with the projection information
  44971. * @param viewMatrix The transform matrix of the light
  44972. * @param renderList The list of mesh to render in the map
  44973. * @returns The current light
  44974. */
  44975. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  44976. if (this.customProjectionMatrixBuilder) {
  44977. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  44978. }
  44979. else {
  44980. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  44981. }
  44982. return this;
  44983. };
  44984. __decorate([
  44985. BABYLON.serializeAsVector3()
  44986. ], ShadowLight.prototype, "position", null);
  44987. __decorate([
  44988. BABYLON.serializeAsVector3()
  44989. ], ShadowLight.prototype, "direction", null);
  44990. __decorate([
  44991. BABYLON.serialize()
  44992. ], ShadowLight.prototype, "shadowMinZ", null);
  44993. __decorate([
  44994. BABYLON.serialize()
  44995. ], ShadowLight.prototype, "shadowMaxZ", null);
  44996. return ShadowLight;
  44997. }(BABYLON.Light));
  44998. BABYLON.ShadowLight = ShadowLight;
  44999. })(BABYLON || (BABYLON = {}));
  45000. //# sourceMappingURL=babylon.shadowLight.js.map
  45001. var BABYLON;
  45002. (function (BABYLON) {
  45003. /**
  45004. * A point light is a light defined by an unique point in world space.
  45005. * The light is emitted in every direction from this point.
  45006. * A good example of a point light is a standard light bulb.
  45007. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45008. */
  45009. var PointLight = /** @class */ (function (_super) {
  45010. __extends(PointLight, _super);
  45011. /**
  45012. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  45013. * A PointLight emits the light in every direction.
  45014. * It can cast shadows.
  45015. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  45016. * ```javascript
  45017. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  45018. * ```
  45019. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45020. * @param name The light friendly name
  45021. * @param position The position of the point light in the scene
  45022. * @param scene The scene the lights belongs to
  45023. */
  45024. function PointLight(name, position, scene) {
  45025. var _this = _super.call(this, name, scene) || this;
  45026. _this._shadowAngle = Math.PI / 2;
  45027. _this.position = position;
  45028. return _this;
  45029. }
  45030. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  45031. /**
  45032. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45033. * This specifies what angle the shadow will use to be created.
  45034. *
  45035. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45036. */
  45037. get: function () {
  45038. return this._shadowAngle;
  45039. },
  45040. /**
  45041. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45042. * This specifies what angle the shadow will use to be created.
  45043. *
  45044. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  45045. */
  45046. set: function (value) {
  45047. this._shadowAngle = value;
  45048. this.forceProjectionMatrixCompute();
  45049. },
  45050. enumerable: true,
  45051. configurable: true
  45052. });
  45053. Object.defineProperty(PointLight.prototype, "direction", {
  45054. /**
  45055. * Gets the direction if it has been set.
  45056. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45057. */
  45058. get: function () {
  45059. return this._direction;
  45060. },
  45061. /**
  45062. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  45063. */
  45064. set: function (value) {
  45065. var previousNeedCube = this.needCube();
  45066. this._direction = value;
  45067. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  45068. this._shadowGenerator.recreateShadowMap();
  45069. }
  45070. },
  45071. enumerable: true,
  45072. configurable: true
  45073. });
  45074. /**
  45075. * Returns the string "PointLight"
  45076. * @returns the class name
  45077. */
  45078. PointLight.prototype.getClassName = function () {
  45079. return "PointLight";
  45080. };
  45081. /**
  45082. * Returns the integer 0.
  45083. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45084. */
  45085. PointLight.prototype.getTypeID = function () {
  45086. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  45087. };
  45088. /**
  45089. * Specifies wether or not the shadowmap should be a cube texture.
  45090. * @returns true if the shadowmap needs to be a cube texture.
  45091. */
  45092. PointLight.prototype.needCube = function () {
  45093. return !this.direction;
  45094. };
  45095. /**
  45096. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  45097. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45098. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45099. */
  45100. PointLight.prototype.getShadowDirection = function (faceIndex) {
  45101. if (this.direction) {
  45102. return _super.prototype.getShadowDirection.call(this, faceIndex);
  45103. }
  45104. else {
  45105. switch (faceIndex) {
  45106. case 0:
  45107. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  45108. case 1:
  45109. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  45110. case 2:
  45111. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  45112. case 3:
  45113. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  45114. case 4:
  45115. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  45116. case 5:
  45117. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  45118. }
  45119. }
  45120. return BABYLON.Vector3.Zero();
  45121. };
  45122. /**
  45123. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  45124. * - fov = PI / 2
  45125. * - aspect ratio : 1.0
  45126. * - z-near and far equal to the active camera minZ and maxZ.
  45127. * Returns the PointLight.
  45128. */
  45129. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45130. var activeCamera = this.getScene().activeCamera;
  45131. if (!activeCamera) {
  45132. return;
  45133. }
  45134. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45135. };
  45136. PointLight.prototype._buildUniformLayout = function () {
  45137. this._uniformBuffer.addUniform("vLightData", 4);
  45138. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45139. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45140. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45141. this._uniformBuffer.addUniform("depthValues", 2);
  45142. this._uniformBuffer.create();
  45143. };
  45144. /**
  45145. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  45146. * @param effect The effect to update
  45147. * @param lightIndex The index of the light in the effect to update
  45148. * @returns The point light
  45149. */
  45150. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  45151. if (this.computeTransformedInformation()) {
  45152. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  45153. return this;
  45154. }
  45155. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  45156. return this;
  45157. };
  45158. __decorate([
  45159. BABYLON.serialize()
  45160. ], PointLight.prototype, "shadowAngle", null);
  45161. return PointLight;
  45162. }(BABYLON.ShadowLight));
  45163. BABYLON.PointLight = PointLight;
  45164. })(BABYLON || (BABYLON = {}));
  45165. //# sourceMappingURL=babylon.pointLight.js.map
  45166. var BABYLON;
  45167. (function (BABYLON) {
  45168. /**
  45169. * A directional light is defined by a direction (what a surprise!).
  45170. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  45171. * 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.
  45172. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45173. */
  45174. var DirectionalLight = /** @class */ (function (_super) {
  45175. __extends(DirectionalLight, _super);
  45176. /**
  45177. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  45178. * The directional light is emitted from everywhere in the given direction.
  45179. * It can cast shawdows.
  45180. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45181. * @param name The friendly name of the light
  45182. * @param direction The direction of the light
  45183. * @param scene The scene the light belongs to
  45184. */
  45185. function DirectionalLight(name, direction, scene) {
  45186. var _this = _super.call(this, name, scene) || this;
  45187. _this._shadowFrustumSize = 0;
  45188. _this._shadowOrthoScale = 0.5;
  45189. /**
  45190. * Automatically compute the projection matrix to best fit (including all the casters)
  45191. * on each frame.
  45192. */
  45193. _this.autoUpdateExtends = true;
  45194. // Cache
  45195. _this._orthoLeft = Number.MAX_VALUE;
  45196. _this._orthoRight = Number.MIN_VALUE;
  45197. _this._orthoTop = Number.MIN_VALUE;
  45198. _this._orthoBottom = Number.MAX_VALUE;
  45199. _this.position = direction.scale(-1.0);
  45200. _this.direction = direction;
  45201. return _this;
  45202. }
  45203. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  45204. /**
  45205. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  45206. */
  45207. get: function () {
  45208. return this._shadowFrustumSize;
  45209. },
  45210. /**
  45211. * Specifies a fix frustum size for the shadow generation.
  45212. */
  45213. set: function (value) {
  45214. this._shadowFrustumSize = value;
  45215. this.forceProjectionMatrixCompute();
  45216. },
  45217. enumerable: true,
  45218. configurable: true
  45219. });
  45220. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  45221. /**
  45222. * Gets the shadow projection scale against the optimal computed one.
  45223. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45224. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45225. */
  45226. get: function () {
  45227. return this._shadowOrthoScale;
  45228. },
  45229. /**
  45230. * Sets the shadow projection scale against the optimal computed one.
  45231. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  45232. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  45233. */
  45234. set: function (value) {
  45235. this._shadowOrthoScale = value;
  45236. this.forceProjectionMatrixCompute();
  45237. },
  45238. enumerable: true,
  45239. configurable: true
  45240. });
  45241. /**
  45242. * Returns the string "DirectionalLight".
  45243. * @return The class name
  45244. */
  45245. DirectionalLight.prototype.getClassName = function () {
  45246. return "DirectionalLight";
  45247. };
  45248. /**
  45249. * Returns the integer 1.
  45250. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45251. */
  45252. DirectionalLight.prototype.getTypeID = function () {
  45253. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  45254. };
  45255. /**
  45256. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  45257. * Returns the DirectionalLight Shadow projection matrix.
  45258. */
  45259. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45260. if (this.shadowFrustumSize > 0) {
  45261. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  45262. }
  45263. else {
  45264. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  45265. }
  45266. };
  45267. /**
  45268. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  45269. * Returns the DirectionalLight Shadow projection matrix.
  45270. */
  45271. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  45272. var activeCamera = this.getScene().activeCamera;
  45273. if (!activeCamera) {
  45274. return;
  45275. }
  45276. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  45277. };
  45278. /**
  45279. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  45280. * Returns the DirectionalLight Shadow projection matrix.
  45281. */
  45282. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45283. var activeCamera = this.getScene().activeCamera;
  45284. if (!activeCamera) {
  45285. return;
  45286. }
  45287. // Check extends
  45288. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  45289. var tempVector3 = BABYLON.Vector3.Zero();
  45290. this._orthoLeft = Number.MAX_VALUE;
  45291. this._orthoRight = Number.MIN_VALUE;
  45292. this._orthoTop = Number.MIN_VALUE;
  45293. this._orthoBottom = Number.MAX_VALUE;
  45294. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  45295. var mesh = renderList[meshIndex];
  45296. if (!mesh) {
  45297. continue;
  45298. }
  45299. var boundingInfo = mesh.getBoundingInfo();
  45300. var boundingBox = boundingInfo.boundingBox;
  45301. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  45302. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  45303. if (tempVector3.x < this._orthoLeft)
  45304. this._orthoLeft = tempVector3.x;
  45305. if (tempVector3.y < this._orthoBottom)
  45306. this._orthoBottom = tempVector3.y;
  45307. if (tempVector3.x > this._orthoRight)
  45308. this._orthoRight = tempVector3.x;
  45309. if (tempVector3.y > this._orthoTop)
  45310. this._orthoTop = tempVector3.y;
  45311. }
  45312. }
  45313. }
  45314. var xOffset = this._orthoRight - this._orthoLeft;
  45315. var yOffset = this._orthoTop - this._orthoBottom;
  45316. 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);
  45317. };
  45318. DirectionalLight.prototype._buildUniformLayout = function () {
  45319. this._uniformBuffer.addUniform("vLightData", 4);
  45320. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45321. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45322. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45323. this._uniformBuffer.addUniform("depthValues", 2);
  45324. this._uniformBuffer.create();
  45325. };
  45326. /**
  45327. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  45328. * @param effect The effect to update
  45329. * @param lightIndex The index of the light in the effect to update
  45330. * @returns The directional light
  45331. */
  45332. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  45333. if (this.computeTransformedInformation()) {
  45334. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  45335. return this;
  45336. }
  45337. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  45338. return this;
  45339. };
  45340. /**
  45341. * Gets the minZ used for shadow according to both the scene and the light.
  45342. *
  45343. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45344. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45345. * @param activeCamera The camera we are returning the min for
  45346. * @returns the depth min z
  45347. */
  45348. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  45349. return 1;
  45350. };
  45351. /**
  45352. * Gets the maxZ used for shadow according to both the scene and the light.
  45353. *
  45354. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  45355. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  45356. * @param activeCamera The camera we are returning the max for
  45357. * @returns the depth max z
  45358. */
  45359. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  45360. return 1;
  45361. };
  45362. __decorate([
  45363. BABYLON.serialize()
  45364. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  45365. __decorate([
  45366. BABYLON.serialize()
  45367. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  45368. __decorate([
  45369. BABYLON.serialize()
  45370. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  45371. return DirectionalLight;
  45372. }(BABYLON.ShadowLight));
  45373. BABYLON.DirectionalLight = DirectionalLight;
  45374. })(BABYLON || (BABYLON = {}));
  45375. //# sourceMappingURL=babylon.directionalLight.js.map
  45376. var BABYLON;
  45377. (function (BABYLON) {
  45378. /**
  45379. * A spot light is defined by a position, a direction, an angle, and an exponent.
  45380. * These values define a cone of light starting from the position, emitting toward the direction.
  45381. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  45382. * and the exponent defines the speed of the decay of the light with distance (reach).
  45383. * Documentation: https://doc.babylonjs.com/babylon101/lights
  45384. */
  45385. var SpotLight = /** @class */ (function (_super) {
  45386. __extends(SpotLight, _super);
  45387. /**
  45388. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  45389. * It can cast shadows.
  45390. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45391. * @param name The light friendly name
  45392. * @param position The position of the spot light in the scene
  45393. * @param direction The direction of the light in the scene
  45394. * @param angle The cone angle of the light in Radians
  45395. * @param exponent The light decay speed with the distance from the emission spot
  45396. * @param scene The scene the lights belongs to
  45397. */
  45398. function SpotLight(name, position, direction, angle, exponent, scene) {
  45399. var _this = _super.call(this, name, scene) || this;
  45400. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  45401. _this._projectionTextureLightNear = 1e-6;
  45402. _this._projectionTextureLightFar = 1000.0;
  45403. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  45404. _this._projectionTextureViewLightDirty = true;
  45405. _this._projectionTextureProjectionLightDirty = true;
  45406. _this._projectionTextureDirty = true;
  45407. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  45408. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  45409. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  45410. _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);
  45411. _this.position = position;
  45412. _this.direction = direction;
  45413. _this.angle = angle;
  45414. _this.exponent = exponent;
  45415. return _this;
  45416. }
  45417. Object.defineProperty(SpotLight.prototype, "angle", {
  45418. /**
  45419. * Gets the cone angle of the spot light in Radians.
  45420. */
  45421. get: function () {
  45422. return this._angle;
  45423. },
  45424. /**
  45425. * Sets the cone angle of the spot light in Radians.
  45426. */
  45427. set: function (value) {
  45428. this._angle = value;
  45429. this._projectionTextureProjectionLightDirty = true;
  45430. this.forceProjectionMatrixCompute();
  45431. },
  45432. enumerable: true,
  45433. configurable: true
  45434. });
  45435. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  45436. /**
  45437. * Allows scaling the angle of the light for shadow generation only.
  45438. */
  45439. get: function () {
  45440. return this._shadowAngleScale;
  45441. },
  45442. /**
  45443. * Allows scaling the angle of the light for shadow generation only.
  45444. */
  45445. set: function (value) {
  45446. this._shadowAngleScale = value;
  45447. this.forceProjectionMatrixCompute();
  45448. },
  45449. enumerable: true,
  45450. configurable: true
  45451. });
  45452. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  45453. /**
  45454. * Allows reading the projecton texture
  45455. */
  45456. get: function () {
  45457. return this._projectionTextureMatrix;
  45458. },
  45459. enumerable: true,
  45460. configurable: true
  45461. });
  45462. ;
  45463. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  45464. /**
  45465. * Gets the near clip of the Spotlight for texture projection.
  45466. */
  45467. get: function () {
  45468. return this._projectionTextureLightNear;
  45469. },
  45470. /**
  45471. * Sets the near clip of the Spotlight for texture projection.
  45472. */
  45473. set: function (value) {
  45474. this._projectionTextureLightNear = value;
  45475. this._projectionTextureProjectionLightDirty = true;
  45476. },
  45477. enumerable: true,
  45478. configurable: true
  45479. });
  45480. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  45481. /**
  45482. * Gets the far clip of the Spotlight for texture projection.
  45483. */
  45484. get: function () {
  45485. return this._projectionTextureLightFar;
  45486. },
  45487. /**
  45488. * Sets the far clip of the Spotlight for texture projection.
  45489. */
  45490. set: function (value) {
  45491. this._projectionTextureLightFar = value;
  45492. this._projectionTextureProjectionLightDirty = true;
  45493. },
  45494. enumerable: true,
  45495. configurable: true
  45496. });
  45497. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  45498. /**
  45499. * Gets the Up vector of the Spotlight for texture projection.
  45500. */
  45501. get: function () {
  45502. return this._projectionTextureUpDirection;
  45503. },
  45504. /**
  45505. * Sets the Up vector of the Spotlight for texture projection.
  45506. */
  45507. set: function (value) {
  45508. this._projectionTextureUpDirection = value;
  45509. this._projectionTextureProjectionLightDirty = true;
  45510. },
  45511. enumerable: true,
  45512. configurable: true
  45513. });
  45514. ;
  45515. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  45516. /**
  45517. * Gets the projection texture of the light.
  45518. */
  45519. get: function () {
  45520. return this._projectionTexture;
  45521. },
  45522. /**
  45523. * Sets the projection texture of the light.
  45524. */
  45525. set: function (value) {
  45526. this._projectionTexture = value;
  45527. this._projectionTextureDirty = true;
  45528. },
  45529. enumerable: true,
  45530. configurable: true
  45531. });
  45532. /**
  45533. * Returns the string "SpotLight".
  45534. * @returns the class name
  45535. */
  45536. SpotLight.prototype.getClassName = function () {
  45537. return "SpotLight";
  45538. };
  45539. /**
  45540. * Returns the integer 2.
  45541. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45542. */
  45543. SpotLight.prototype.getTypeID = function () {
  45544. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  45545. };
  45546. /**
  45547. * Overrides the direction setter to recompute the projection texture view light Matrix.
  45548. */
  45549. SpotLight.prototype._setDirection = function (value) {
  45550. _super.prototype._setDirection.call(this, value);
  45551. this._projectionTextureViewLightDirty = true;
  45552. };
  45553. /**
  45554. * Overrides the position setter to recompute the projection texture view light Matrix.
  45555. */
  45556. SpotLight.prototype._setPosition = function (value) {
  45557. _super.prototype._setPosition.call(this, value);
  45558. this._projectionTextureViewLightDirty = true;
  45559. };
  45560. /**
  45561. * 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.
  45562. * Returns the SpotLight.
  45563. */
  45564. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  45565. var activeCamera = this.getScene().activeCamera;
  45566. if (!activeCamera) {
  45567. return;
  45568. }
  45569. this._shadowAngleScale = this._shadowAngleScale || 1;
  45570. var angle = this._shadowAngleScale * this._angle;
  45571. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  45572. };
  45573. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  45574. this._projectionTextureViewLightDirty = false;
  45575. this._projectionTextureDirty = true;
  45576. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  45577. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  45578. };
  45579. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  45580. this._projectionTextureProjectionLightDirty = false;
  45581. this._projectionTextureDirty = true;
  45582. var light_far = this.projectionTextureLightFar;
  45583. var light_near = this.projectionTextureLightNear;
  45584. var P = light_far / (light_far - light_near);
  45585. var Q = -P * light_near;
  45586. var S = 1.0 / Math.tan(this._angle / 2.0);
  45587. var A = 1.0;
  45588. 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);
  45589. };
  45590. /**
  45591. * Main function for light texture projection matrix computing.
  45592. */
  45593. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  45594. this._projectionTextureDirty = false;
  45595. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  45596. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  45597. };
  45598. SpotLight.prototype._buildUniformLayout = function () {
  45599. this._uniformBuffer.addUniform("vLightData", 4);
  45600. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45601. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45602. this._uniformBuffer.addUniform("vLightDirection", 3);
  45603. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45604. this._uniformBuffer.addUniform("depthValues", 2);
  45605. this._uniformBuffer.create();
  45606. };
  45607. /**
  45608. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  45609. * @param effect The effect to update
  45610. * @param lightIndex The index of the light in the effect to update
  45611. * @returns The spot light
  45612. */
  45613. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  45614. var normalizeDirection;
  45615. if (this.computeTransformedInformation()) {
  45616. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  45617. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  45618. }
  45619. else {
  45620. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  45621. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45622. }
  45623. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  45624. if (this.projectionTexture && this.projectionTexture.isReady()) {
  45625. if (this._projectionTextureViewLightDirty) {
  45626. this._computeProjectionTextureViewLightMatrix();
  45627. }
  45628. if (this._projectionTextureProjectionLightDirty) {
  45629. this._computeProjectionTextureProjectionLightMatrix();
  45630. }
  45631. if (this._projectionTextureDirty) {
  45632. this._computeProjectionTextureMatrix();
  45633. }
  45634. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  45635. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  45636. }
  45637. return this;
  45638. };
  45639. /**
  45640. * Disposes the light and the associated resources.
  45641. */
  45642. SpotLight.prototype.dispose = function () {
  45643. _super.prototype.dispose.call(this);
  45644. if (this._projectionTexture) {
  45645. this._projectionTexture.dispose();
  45646. }
  45647. };
  45648. __decorate([
  45649. BABYLON.serialize()
  45650. ], SpotLight.prototype, "angle", null);
  45651. __decorate([
  45652. BABYLON.serialize()
  45653. ], SpotLight.prototype, "shadowAngleScale", null);
  45654. __decorate([
  45655. BABYLON.serialize()
  45656. ], SpotLight.prototype, "exponent", void 0);
  45657. __decorate([
  45658. BABYLON.serialize()
  45659. ], SpotLight.prototype, "projectionTextureLightNear", null);
  45660. __decorate([
  45661. BABYLON.serialize()
  45662. ], SpotLight.prototype, "projectionTextureLightFar", null);
  45663. __decorate([
  45664. BABYLON.serialize()
  45665. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  45666. __decorate([
  45667. BABYLON.serializeAsTexture("projectedLightTexture")
  45668. ], SpotLight.prototype, "_projectionTexture", void 0);
  45669. return SpotLight;
  45670. }(BABYLON.ShadowLight));
  45671. BABYLON.SpotLight = SpotLight;
  45672. })(BABYLON || (BABYLON = {}));
  45673. //# sourceMappingURL=babylon.spotLight.js.map
  45674. var BABYLON;
  45675. (function (BABYLON) {
  45676. var AnimationRange = /** @class */ (function () {
  45677. function AnimationRange(name, from, to) {
  45678. this.name = name;
  45679. this.from = from;
  45680. this.to = to;
  45681. }
  45682. AnimationRange.prototype.clone = function () {
  45683. return new AnimationRange(this.name, this.from, this.to);
  45684. };
  45685. return AnimationRange;
  45686. }());
  45687. BABYLON.AnimationRange = AnimationRange;
  45688. /**
  45689. * Composed of a frame, and an action function
  45690. */
  45691. var AnimationEvent = /** @class */ (function () {
  45692. function AnimationEvent(frame, action, onlyOnce) {
  45693. this.frame = frame;
  45694. this.action = action;
  45695. this.onlyOnce = onlyOnce;
  45696. this.isDone = false;
  45697. }
  45698. return AnimationEvent;
  45699. }());
  45700. BABYLON.AnimationEvent = AnimationEvent;
  45701. var PathCursor = /** @class */ (function () {
  45702. function PathCursor(path) {
  45703. this.path = path;
  45704. this._onchange = new Array();
  45705. this.value = 0;
  45706. this.animations = new Array();
  45707. }
  45708. PathCursor.prototype.getPoint = function () {
  45709. var point = this.path.getPointAtLengthPosition(this.value);
  45710. return new BABYLON.Vector3(point.x, 0, point.y);
  45711. };
  45712. PathCursor.prototype.moveAhead = function (step) {
  45713. if (step === void 0) { step = 0.002; }
  45714. this.move(step);
  45715. return this;
  45716. };
  45717. PathCursor.prototype.moveBack = function (step) {
  45718. if (step === void 0) { step = 0.002; }
  45719. this.move(-step);
  45720. return this;
  45721. };
  45722. PathCursor.prototype.move = function (step) {
  45723. if (Math.abs(step) > 1) {
  45724. throw "step size should be less than 1.";
  45725. }
  45726. this.value += step;
  45727. this.ensureLimits();
  45728. this.raiseOnChange();
  45729. return this;
  45730. };
  45731. PathCursor.prototype.ensureLimits = function () {
  45732. while (this.value > 1) {
  45733. this.value -= 1;
  45734. }
  45735. while (this.value < 0) {
  45736. this.value += 1;
  45737. }
  45738. return this;
  45739. };
  45740. // used by animation engine
  45741. PathCursor.prototype.raiseOnChange = function () {
  45742. var _this = this;
  45743. this._onchange.forEach(function (f) { return f(_this); });
  45744. return this;
  45745. };
  45746. PathCursor.prototype.onchange = function (f) {
  45747. this._onchange.push(f);
  45748. return this;
  45749. };
  45750. return PathCursor;
  45751. }());
  45752. BABYLON.PathCursor = PathCursor;
  45753. var AnimationKeyInterpolation;
  45754. (function (AnimationKeyInterpolation) {
  45755. /**
  45756. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  45757. */
  45758. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  45759. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  45760. var Animation = /** @class */ (function () {
  45761. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  45762. this.name = name;
  45763. this.targetProperty = targetProperty;
  45764. this.framePerSecond = framePerSecond;
  45765. this.dataType = dataType;
  45766. this.loopMode = loopMode;
  45767. this.enableBlending = enableBlending;
  45768. this._runtimeAnimations = new Array();
  45769. // The set of event that will be linked to this animation
  45770. this._events = new Array();
  45771. this.blendingSpeed = 0.01;
  45772. this._ranges = {};
  45773. this.targetPropertyPath = targetProperty.split(".");
  45774. this.dataType = dataType;
  45775. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  45776. }
  45777. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  45778. var dataType = undefined;
  45779. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  45780. dataType = Animation.ANIMATIONTYPE_FLOAT;
  45781. }
  45782. else if (from instanceof BABYLON.Quaternion) {
  45783. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  45784. }
  45785. else if (from instanceof BABYLON.Vector3) {
  45786. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  45787. }
  45788. else if (from instanceof BABYLON.Vector2) {
  45789. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  45790. }
  45791. else if (from instanceof BABYLON.Color3) {
  45792. dataType = Animation.ANIMATIONTYPE_COLOR3;
  45793. }
  45794. else if (from instanceof BABYLON.Size) {
  45795. dataType = Animation.ANIMATIONTYPE_SIZE;
  45796. }
  45797. if (dataType == undefined) {
  45798. return null;
  45799. }
  45800. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  45801. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  45802. animation.setKeys(keys);
  45803. if (easingFunction !== undefined) {
  45804. animation.setEasingFunction(easingFunction);
  45805. }
  45806. return animation;
  45807. };
  45808. /**
  45809. * Sets up an animation.
  45810. * @param property the property to animate
  45811. * @param animationType the animation type to apply
  45812. * @param easingFunction the easing function used in the animation
  45813. * @returns The created animation
  45814. */
  45815. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  45816. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  45817. animation.setEasingFunction(easingFunction);
  45818. return animation;
  45819. };
  45820. /**
  45821. * Create and start an animation on a node
  45822. * @param {string} name defines the name of the global animation that will be run on all nodes
  45823. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45824. * @param {string} targetProperty defines property to animate
  45825. * @param {number} framePerSecond defines the number of frame per second yo use
  45826. * @param {number} totalFrame defines the number of frames in total
  45827. * @param {any} from defines the initial value
  45828. * @param {any} to defines the final value
  45829. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45830. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45831. * @param onAnimationEnd defines the callback to call when animation end
  45832. * @returns the animatable created for this animation
  45833. */
  45834. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45835. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45836. if (!animation) {
  45837. return null;
  45838. }
  45839. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45840. };
  45841. /**
  45842. * Create and start an animation on a node and its descendants
  45843. * @param {string} name defines the name of the global animation that will be run on all nodes
  45844. * @param {BABYLON.Node} node defines the root node where the animation will take place
  45845. * @param {boolean} 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.
  45846. * @param {string} targetProperty defines property to animate
  45847. * @param {number} framePerSecond defines the number of frame per second yo use
  45848. * @param {number} totalFrame defines the number of frames in total
  45849. * @param {any} from defines the initial value
  45850. * @param {any} to defines the final value
  45851. * @param {number} loopMode defines which loop mode you want to use (off by default)
  45852. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  45853. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  45854. * @returns the list of animatables created for all nodes
  45855. * @example https://www.babylonjs-playground.com/#MH0VLI
  45856. */
  45857. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45858. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45859. if (!animation) {
  45860. return null;
  45861. }
  45862. var scene = node.getScene();
  45863. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45864. };
  45865. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  45866. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  45867. if (!animation) {
  45868. return null;
  45869. }
  45870. node.animations.push(animation);
  45871. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  45872. };
  45873. /**
  45874. * Transition property of the Camera to the target Value.
  45875. * @param property The property to transition
  45876. * @param targetValue The target Value of the property
  45877. * @param host The object where the property to animate belongs
  45878. * @param scene Scene used to run the animation
  45879. * @param frameRate Framerate (in frame/s) to use
  45880. * @param transition The transition type we want to use
  45881. * @param duration The duration of the animation, in milliseconds
  45882. * @param onAnimationEnd Call back trigger at the end of the animation.
  45883. */
  45884. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  45885. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  45886. if (duration <= 0) {
  45887. host[property] = targetValue;
  45888. if (onAnimationEnd) {
  45889. onAnimationEnd();
  45890. }
  45891. return null;
  45892. }
  45893. var endFrame = frameRate * (duration / 1000);
  45894. transition.setKeys([{
  45895. frame: 0,
  45896. value: host[property].clone ? host[property].clone() : host[property]
  45897. },
  45898. {
  45899. frame: endFrame,
  45900. value: targetValue
  45901. }]);
  45902. if (!host.animations) {
  45903. host.animations = [];
  45904. }
  45905. host.animations.push(transition);
  45906. var animation = scene.beginAnimation(host, 0, endFrame, false);
  45907. animation.onAnimationEnd = onAnimationEnd;
  45908. return animation;
  45909. };
  45910. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  45911. /**
  45912. * Return the array of runtime animations currently using this animation
  45913. */
  45914. get: function () {
  45915. return this._runtimeAnimations;
  45916. },
  45917. enumerable: true,
  45918. configurable: true
  45919. });
  45920. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  45921. get: function () {
  45922. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  45923. var runtimeAnimation = _a[_i];
  45924. if (!runtimeAnimation.isStopped) {
  45925. return true;
  45926. }
  45927. }
  45928. return false;
  45929. },
  45930. enumerable: true,
  45931. configurable: true
  45932. });
  45933. // Methods
  45934. /**
  45935. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  45936. */
  45937. Animation.prototype.toString = function (fullDetails) {
  45938. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  45939. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  45940. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  45941. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  45942. if (fullDetails) {
  45943. ret += ", Ranges: {";
  45944. var first = true;
  45945. for (var name in this._ranges) {
  45946. if (first) {
  45947. ret += ", ";
  45948. first = false;
  45949. }
  45950. ret += name;
  45951. }
  45952. ret += "}";
  45953. }
  45954. return ret;
  45955. };
  45956. /**
  45957. * Add an event to this animation.
  45958. */
  45959. Animation.prototype.addEvent = function (event) {
  45960. this._events.push(event);
  45961. };
  45962. /**
  45963. * Remove all events found at the given frame
  45964. * @param frame
  45965. */
  45966. Animation.prototype.removeEvents = function (frame) {
  45967. for (var index = 0; index < this._events.length; index++) {
  45968. if (this._events[index].frame === frame) {
  45969. this._events.splice(index, 1);
  45970. index--;
  45971. }
  45972. }
  45973. };
  45974. Animation.prototype.getEvents = function () {
  45975. return this._events;
  45976. };
  45977. Animation.prototype.createRange = function (name, from, to) {
  45978. // check name not already in use; could happen for bones after serialized
  45979. if (!this._ranges[name]) {
  45980. this._ranges[name] = new AnimationRange(name, from, to);
  45981. }
  45982. };
  45983. Animation.prototype.deleteRange = function (name, deleteFrames) {
  45984. if (deleteFrames === void 0) { deleteFrames = true; }
  45985. var range = this._ranges[name];
  45986. if (!range) {
  45987. return;
  45988. }
  45989. if (deleteFrames) {
  45990. var from = range.from;
  45991. var to = range.to;
  45992. // this loop MUST go high to low for multiple splices to work
  45993. for (var key = this._keys.length - 1; key >= 0; key--) {
  45994. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  45995. this._keys.splice(key, 1);
  45996. }
  45997. }
  45998. }
  45999. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  46000. };
  46001. Animation.prototype.getRange = function (name) {
  46002. return this._ranges[name];
  46003. };
  46004. Animation.prototype.getKeys = function () {
  46005. return this._keys;
  46006. };
  46007. Animation.prototype.getHighestFrame = function () {
  46008. var ret = 0;
  46009. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  46010. if (ret < this._keys[key].frame) {
  46011. ret = this._keys[key].frame;
  46012. }
  46013. }
  46014. return ret;
  46015. };
  46016. Animation.prototype.getEasingFunction = function () {
  46017. return this._easingFunction;
  46018. };
  46019. Animation.prototype.setEasingFunction = function (easingFunction) {
  46020. this._easingFunction = easingFunction;
  46021. };
  46022. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  46023. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  46024. };
  46025. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46026. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46027. };
  46028. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  46029. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  46030. };
  46031. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46032. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  46033. };
  46034. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  46035. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  46036. };
  46037. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46038. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46039. };
  46040. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  46041. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  46042. };
  46043. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  46044. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  46045. };
  46046. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  46047. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  46048. };
  46049. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  46050. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  46051. };
  46052. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  46053. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  46054. };
  46055. Animation.prototype.clone = function () {
  46056. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  46057. clone.enableBlending = this.enableBlending;
  46058. clone.blendingSpeed = this.blendingSpeed;
  46059. if (this._keys) {
  46060. clone.setKeys(this._keys);
  46061. }
  46062. if (this._ranges) {
  46063. clone._ranges = {};
  46064. for (var name in this._ranges) {
  46065. var range = this._ranges[name];
  46066. if (!range) {
  46067. continue;
  46068. }
  46069. clone._ranges[name] = range.clone();
  46070. }
  46071. }
  46072. return clone;
  46073. };
  46074. Animation.prototype.setKeys = function (values) {
  46075. this._keys = values.slice(0);
  46076. };
  46077. Animation.prototype.serialize = function () {
  46078. var serializationObject = {};
  46079. serializationObject.name = this.name;
  46080. serializationObject.property = this.targetProperty;
  46081. serializationObject.framePerSecond = this.framePerSecond;
  46082. serializationObject.dataType = this.dataType;
  46083. serializationObject.loopBehavior = this.loopMode;
  46084. serializationObject.enableBlending = this.enableBlending;
  46085. serializationObject.blendingSpeed = this.blendingSpeed;
  46086. var dataType = this.dataType;
  46087. serializationObject.keys = [];
  46088. var keys = this.getKeys();
  46089. for (var index = 0; index < keys.length; index++) {
  46090. var animationKey = keys[index];
  46091. var key = {};
  46092. key.frame = animationKey.frame;
  46093. switch (dataType) {
  46094. case Animation.ANIMATIONTYPE_FLOAT:
  46095. key.values = [animationKey.value];
  46096. break;
  46097. case Animation.ANIMATIONTYPE_QUATERNION:
  46098. case Animation.ANIMATIONTYPE_MATRIX:
  46099. case Animation.ANIMATIONTYPE_VECTOR3:
  46100. case Animation.ANIMATIONTYPE_COLOR3:
  46101. key.values = animationKey.value.asArray();
  46102. break;
  46103. }
  46104. serializationObject.keys.push(key);
  46105. }
  46106. serializationObject.ranges = [];
  46107. for (var name in this._ranges) {
  46108. var source = this._ranges[name];
  46109. if (!source) {
  46110. continue;
  46111. }
  46112. var range = {};
  46113. range.name = name;
  46114. range.from = source.from;
  46115. range.to = source.to;
  46116. serializationObject.ranges.push(range);
  46117. }
  46118. return serializationObject;
  46119. };
  46120. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  46121. get: function () {
  46122. return Animation._ANIMATIONTYPE_FLOAT;
  46123. },
  46124. enumerable: true,
  46125. configurable: true
  46126. });
  46127. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  46128. get: function () {
  46129. return Animation._ANIMATIONTYPE_VECTOR3;
  46130. },
  46131. enumerable: true,
  46132. configurable: true
  46133. });
  46134. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  46135. get: function () {
  46136. return Animation._ANIMATIONTYPE_VECTOR2;
  46137. },
  46138. enumerable: true,
  46139. configurable: true
  46140. });
  46141. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  46142. get: function () {
  46143. return Animation._ANIMATIONTYPE_SIZE;
  46144. },
  46145. enumerable: true,
  46146. configurable: true
  46147. });
  46148. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  46149. get: function () {
  46150. return Animation._ANIMATIONTYPE_QUATERNION;
  46151. },
  46152. enumerable: true,
  46153. configurable: true
  46154. });
  46155. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  46156. get: function () {
  46157. return Animation._ANIMATIONTYPE_MATRIX;
  46158. },
  46159. enumerable: true,
  46160. configurable: true
  46161. });
  46162. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  46163. get: function () {
  46164. return Animation._ANIMATIONTYPE_COLOR3;
  46165. },
  46166. enumerable: true,
  46167. configurable: true
  46168. });
  46169. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  46170. get: function () {
  46171. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  46172. },
  46173. enumerable: true,
  46174. configurable: true
  46175. });
  46176. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  46177. get: function () {
  46178. return Animation._ANIMATIONLOOPMODE_CYCLE;
  46179. },
  46180. enumerable: true,
  46181. configurable: true
  46182. });
  46183. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  46184. get: function () {
  46185. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  46186. },
  46187. enumerable: true,
  46188. configurable: true
  46189. });
  46190. Animation.Parse = function (parsedAnimation) {
  46191. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  46192. var dataType = parsedAnimation.dataType;
  46193. var keys = [];
  46194. var data;
  46195. var index;
  46196. if (parsedAnimation.enableBlending) {
  46197. animation.enableBlending = parsedAnimation.enableBlending;
  46198. }
  46199. if (parsedAnimation.blendingSpeed) {
  46200. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  46201. }
  46202. for (index = 0; index < parsedAnimation.keys.length; index++) {
  46203. var key = parsedAnimation.keys[index];
  46204. var inTangent;
  46205. var outTangent;
  46206. switch (dataType) {
  46207. case Animation.ANIMATIONTYPE_FLOAT:
  46208. data = key.values[0];
  46209. if (key.values.length >= 1) {
  46210. inTangent = key.values[1];
  46211. }
  46212. if (key.values.length >= 2) {
  46213. outTangent = key.values[2];
  46214. }
  46215. break;
  46216. case Animation.ANIMATIONTYPE_QUATERNION:
  46217. data = BABYLON.Quaternion.FromArray(key.values);
  46218. if (key.values.length >= 8) {
  46219. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  46220. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  46221. inTangent = _inTangent;
  46222. }
  46223. }
  46224. if (key.values.length >= 12) {
  46225. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  46226. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  46227. outTangent = _outTangent;
  46228. }
  46229. }
  46230. break;
  46231. case Animation.ANIMATIONTYPE_MATRIX:
  46232. data = BABYLON.Matrix.FromArray(key.values);
  46233. break;
  46234. case Animation.ANIMATIONTYPE_COLOR3:
  46235. data = BABYLON.Color3.FromArray(key.values);
  46236. break;
  46237. case Animation.ANIMATIONTYPE_VECTOR3:
  46238. default:
  46239. data = BABYLON.Vector3.FromArray(key.values);
  46240. break;
  46241. }
  46242. var keyData = {};
  46243. keyData.frame = key.frame;
  46244. keyData.value = data;
  46245. if (inTangent != undefined) {
  46246. keyData.inTangent = inTangent;
  46247. }
  46248. if (outTangent != undefined) {
  46249. keyData.outTangent = outTangent;
  46250. }
  46251. keys.push(keyData);
  46252. }
  46253. animation.setKeys(keys);
  46254. if (parsedAnimation.ranges) {
  46255. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  46256. data = parsedAnimation.ranges[index];
  46257. animation.createRange(data.name, data.from, data.to);
  46258. }
  46259. }
  46260. return animation;
  46261. };
  46262. Animation.AppendSerializedAnimations = function (source, destination) {
  46263. if (source.animations) {
  46264. destination.animations = [];
  46265. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  46266. var animation = source.animations[animationIndex];
  46267. destination.animations.push(animation.serialize());
  46268. }
  46269. }
  46270. };
  46271. Animation.AllowMatricesInterpolation = false;
  46272. // Statics
  46273. Animation._ANIMATIONTYPE_FLOAT = 0;
  46274. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  46275. Animation._ANIMATIONTYPE_QUATERNION = 2;
  46276. Animation._ANIMATIONTYPE_MATRIX = 3;
  46277. Animation._ANIMATIONTYPE_COLOR3 = 4;
  46278. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  46279. Animation._ANIMATIONTYPE_SIZE = 6;
  46280. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  46281. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  46282. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  46283. return Animation;
  46284. }());
  46285. BABYLON.Animation = Animation;
  46286. })(BABYLON || (BABYLON = {}));
  46287. //# sourceMappingURL=babylon.animation.js.map
  46288. var BABYLON;
  46289. (function (BABYLON) {
  46290. /**
  46291. * This class defines the direct association between an animation and a target
  46292. */
  46293. var TargetedAnimation = /** @class */ (function () {
  46294. function TargetedAnimation() {
  46295. }
  46296. return TargetedAnimation;
  46297. }());
  46298. BABYLON.TargetedAnimation = TargetedAnimation;
  46299. /**
  46300. * Use this class to create coordinated animations on multiple targets
  46301. */
  46302. var AnimationGroup = /** @class */ (function () {
  46303. function AnimationGroup(name, scene) {
  46304. if (scene === void 0) { scene = null; }
  46305. this.name = name;
  46306. this._targetedAnimations = new Array();
  46307. this._animatables = new Array();
  46308. this._from = Number.MAX_VALUE;
  46309. this._to = -Number.MAX_VALUE;
  46310. this._speedRatio = 1;
  46311. this.onAnimationEndObservable = new BABYLON.Observable();
  46312. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  46313. this._scene.animationGroups.push(this);
  46314. }
  46315. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  46316. /**
  46317. * Define if the animations are started
  46318. */
  46319. get: function () {
  46320. return this._isStarted;
  46321. },
  46322. enumerable: true,
  46323. configurable: true
  46324. });
  46325. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  46326. /**
  46327. * Gets or sets the speed ratio to use for all animations
  46328. */
  46329. get: function () {
  46330. return this._speedRatio;
  46331. },
  46332. /**
  46333. * Gets or sets the speed ratio to use for all animations
  46334. */
  46335. set: function (value) {
  46336. if (this._speedRatio === value) {
  46337. return;
  46338. }
  46339. this._speedRatio = value;
  46340. for (var index = 0; index < this._animatables.length; index++) {
  46341. var animatable = this._animatables[index];
  46342. animatable.speedRatio = this._speedRatio;
  46343. }
  46344. },
  46345. enumerable: true,
  46346. configurable: true
  46347. });
  46348. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  46349. /**
  46350. * Gets the targeted animations for this animation group
  46351. */
  46352. get: function () {
  46353. return this._targetedAnimations;
  46354. },
  46355. enumerable: true,
  46356. configurable: true
  46357. });
  46358. /**
  46359. * Add an animation (with its target) in the group
  46360. * @param animation defines the animation we want to add
  46361. * @param target defines the target of the animation
  46362. * @returns the {BABYLON.TargetedAnimation} object
  46363. */
  46364. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  46365. var targetedAnimation = {
  46366. animation: animation,
  46367. target: target
  46368. };
  46369. var keys = animation.getKeys();
  46370. if (this._from > keys[0].frame) {
  46371. this._from = keys[0].frame;
  46372. }
  46373. if (this._to < keys[keys.length - 1].frame) {
  46374. this._to = keys[keys.length - 1].frame;
  46375. }
  46376. this._targetedAnimations.push(targetedAnimation);
  46377. return targetedAnimation;
  46378. };
  46379. /**
  46380. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  46381. * It can add constant keys at begin or end
  46382. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  46383. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  46384. */
  46385. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  46386. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  46387. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  46388. beginFrame = Math.max(beginFrame, this._from);
  46389. endFrame = Math.min(endFrame, this._to);
  46390. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46391. var targetedAnimation = this._targetedAnimations[index];
  46392. var keys = targetedAnimation.animation.getKeys();
  46393. var startKey = keys[0];
  46394. var endKey = keys[keys.length - 1];
  46395. if (startKey.frame > beginFrame) {
  46396. var newKey = {
  46397. frame: beginFrame,
  46398. value: startKey.value,
  46399. inTangent: startKey.inTangent,
  46400. outTangent: startKey.outTangent,
  46401. interpolation: startKey.interpolation
  46402. };
  46403. keys.splice(0, 0, newKey);
  46404. }
  46405. if (endKey.frame < endFrame) {
  46406. var newKey = {
  46407. frame: endFrame,
  46408. value: endKey.value,
  46409. inTangent: endKey.outTangent,
  46410. outTangent: endKey.outTangent,
  46411. interpolation: endKey.interpolation
  46412. };
  46413. keys.push(newKey);
  46414. }
  46415. }
  46416. return this;
  46417. };
  46418. /**
  46419. * Start all animations on given targets
  46420. * @param loop defines if animations must loop
  46421. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  46422. */
  46423. AnimationGroup.prototype.start = function (loop, speedRatio) {
  46424. var _this = this;
  46425. if (loop === void 0) { loop = false; }
  46426. if (speedRatio === void 0) { speedRatio = 1; }
  46427. if (this._isStarted || this._targetedAnimations.length === 0) {
  46428. return this;
  46429. }
  46430. var _loop_1 = function () {
  46431. var targetedAnimation = this_1._targetedAnimations[index];
  46432. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  46433. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  46434. }));
  46435. };
  46436. var this_1 = this;
  46437. for (var index = 0; index < this._targetedAnimations.length; index++) {
  46438. _loop_1();
  46439. }
  46440. this._speedRatio = speedRatio;
  46441. this._isStarted = true;
  46442. return this;
  46443. };
  46444. /**
  46445. * Pause all animations
  46446. */
  46447. AnimationGroup.prototype.pause = function () {
  46448. if (!this._isStarted) {
  46449. return this;
  46450. }
  46451. for (var index = 0; index < this._animatables.length; index++) {
  46452. var animatable = this._animatables[index];
  46453. animatable.pause();
  46454. }
  46455. return this;
  46456. };
  46457. /**
  46458. * Play all animations to initial state
  46459. * This function will start() the animations if they were not started or will restart() them if they were paused
  46460. * @param loop defines if animations must loop
  46461. */
  46462. AnimationGroup.prototype.play = function (loop) {
  46463. if (this.isStarted) {
  46464. if (loop !== undefined) {
  46465. for (var index = 0; index < this._animatables.length; index++) {
  46466. var animatable = this._animatables[index];
  46467. animatable.loopAnimation = loop;
  46468. }
  46469. }
  46470. this.restart();
  46471. }
  46472. else {
  46473. this.start(loop, this._speedRatio);
  46474. }
  46475. return this;
  46476. };
  46477. /**
  46478. * Reset all animations to initial state
  46479. */
  46480. AnimationGroup.prototype.reset = function () {
  46481. if (!this._isStarted) {
  46482. return this;
  46483. }
  46484. for (var index = 0; index < this._animatables.length; index++) {
  46485. var animatable = this._animatables[index];
  46486. animatable.reset();
  46487. }
  46488. return this;
  46489. };
  46490. /**
  46491. * Restart animations from key 0
  46492. */
  46493. AnimationGroup.prototype.restart = function () {
  46494. if (!this._isStarted) {
  46495. return this;
  46496. }
  46497. for (var index = 0; index < this._animatables.length; index++) {
  46498. var animatable = this._animatables[index];
  46499. animatable.restart();
  46500. }
  46501. return this;
  46502. };
  46503. /**
  46504. * Stop all animations
  46505. */
  46506. AnimationGroup.prototype.stop = function () {
  46507. if (!this._isStarted) {
  46508. return this;
  46509. }
  46510. for (var index = 0; index < this._animatables.length; index++) {
  46511. var animatable = this._animatables[index];
  46512. animatable.stop();
  46513. }
  46514. this._isStarted = false;
  46515. return this;
  46516. };
  46517. /**
  46518. * Dispose all associated resources
  46519. */
  46520. AnimationGroup.prototype.dispose = function () {
  46521. this._targetedAnimations = [];
  46522. this._animatables = [];
  46523. var index = this._scene.animationGroups.indexOf(this);
  46524. if (index > -1) {
  46525. this._scene.animationGroups.splice(index, 1);
  46526. }
  46527. };
  46528. return AnimationGroup;
  46529. }());
  46530. BABYLON.AnimationGroup = AnimationGroup;
  46531. })(BABYLON || (BABYLON = {}));
  46532. //# sourceMappingURL=babylon.animationGroup.js.map
  46533. var BABYLON;
  46534. (function (BABYLON) {
  46535. var RuntimeAnimation = /** @class */ (function () {
  46536. function RuntimeAnimation(target, animation) {
  46537. this._offsetsCache = {};
  46538. this._highLimitsCache = {};
  46539. this._stopped = false;
  46540. this._blendingFactor = 0;
  46541. this._ratioOffset = 0;
  46542. this._animation = animation;
  46543. this._target = target;
  46544. animation._runtimeAnimations.push(this);
  46545. }
  46546. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  46547. get: function () {
  46548. return this._animation;
  46549. },
  46550. enumerable: true,
  46551. configurable: true
  46552. });
  46553. RuntimeAnimation.prototype.reset = function () {
  46554. this._offsetsCache = {};
  46555. this._highLimitsCache = {};
  46556. this.currentFrame = 0;
  46557. this._blendingFactor = 0;
  46558. this._originalBlendValue = null;
  46559. };
  46560. RuntimeAnimation.prototype.isStopped = function () {
  46561. return this._stopped;
  46562. };
  46563. RuntimeAnimation.prototype.dispose = function () {
  46564. var index = this._animation.runtimeAnimations.indexOf(this);
  46565. if (index > -1) {
  46566. this._animation.runtimeAnimations.splice(index, 1);
  46567. }
  46568. };
  46569. RuntimeAnimation.prototype._getKeyValue = function (value) {
  46570. if (typeof value === "function") {
  46571. return value();
  46572. }
  46573. return value;
  46574. };
  46575. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  46576. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  46577. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  46578. }
  46579. this.currentFrame = currentFrame;
  46580. var keys = this._animation.getKeys();
  46581. // Try to get a hash to find the right key
  46582. 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));
  46583. if (keys[startKeyIndex].frame >= currentFrame) {
  46584. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  46585. startKeyIndex--;
  46586. }
  46587. }
  46588. for (var key = startKeyIndex; key < keys.length; key++) {
  46589. var endKey = keys[key + 1];
  46590. if (endKey.frame >= currentFrame) {
  46591. var startKey = keys[key];
  46592. var startValue = this._getKeyValue(startKey.value);
  46593. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  46594. return startValue;
  46595. }
  46596. var endValue = this._getKeyValue(endKey.value);
  46597. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  46598. var frameDelta = endKey.frame - startKey.frame;
  46599. // gradient : percent of currentFrame between the frame inf and the frame sup
  46600. var gradient = (currentFrame - startKey.frame) / frameDelta;
  46601. // check for easingFunction and correction of gradient
  46602. var easingFunction = this._animation.getEasingFunction();
  46603. if (easingFunction != null) {
  46604. gradient = easingFunction.ease(gradient);
  46605. }
  46606. switch (this._animation.dataType) {
  46607. // Float
  46608. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46609. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  46610. switch (loopMode) {
  46611. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46612. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46613. return floatValue;
  46614. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46615. return offsetValue * repeatCount + floatValue;
  46616. }
  46617. break;
  46618. // Quaternion
  46619. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46620. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  46621. switch (loopMode) {
  46622. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46623. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46624. return quatValue;
  46625. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46626. return quatValue.add(offsetValue.scale(repeatCount));
  46627. }
  46628. return quatValue;
  46629. // Vector3
  46630. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46631. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  46632. switch (loopMode) {
  46633. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46634. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46635. return vec3Value;
  46636. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46637. return vec3Value.add(offsetValue.scale(repeatCount));
  46638. }
  46639. // Vector2
  46640. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46641. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  46642. switch (loopMode) {
  46643. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46644. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46645. return vec2Value;
  46646. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46647. return vec2Value.add(offsetValue.scale(repeatCount));
  46648. }
  46649. // Size
  46650. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46651. switch (loopMode) {
  46652. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46653. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46654. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  46655. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46656. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46657. }
  46658. // Color3
  46659. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46660. switch (loopMode) {
  46661. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46662. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46663. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  46664. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46665. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  46666. }
  46667. // Matrix
  46668. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  46669. switch (loopMode) {
  46670. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  46671. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  46672. if (BABYLON.Animation.AllowMatricesInterpolation) {
  46673. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  46674. }
  46675. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  46676. return startValue;
  46677. }
  46678. default:
  46679. break;
  46680. }
  46681. break;
  46682. }
  46683. }
  46684. return this._getKeyValue(keys[keys.length - 1].value);
  46685. };
  46686. RuntimeAnimation.prototype.setValue = function (currentValue, blend) {
  46687. if (blend === void 0) { blend = false; }
  46688. // Set value
  46689. var path;
  46690. var destination;
  46691. var targetPropertyPath = this._animation.targetPropertyPath;
  46692. if (targetPropertyPath.length > 1) {
  46693. var property = this._target[targetPropertyPath[0]];
  46694. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  46695. property = property[targetPropertyPath[index]];
  46696. }
  46697. path = targetPropertyPath[targetPropertyPath.length - 1];
  46698. destination = property;
  46699. }
  46700. else {
  46701. path = targetPropertyPath[0];
  46702. destination = this._target;
  46703. }
  46704. // Blending
  46705. if (this._animation.enableBlending && this._blendingFactor <= 1.0) {
  46706. if (!this._originalBlendValue) {
  46707. if (destination[path].clone) {
  46708. this._originalBlendValue = destination[path].clone();
  46709. }
  46710. else {
  46711. this._originalBlendValue = destination[path];
  46712. }
  46713. }
  46714. if (this._originalBlendValue.prototype) {
  46715. if (this._originalBlendValue.prototype.Lerp) {
  46716. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  46717. }
  46718. else {
  46719. destination[path] = currentValue;
  46720. }
  46721. }
  46722. else if (this._originalBlendValue.m) {
  46723. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  46724. }
  46725. else {
  46726. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  46727. }
  46728. this._blendingFactor += this._animation.blendingSpeed;
  46729. }
  46730. else {
  46731. destination[path] = currentValue;
  46732. }
  46733. if (this._target.markAsDirty) {
  46734. this._target.markAsDirty(this._animation.targetProperty);
  46735. }
  46736. };
  46737. RuntimeAnimation.prototype.goToFrame = function (frame) {
  46738. var keys = this._animation.getKeys();
  46739. if (frame < keys[0].frame) {
  46740. frame = keys[0].frame;
  46741. }
  46742. else if (frame > keys[keys.length - 1].frame) {
  46743. frame = keys[keys.length - 1].frame;
  46744. }
  46745. var currentValue = this._interpolate(frame, 0, this._animation.loopMode);
  46746. this.setValue(currentValue);
  46747. };
  46748. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  46749. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  46750. this._ratioOffset = this._previousRatio - newRatio;
  46751. };
  46752. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  46753. if (blend === void 0) { blend = false; }
  46754. var targetPropertyPath = this._animation.targetPropertyPath;
  46755. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  46756. this._stopped = true;
  46757. return false;
  46758. }
  46759. var returnValue = true;
  46760. var keys = this._animation.getKeys();
  46761. // Adding a start key at frame 0 if missing
  46762. if (keys[0].frame !== 0) {
  46763. var newKey = { frame: 0, value: keys[0].value };
  46764. keys.splice(0, 0, newKey);
  46765. }
  46766. // Check limits
  46767. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  46768. from = keys[0].frame;
  46769. }
  46770. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  46771. to = keys[keys.length - 1].frame;
  46772. }
  46773. //to and from cannot be the same key
  46774. if (from === to) {
  46775. if (from > keys[0].frame) {
  46776. from--;
  46777. }
  46778. else if (to < keys[keys.length - 1].frame) {
  46779. to++;
  46780. }
  46781. }
  46782. // Compute ratio
  46783. var range = to - from;
  46784. var offsetValue;
  46785. // ratio represents the frame delta between from and to
  46786. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  46787. var highLimitValue = 0;
  46788. this._previousDelay = delay;
  46789. this._previousRatio = ratio;
  46790. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  46791. returnValue = false;
  46792. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  46793. }
  46794. else {
  46795. // Get max value if required
  46796. if (this._animation.loopMode !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  46797. var keyOffset = to.toString() + from.toString();
  46798. if (!this._offsetsCache[keyOffset]) {
  46799. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46800. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  46801. switch (this._animation.dataType) {
  46802. // Float
  46803. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46804. this._offsetsCache[keyOffset] = toValue - fromValue;
  46805. break;
  46806. // Quaternion
  46807. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46808. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46809. break;
  46810. // Vector3
  46811. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46812. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46813. // Vector2
  46814. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46815. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46816. // Size
  46817. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46818. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46819. // Color3
  46820. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46821. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  46822. default:
  46823. break;
  46824. }
  46825. this._highLimitsCache[keyOffset] = toValue;
  46826. }
  46827. highLimitValue = this._highLimitsCache[keyOffset];
  46828. offsetValue = this._offsetsCache[keyOffset];
  46829. }
  46830. }
  46831. if (offsetValue === undefined) {
  46832. switch (this._animation.dataType) {
  46833. // Float
  46834. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  46835. offsetValue = 0;
  46836. break;
  46837. // Quaternion
  46838. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  46839. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  46840. break;
  46841. // Vector3
  46842. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  46843. offsetValue = BABYLON.Vector3.Zero();
  46844. break;
  46845. // Vector2
  46846. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  46847. offsetValue = BABYLON.Vector2.Zero();
  46848. break;
  46849. // Size
  46850. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  46851. offsetValue = BABYLON.Size.Zero();
  46852. break;
  46853. // Color3
  46854. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  46855. offsetValue = BABYLON.Color3.Black();
  46856. }
  46857. }
  46858. // Compute value
  46859. var repeatCount = (ratio / range) >> 0;
  46860. var currentFrame = returnValue ? from + ratio % range : to;
  46861. var currentValue = this._interpolate(currentFrame, repeatCount, this._animation.loopMode, offsetValue, highLimitValue);
  46862. // Set value
  46863. this.setValue(currentValue);
  46864. // Check events
  46865. var events = this._animation.getEvents();
  46866. for (var index = 0; index < events.length; index++) {
  46867. // Make sure current frame has passed event frame and that event frame is within the current range
  46868. // Also, handle both forward and reverse animations
  46869. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  46870. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  46871. var event = events[index];
  46872. if (!event.isDone) {
  46873. // If event should be done only once, remove it.
  46874. if (event.onlyOnce) {
  46875. events.splice(index, 1);
  46876. index--;
  46877. }
  46878. event.isDone = true;
  46879. event.action();
  46880. } // Don't do anything if the event has already be done.
  46881. }
  46882. else if (events[index].isDone && !events[index].onlyOnce) {
  46883. // reset event, the animation is looping
  46884. events[index].isDone = false;
  46885. }
  46886. }
  46887. if (!returnValue) {
  46888. this._stopped = true;
  46889. }
  46890. return returnValue;
  46891. };
  46892. return RuntimeAnimation;
  46893. }());
  46894. BABYLON.RuntimeAnimation = RuntimeAnimation;
  46895. })(BABYLON || (BABYLON = {}));
  46896. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  46897. var BABYLON;
  46898. (function (BABYLON) {
  46899. var Animatable = /** @class */ (function () {
  46900. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  46901. if (fromFrame === void 0) { fromFrame = 0; }
  46902. if (toFrame === void 0) { toFrame = 100; }
  46903. if (loopAnimation === void 0) { loopAnimation = false; }
  46904. if (speedRatio === void 0) { speedRatio = 1.0; }
  46905. this.target = target;
  46906. this.fromFrame = fromFrame;
  46907. this.toFrame = toFrame;
  46908. this.loopAnimation = loopAnimation;
  46909. this.onAnimationEnd = onAnimationEnd;
  46910. this._localDelayOffset = null;
  46911. this._pausedDelay = null;
  46912. this._runtimeAnimations = new Array();
  46913. this._paused = false;
  46914. this._speedRatio = 1;
  46915. this.animationStarted = false;
  46916. if (animations) {
  46917. this.appendAnimations(target, animations);
  46918. }
  46919. this._speedRatio = speedRatio;
  46920. this._scene = scene;
  46921. scene._activeAnimatables.push(this);
  46922. }
  46923. Object.defineProperty(Animatable.prototype, "speedRatio", {
  46924. get: function () {
  46925. return this._speedRatio;
  46926. },
  46927. set: function (value) {
  46928. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  46929. var animation = this._runtimeAnimations[index];
  46930. animation._prepareForSpeedRatioChange(value);
  46931. }
  46932. this._speedRatio = value;
  46933. },
  46934. enumerable: true,
  46935. configurable: true
  46936. });
  46937. // Methods
  46938. Animatable.prototype.getAnimations = function () {
  46939. return this._runtimeAnimations;
  46940. };
  46941. Animatable.prototype.appendAnimations = function (target, animations) {
  46942. for (var index = 0; index < animations.length; index++) {
  46943. var animation = animations[index];
  46944. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation));
  46945. }
  46946. };
  46947. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  46948. var runtimeAnimations = this._runtimeAnimations;
  46949. for (var index = 0; index < runtimeAnimations.length; index++) {
  46950. if (runtimeAnimations[index].animation.targetProperty === property) {
  46951. return runtimeAnimations[index].animation;
  46952. }
  46953. }
  46954. return null;
  46955. };
  46956. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  46957. var runtimeAnimations = this._runtimeAnimations;
  46958. for (var index = 0; index < runtimeAnimations.length; index++) {
  46959. if (runtimeAnimations[index].animation.targetProperty === property) {
  46960. return runtimeAnimations[index];
  46961. }
  46962. }
  46963. return null;
  46964. };
  46965. Animatable.prototype.reset = function () {
  46966. var runtimeAnimations = this._runtimeAnimations;
  46967. for (var index = 0; index < runtimeAnimations.length; index++) {
  46968. runtimeAnimations[index].reset();
  46969. }
  46970. // Reset to original value
  46971. for (index = 0; index < runtimeAnimations.length; index++) {
  46972. var animation = runtimeAnimations[index];
  46973. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  46974. }
  46975. this._localDelayOffset = null;
  46976. this._pausedDelay = null;
  46977. };
  46978. Animatable.prototype.enableBlending = function (blendingSpeed) {
  46979. var runtimeAnimations = this._runtimeAnimations;
  46980. for (var index = 0; index < runtimeAnimations.length; index++) {
  46981. runtimeAnimations[index].animation.enableBlending = true;
  46982. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  46983. }
  46984. };
  46985. Animatable.prototype.disableBlending = function () {
  46986. var runtimeAnimations = this._runtimeAnimations;
  46987. for (var index = 0; index < runtimeAnimations.length; index++) {
  46988. runtimeAnimations[index].animation.enableBlending = false;
  46989. }
  46990. };
  46991. Animatable.prototype.goToFrame = function (frame) {
  46992. var runtimeAnimations = this._runtimeAnimations;
  46993. if (runtimeAnimations[0]) {
  46994. var fps = runtimeAnimations[0].animation.framePerSecond;
  46995. var currentFrame = runtimeAnimations[0].currentFrame;
  46996. var adjustTime = frame - currentFrame;
  46997. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  46998. if (this._localDelayOffset === null) {
  46999. this._localDelayOffset = 0;
  47000. }
  47001. this._localDelayOffset -= delay;
  47002. }
  47003. for (var index = 0; index < runtimeAnimations.length; index++) {
  47004. runtimeAnimations[index].goToFrame(frame);
  47005. }
  47006. };
  47007. Animatable.prototype.pause = function () {
  47008. if (this._paused) {
  47009. return;
  47010. }
  47011. this._paused = true;
  47012. };
  47013. Animatable.prototype.restart = function () {
  47014. this._paused = false;
  47015. };
  47016. Animatable.prototype.stop = function (animationName) {
  47017. if (animationName) {
  47018. var idx = this._scene._activeAnimatables.indexOf(this);
  47019. if (idx > -1) {
  47020. var runtimeAnimations = this._runtimeAnimations;
  47021. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  47022. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  47023. continue;
  47024. }
  47025. runtimeAnimations[index].dispose();
  47026. runtimeAnimations.splice(index, 1);
  47027. }
  47028. if (runtimeAnimations.length == 0) {
  47029. this._scene._activeAnimatables.splice(idx, 1);
  47030. if (this.onAnimationEnd) {
  47031. this.onAnimationEnd();
  47032. }
  47033. }
  47034. }
  47035. }
  47036. else {
  47037. var index = this._scene._activeAnimatables.indexOf(this);
  47038. if (index > -1) {
  47039. this._scene._activeAnimatables.splice(index, 1);
  47040. var runtimeAnimations = this._runtimeAnimations;
  47041. for (var index = 0; index < runtimeAnimations.length; index++) {
  47042. runtimeAnimations[index].dispose();
  47043. }
  47044. if (this.onAnimationEnd) {
  47045. this.onAnimationEnd();
  47046. }
  47047. }
  47048. }
  47049. };
  47050. Animatable.prototype._animate = function (delay) {
  47051. if (this._paused) {
  47052. this.animationStarted = false;
  47053. if (this._pausedDelay === null) {
  47054. this._pausedDelay = delay;
  47055. }
  47056. return true;
  47057. }
  47058. if (this._localDelayOffset === null) {
  47059. this._localDelayOffset = delay;
  47060. this._pausedDelay = null;
  47061. }
  47062. else if (this._pausedDelay !== null) {
  47063. this._localDelayOffset += delay - this._pausedDelay;
  47064. this._pausedDelay = null;
  47065. }
  47066. // Animating
  47067. var running = false;
  47068. var runtimeAnimations = this._runtimeAnimations;
  47069. var index;
  47070. for (index = 0; index < runtimeAnimations.length; index++) {
  47071. var animation = runtimeAnimations[index];
  47072. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio);
  47073. running = running || isRunning;
  47074. }
  47075. this.animationStarted = running;
  47076. if (!running) {
  47077. // Remove from active animatables
  47078. index = this._scene._activeAnimatables.indexOf(this);
  47079. this._scene._activeAnimatables.splice(index, 1);
  47080. // Dispose all runtime animations
  47081. for (index = 0; index < runtimeAnimations.length; index++) {
  47082. runtimeAnimations[index].dispose();
  47083. }
  47084. }
  47085. if (!running && this.onAnimationEnd) {
  47086. this.onAnimationEnd();
  47087. this.onAnimationEnd = null;
  47088. }
  47089. return running;
  47090. };
  47091. return Animatable;
  47092. }());
  47093. BABYLON.Animatable = Animatable;
  47094. })(BABYLON || (BABYLON = {}));
  47095. //# sourceMappingURL=babylon.animatable.js.map
  47096. var BABYLON;
  47097. (function (BABYLON) {
  47098. var EasingFunction = /** @class */ (function () {
  47099. function EasingFunction() {
  47100. // Properties
  47101. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  47102. }
  47103. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  47104. get: function () {
  47105. return EasingFunction._EASINGMODE_EASEIN;
  47106. },
  47107. enumerable: true,
  47108. configurable: true
  47109. });
  47110. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  47111. get: function () {
  47112. return EasingFunction._EASINGMODE_EASEOUT;
  47113. },
  47114. enumerable: true,
  47115. configurable: true
  47116. });
  47117. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  47118. get: function () {
  47119. return EasingFunction._EASINGMODE_EASEINOUT;
  47120. },
  47121. enumerable: true,
  47122. configurable: true
  47123. });
  47124. EasingFunction.prototype.setEasingMode = function (easingMode) {
  47125. var n = Math.min(Math.max(easingMode, 0), 2);
  47126. this._easingMode = n;
  47127. };
  47128. EasingFunction.prototype.getEasingMode = function () {
  47129. return this._easingMode;
  47130. };
  47131. EasingFunction.prototype.easeInCore = function (gradient) {
  47132. throw new Error('You must implement this method');
  47133. };
  47134. EasingFunction.prototype.ease = function (gradient) {
  47135. switch (this._easingMode) {
  47136. case EasingFunction.EASINGMODE_EASEIN:
  47137. return this.easeInCore(gradient);
  47138. case EasingFunction.EASINGMODE_EASEOUT:
  47139. return (1 - this.easeInCore(1 - gradient));
  47140. }
  47141. if (gradient >= 0.5) {
  47142. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  47143. }
  47144. return (this.easeInCore(gradient * 2) * 0.5);
  47145. };
  47146. //Statics
  47147. EasingFunction._EASINGMODE_EASEIN = 0;
  47148. EasingFunction._EASINGMODE_EASEOUT = 1;
  47149. EasingFunction._EASINGMODE_EASEINOUT = 2;
  47150. return EasingFunction;
  47151. }());
  47152. BABYLON.EasingFunction = EasingFunction;
  47153. var CircleEase = /** @class */ (function (_super) {
  47154. __extends(CircleEase, _super);
  47155. function CircleEase() {
  47156. return _super !== null && _super.apply(this, arguments) || this;
  47157. }
  47158. CircleEase.prototype.easeInCore = function (gradient) {
  47159. gradient = Math.max(0, Math.min(1, gradient));
  47160. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  47161. };
  47162. return CircleEase;
  47163. }(EasingFunction));
  47164. BABYLON.CircleEase = CircleEase;
  47165. var BackEase = /** @class */ (function (_super) {
  47166. __extends(BackEase, _super);
  47167. function BackEase(amplitude) {
  47168. if (amplitude === void 0) { amplitude = 1; }
  47169. var _this = _super.call(this) || this;
  47170. _this.amplitude = amplitude;
  47171. return _this;
  47172. }
  47173. BackEase.prototype.easeInCore = function (gradient) {
  47174. var num = Math.max(0, this.amplitude);
  47175. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  47176. };
  47177. return BackEase;
  47178. }(EasingFunction));
  47179. BABYLON.BackEase = BackEase;
  47180. var BounceEase = /** @class */ (function (_super) {
  47181. __extends(BounceEase, _super);
  47182. function BounceEase(bounces, bounciness) {
  47183. if (bounces === void 0) { bounces = 3; }
  47184. if (bounciness === void 0) { bounciness = 2; }
  47185. var _this = _super.call(this) || this;
  47186. _this.bounces = bounces;
  47187. _this.bounciness = bounciness;
  47188. return _this;
  47189. }
  47190. BounceEase.prototype.easeInCore = function (gradient) {
  47191. var y = Math.max(0.0, this.bounces);
  47192. var bounciness = this.bounciness;
  47193. if (bounciness <= 1.0) {
  47194. bounciness = 1.001;
  47195. }
  47196. var num9 = Math.pow(bounciness, y);
  47197. var num5 = 1.0 - bounciness;
  47198. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  47199. var num15 = gradient * num4;
  47200. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  47201. var num3 = Math.floor(num65);
  47202. var num13 = num3 + 1.0;
  47203. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  47204. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  47205. var num7 = (num8 + num12) * 0.5;
  47206. var num6 = gradient - num7;
  47207. var num2 = num7 - num8;
  47208. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  47209. };
  47210. return BounceEase;
  47211. }(EasingFunction));
  47212. BABYLON.BounceEase = BounceEase;
  47213. var CubicEase = /** @class */ (function (_super) {
  47214. __extends(CubicEase, _super);
  47215. function CubicEase() {
  47216. return _super !== null && _super.apply(this, arguments) || this;
  47217. }
  47218. CubicEase.prototype.easeInCore = function (gradient) {
  47219. return (gradient * gradient * gradient);
  47220. };
  47221. return CubicEase;
  47222. }(EasingFunction));
  47223. BABYLON.CubicEase = CubicEase;
  47224. var ElasticEase = /** @class */ (function (_super) {
  47225. __extends(ElasticEase, _super);
  47226. function ElasticEase(oscillations, springiness) {
  47227. if (oscillations === void 0) { oscillations = 3; }
  47228. if (springiness === void 0) { springiness = 3; }
  47229. var _this = _super.call(this) || this;
  47230. _this.oscillations = oscillations;
  47231. _this.springiness = springiness;
  47232. return _this;
  47233. }
  47234. ElasticEase.prototype.easeInCore = function (gradient) {
  47235. var num2;
  47236. var num3 = Math.max(0.0, this.oscillations);
  47237. var num = Math.max(0.0, this.springiness);
  47238. if (num == 0) {
  47239. num2 = gradient;
  47240. }
  47241. else {
  47242. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  47243. }
  47244. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  47245. };
  47246. return ElasticEase;
  47247. }(EasingFunction));
  47248. BABYLON.ElasticEase = ElasticEase;
  47249. var ExponentialEase = /** @class */ (function (_super) {
  47250. __extends(ExponentialEase, _super);
  47251. function ExponentialEase(exponent) {
  47252. if (exponent === void 0) { exponent = 2; }
  47253. var _this = _super.call(this) || this;
  47254. _this.exponent = exponent;
  47255. return _this;
  47256. }
  47257. ExponentialEase.prototype.easeInCore = function (gradient) {
  47258. if (this.exponent <= 0) {
  47259. return gradient;
  47260. }
  47261. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  47262. };
  47263. return ExponentialEase;
  47264. }(EasingFunction));
  47265. BABYLON.ExponentialEase = ExponentialEase;
  47266. var PowerEase = /** @class */ (function (_super) {
  47267. __extends(PowerEase, _super);
  47268. function PowerEase(power) {
  47269. if (power === void 0) { power = 2; }
  47270. var _this = _super.call(this) || this;
  47271. _this.power = power;
  47272. return _this;
  47273. }
  47274. PowerEase.prototype.easeInCore = function (gradient) {
  47275. var y = Math.max(0.0, this.power);
  47276. return Math.pow(gradient, y);
  47277. };
  47278. return PowerEase;
  47279. }(EasingFunction));
  47280. BABYLON.PowerEase = PowerEase;
  47281. var QuadraticEase = /** @class */ (function (_super) {
  47282. __extends(QuadraticEase, _super);
  47283. function QuadraticEase() {
  47284. return _super !== null && _super.apply(this, arguments) || this;
  47285. }
  47286. QuadraticEase.prototype.easeInCore = function (gradient) {
  47287. return (gradient * gradient);
  47288. };
  47289. return QuadraticEase;
  47290. }(EasingFunction));
  47291. BABYLON.QuadraticEase = QuadraticEase;
  47292. var QuarticEase = /** @class */ (function (_super) {
  47293. __extends(QuarticEase, _super);
  47294. function QuarticEase() {
  47295. return _super !== null && _super.apply(this, arguments) || this;
  47296. }
  47297. QuarticEase.prototype.easeInCore = function (gradient) {
  47298. return (gradient * gradient * gradient * gradient);
  47299. };
  47300. return QuarticEase;
  47301. }(EasingFunction));
  47302. BABYLON.QuarticEase = QuarticEase;
  47303. var QuinticEase = /** @class */ (function (_super) {
  47304. __extends(QuinticEase, _super);
  47305. function QuinticEase() {
  47306. return _super !== null && _super.apply(this, arguments) || this;
  47307. }
  47308. QuinticEase.prototype.easeInCore = function (gradient) {
  47309. return (gradient * gradient * gradient * gradient * gradient);
  47310. };
  47311. return QuinticEase;
  47312. }(EasingFunction));
  47313. BABYLON.QuinticEase = QuinticEase;
  47314. var SineEase = /** @class */ (function (_super) {
  47315. __extends(SineEase, _super);
  47316. function SineEase() {
  47317. return _super !== null && _super.apply(this, arguments) || this;
  47318. }
  47319. SineEase.prototype.easeInCore = function (gradient) {
  47320. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  47321. };
  47322. return SineEase;
  47323. }(EasingFunction));
  47324. BABYLON.SineEase = SineEase;
  47325. var BezierCurveEase = /** @class */ (function (_super) {
  47326. __extends(BezierCurveEase, _super);
  47327. function BezierCurveEase(x1, y1, x2, y2) {
  47328. if (x1 === void 0) { x1 = 0; }
  47329. if (y1 === void 0) { y1 = 0; }
  47330. if (x2 === void 0) { x2 = 1; }
  47331. if (y2 === void 0) { y2 = 1; }
  47332. var _this = _super.call(this) || this;
  47333. _this.x1 = x1;
  47334. _this.y1 = y1;
  47335. _this.x2 = x2;
  47336. _this.y2 = y2;
  47337. return _this;
  47338. }
  47339. BezierCurveEase.prototype.easeInCore = function (gradient) {
  47340. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  47341. };
  47342. return BezierCurveEase;
  47343. }(EasingFunction));
  47344. BABYLON.BezierCurveEase = BezierCurveEase;
  47345. })(BABYLON || (BABYLON = {}));
  47346. //# sourceMappingURL=babylon.easing.js.map
  47347. var BABYLON;
  47348. (function (BABYLON) {
  47349. var Condition = /** @class */ (function () {
  47350. function Condition(actionManager) {
  47351. this._actionManager = actionManager;
  47352. }
  47353. Condition.prototype.isValid = function () {
  47354. return true;
  47355. };
  47356. Condition.prototype._getProperty = function (propertyPath) {
  47357. return this._actionManager._getProperty(propertyPath);
  47358. };
  47359. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  47360. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47361. };
  47362. Condition.prototype.serialize = function () {
  47363. };
  47364. Condition.prototype._serialize = function (serializedCondition) {
  47365. return {
  47366. type: 2,
  47367. children: [],
  47368. name: serializedCondition.name,
  47369. properties: serializedCondition.properties
  47370. };
  47371. };
  47372. return Condition;
  47373. }());
  47374. BABYLON.Condition = Condition;
  47375. var ValueCondition = /** @class */ (function (_super) {
  47376. __extends(ValueCondition, _super);
  47377. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  47378. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  47379. var _this = _super.call(this, actionManager) || this;
  47380. _this.propertyPath = propertyPath;
  47381. _this.value = value;
  47382. _this.operator = operator;
  47383. _this._target = target;
  47384. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  47385. _this._property = _this._getProperty(_this.propertyPath);
  47386. return _this;
  47387. }
  47388. Object.defineProperty(ValueCondition, "IsEqual", {
  47389. get: function () {
  47390. return ValueCondition._IsEqual;
  47391. },
  47392. enumerable: true,
  47393. configurable: true
  47394. });
  47395. Object.defineProperty(ValueCondition, "IsDifferent", {
  47396. get: function () {
  47397. return ValueCondition._IsDifferent;
  47398. },
  47399. enumerable: true,
  47400. configurable: true
  47401. });
  47402. Object.defineProperty(ValueCondition, "IsGreater", {
  47403. get: function () {
  47404. return ValueCondition._IsGreater;
  47405. },
  47406. enumerable: true,
  47407. configurable: true
  47408. });
  47409. Object.defineProperty(ValueCondition, "IsLesser", {
  47410. get: function () {
  47411. return ValueCondition._IsLesser;
  47412. },
  47413. enumerable: true,
  47414. configurable: true
  47415. });
  47416. // Methods
  47417. ValueCondition.prototype.isValid = function () {
  47418. switch (this.operator) {
  47419. case ValueCondition.IsGreater:
  47420. return this._effectiveTarget[this._property] > this.value;
  47421. case ValueCondition.IsLesser:
  47422. return this._effectiveTarget[this._property] < this.value;
  47423. case ValueCondition.IsEqual:
  47424. case ValueCondition.IsDifferent:
  47425. var check;
  47426. if (this.value.equals) {
  47427. check = this.value.equals(this._effectiveTarget[this._property]);
  47428. }
  47429. else {
  47430. check = this.value === this._effectiveTarget[this._property];
  47431. }
  47432. return this.operator === ValueCondition.IsEqual ? check : !check;
  47433. }
  47434. return false;
  47435. };
  47436. ValueCondition.prototype.serialize = function () {
  47437. return this._serialize({
  47438. name: "ValueCondition",
  47439. properties: [
  47440. BABYLON.Action._GetTargetProperty(this._target),
  47441. { name: "propertyPath", value: this.propertyPath },
  47442. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  47443. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  47444. ]
  47445. });
  47446. };
  47447. ValueCondition.GetOperatorName = function (operator) {
  47448. switch (operator) {
  47449. case ValueCondition._IsEqual: return "IsEqual";
  47450. case ValueCondition._IsDifferent: return "IsDifferent";
  47451. case ValueCondition._IsGreater: return "IsGreater";
  47452. case ValueCondition._IsLesser: return "IsLesser";
  47453. default: return "";
  47454. }
  47455. };
  47456. // Statics
  47457. ValueCondition._IsEqual = 0;
  47458. ValueCondition._IsDifferent = 1;
  47459. ValueCondition._IsGreater = 2;
  47460. ValueCondition._IsLesser = 3;
  47461. return ValueCondition;
  47462. }(Condition));
  47463. BABYLON.ValueCondition = ValueCondition;
  47464. var PredicateCondition = /** @class */ (function (_super) {
  47465. __extends(PredicateCondition, _super);
  47466. function PredicateCondition(actionManager, predicate) {
  47467. var _this = _super.call(this, actionManager) || this;
  47468. _this.predicate = predicate;
  47469. return _this;
  47470. }
  47471. PredicateCondition.prototype.isValid = function () {
  47472. return this.predicate();
  47473. };
  47474. return PredicateCondition;
  47475. }(Condition));
  47476. BABYLON.PredicateCondition = PredicateCondition;
  47477. var StateCondition = /** @class */ (function (_super) {
  47478. __extends(StateCondition, _super);
  47479. function StateCondition(actionManager, target, value) {
  47480. var _this = _super.call(this, actionManager) || this;
  47481. _this.value = value;
  47482. _this._target = target;
  47483. return _this;
  47484. }
  47485. // Methods
  47486. StateCondition.prototype.isValid = function () {
  47487. return this._target.state === this.value;
  47488. };
  47489. StateCondition.prototype.serialize = function () {
  47490. return this._serialize({
  47491. name: "StateCondition",
  47492. properties: [
  47493. BABYLON.Action._GetTargetProperty(this._target),
  47494. { name: "value", value: this.value }
  47495. ]
  47496. });
  47497. };
  47498. return StateCondition;
  47499. }(Condition));
  47500. BABYLON.StateCondition = StateCondition;
  47501. })(BABYLON || (BABYLON = {}));
  47502. //# sourceMappingURL=babylon.condition.js.map
  47503. var BABYLON;
  47504. (function (BABYLON) {
  47505. var Action = /** @class */ (function () {
  47506. function Action(triggerOptions, condition) {
  47507. this.triggerOptions = triggerOptions;
  47508. this.onBeforeExecuteObservable = new BABYLON.Observable();
  47509. if (triggerOptions.parameter) {
  47510. this.trigger = triggerOptions.trigger;
  47511. this._triggerParameter = triggerOptions.parameter;
  47512. }
  47513. else {
  47514. this.trigger = triggerOptions;
  47515. }
  47516. this._nextActiveAction = this;
  47517. this._condition = condition;
  47518. }
  47519. // Methods
  47520. Action.prototype._prepare = function () {
  47521. };
  47522. Action.prototype.getTriggerParameter = function () {
  47523. return this._triggerParameter;
  47524. };
  47525. Action.prototype._executeCurrent = function (evt) {
  47526. if (this._nextActiveAction._condition) {
  47527. var condition = this._nextActiveAction._condition;
  47528. var currentRenderId = this._actionManager.getScene().getRenderId();
  47529. // We cache the current evaluation for the current frame
  47530. if (condition._evaluationId === currentRenderId) {
  47531. if (!condition._currentResult) {
  47532. return;
  47533. }
  47534. }
  47535. else {
  47536. condition._evaluationId = currentRenderId;
  47537. if (!condition.isValid()) {
  47538. condition._currentResult = false;
  47539. return;
  47540. }
  47541. condition._currentResult = true;
  47542. }
  47543. }
  47544. this.onBeforeExecuteObservable.notifyObservers(this);
  47545. this._nextActiveAction.execute(evt);
  47546. this.skipToNextActiveAction();
  47547. };
  47548. Action.prototype.execute = function (evt) {
  47549. };
  47550. Action.prototype.skipToNextActiveAction = function () {
  47551. if (this._nextActiveAction._child) {
  47552. if (!this._nextActiveAction._child._actionManager) {
  47553. this._nextActiveAction._child._actionManager = this._actionManager;
  47554. }
  47555. this._nextActiveAction = this._nextActiveAction._child;
  47556. }
  47557. else {
  47558. this._nextActiveAction = this;
  47559. }
  47560. };
  47561. Action.prototype.then = function (action) {
  47562. this._child = action;
  47563. action._actionManager = this._actionManager;
  47564. action._prepare();
  47565. return action;
  47566. };
  47567. Action.prototype._getProperty = function (propertyPath) {
  47568. return this._actionManager._getProperty(propertyPath);
  47569. };
  47570. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  47571. return this._actionManager._getEffectiveTarget(target, propertyPath);
  47572. };
  47573. Action.prototype.serialize = function (parent) {
  47574. };
  47575. // Called by BABYLON.Action objects in serialize(...). Internal use
  47576. Action.prototype._serialize = function (serializedAction, parent) {
  47577. var serializationObject = {
  47578. type: 1,
  47579. children: [],
  47580. name: serializedAction.name,
  47581. properties: serializedAction.properties || []
  47582. };
  47583. // Serialize child
  47584. if (this._child) {
  47585. this._child.serialize(serializationObject);
  47586. }
  47587. // Check if "this" has a condition
  47588. if (this._condition) {
  47589. var serializedCondition = this._condition.serialize();
  47590. serializedCondition.children.push(serializationObject);
  47591. if (parent) {
  47592. parent.children.push(serializedCondition);
  47593. }
  47594. return serializedCondition;
  47595. }
  47596. if (parent) {
  47597. parent.children.push(serializationObject);
  47598. }
  47599. return serializationObject;
  47600. };
  47601. Action._SerializeValueAsString = function (value) {
  47602. if (typeof value === "number") {
  47603. return value.toString();
  47604. }
  47605. if (typeof value === "boolean") {
  47606. return value ? "true" : "false";
  47607. }
  47608. if (value instanceof BABYLON.Vector2) {
  47609. return value.x + ", " + value.y;
  47610. }
  47611. if (value instanceof BABYLON.Vector3) {
  47612. return value.x + ", " + value.y + ", " + value.z;
  47613. }
  47614. if (value instanceof BABYLON.Color3) {
  47615. return value.r + ", " + value.g + ", " + value.b;
  47616. }
  47617. if (value instanceof BABYLON.Color4) {
  47618. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  47619. }
  47620. return value; // string
  47621. };
  47622. Action._GetTargetProperty = function (target) {
  47623. return {
  47624. name: "target",
  47625. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  47626. : target instanceof BABYLON.Light ? "LightProperties"
  47627. : target instanceof BABYLON.Camera ? "CameraProperties"
  47628. : "SceneProperties",
  47629. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  47630. };
  47631. };
  47632. return Action;
  47633. }());
  47634. BABYLON.Action = Action;
  47635. })(BABYLON || (BABYLON = {}));
  47636. //# sourceMappingURL=babylon.action.js.map
  47637. var BABYLON;
  47638. (function (BABYLON) {
  47639. /**
  47640. * ActionEvent is the event beint sent when an action is triggered.
  47641. */
  47642. var ActionEvent = /** @class */ (function () {
  47643. /**
  47644. * @param source The mesh or sprite that triggered the action.
  47645. * @param pointerX The X mouse cursor position at the time of the event
  47646. * @param pointerY The Y mouse cursor position at the time of the event
  47647. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  47648. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  47649. */
  47650. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  47651. this.source = source;
  47652. this.pointerX = pointerX;
  47653. this.pointerY = pointerY;
  47654. this.meshUnderPointer = meshUnderPointer;
  47655. this.sourceEvent = sourceEvent;
  47656. this.additionalData = additionalData;
  47657. }
  47658. /**
  47659. * Helper function to auto-create an ActionEvent from a source mesh.
  47660. * @param source The source mesh that triggered the event
  47661. * @param evt {Event} The original (browser) event
  47662. */
  47663. ActionEvent.CreateNew = function (source, evt, additionalData) {
  47664. var scene = source.getScene();
  47665. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47666. };
  47667. /**
  47668. * Helper function to auto-create an ActionEvent from a source mesh.
  47669. * @param source The source sprite that triggered the event
  47670. * @param scene Scene associated with the sprite
  47671. * @param evt {Event} The original (browser) event
  47672. */
  47673. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  47674. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  47675. };
  47676. /**
  47677. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  47678. * @param scene the scene where the event occurred
  47679. * @param evt {Event} The original (browser) event
  47680. */
  47681. ActionEvent.CreateNewFromScene = function (scene, evt) {
  47682. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  47683. };
  47684. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  47685. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  47686. };
  47687. return ActionEvent;
  47688. }());
  47689. BABYLON.ActionEvent = ActionEvent;
  47690. /**
  47691. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  47692. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  47693. */
  47694. var ActionManager = /** @class */ (function () {
  47695. function ActionManager(scene) {
  47696. // Members
  47697. this.actions = new Array();
  47698. this.hoverCursor = '';
  47699. this._scene = scene;
  47700. scene._actionManagers.push(this);
  47701. }
  47702. Object.defineProperty(ActionManager, "NothingTrigger", {
  47703. get: function () {
  47704. return ActionManager._NothingTrigger;
  47705. },
  47706. enumerable: true,
  47707. configurable: true
  47708. });
  47709. Object.defineProperty(ActionManager, "OnPickTrigger", {
  47710. get: function () {
  47711. return ActionManager._OnPickTrigger;
  47712. },
  47713. enumerable: true,
  47714. configurable: true
  47715. });
  47716. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  47717. get: function () {
  47718. return ActionManager._OnLeftPickTrigger;
  47719. },
  47720. enumerable: true,
  47721. configurable: true
  47722. });
  47723. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  47724. get: function () {
  47725. return ActionManager._OnRightPickTrigger;
  47726. },
  47727. enumerable: true,
  47728. configurable: true
  47729. });
  47730. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  47731. get: function () {
  47732. return ActionManager._OnCenterPickTrigger;
  47733. },
  47734. enumerable: true,
  47735. configurable: true
  47736. });
  47737. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  47738. get: function () {
  47739. return ActionManager._OnPickDownTrigger;
  47740. },
  47741. enumerable: true,
  47742. configurable: true
  47743. });
  47744. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  47745. get: function () {
  47746. return ActionManager._OnDoublePickTrigger;
  47747. },
  47748. enumerable: true,
  47749. configurable: true
  47750. });
  47751. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  47752. get: function () {
  47753. return ActionManager._OnPickUpTrigger;
  47754. },
  47755. enumerable: true,
  47756. configurable: true
  47757. });
  47758. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  47759. /// This trigger will only be raised if you also declared a OnPickDown
  47760. get: function () {
  47761. return ActionManager._OnPickOutTrigger;
  47762. },
  47763. enumerable: true,
  47764. configurable: true
  47765. });
  47766. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  47767. get: function () {
  47768. return ActionManager._OnLongPressTrigger;
  47769. },
  47770. enumerable: true,
  47771. configurable: true
  47772. });
  47773. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  47774. get: function () {
  47775. return ActionManager._OnPointerOverTrigger;
  47776. },
  47777. enumerable: true,
  47778. configurable: true
  47779. });
  47780. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  47781. get: function () {
  47782. return ActionManager._OnPointerOutTrigger;
  47783. },
  47784. enumerable: true,
  47785. configurable: true
  47786. });
  47787. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  47788. get: function () {
  47789. return ActionManager._OnEveryFrameTrigger;
  47790. },
  47791. enumerable: true,
  47792. configurable: true
  47793. });
  47794. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  47795. get: function () {
  47796. return ActionManager._OnIntersectionEnterTrigger;
  47797. },
  47798. enumerable: true,
  47799. configurable: true
  47800. });
  47801. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  47802. get: function () {
  47803. return ActionManager._OnIntersectionExitTrigger;
  47804. },
  47805. enumerable: true,
  47806. configurable: true
  47807. });
  47808. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  47809. get: function () {
  47810. return ActionManager._OnKeyDownTrigger;
  47811. },
  47812. enumerable: true,
  47813. configurable: true
  47814. });
  47815. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  47816. get: function () {
  47817. return ActionManager._OnKeyUpTrigger;
  47818. },
  47819. enumerable: true,
  47820. configurable: true
  47821. });
  47822. // Methods
  47823. ActionManager.prototype.dispose = function () {
  47824. var index = this._scene._actionManagers.indexOf(this);
  47825. for (var i = 0; i < this.actions.length; i++) {
  47826. var action = this.actions[i];
  47827. ActionManager.Triggers[action.trigger]--;
  47828. if (ActionManager.Triggers[action.trigger] === 0) {
  47829. delete ActionManager.Triggers[action.trigger];
  47830. }
  47831. }
  47832. if (index > -1) {
  47833. this._scene._actionManagers.splice(index, 1);
  47834. }
  47835. };
  47836. ActionManager.prototype.getScene = function () {
  47837. return this._scene;
  47838. };
  47839. /**
  47840. * Does this action manager handles actions of any of the given triggers
  47841. * @param {number[]} triggers - the triggers to be tested
  47842. * @return {boolean} whether one (or more) of the triggers is handeled
  47843. */
  47844. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  47845. for (var index = 0; index < this.actions.length; index++) {
  47846. var action = this.actions[index];
  47847. if (triggers.indexOf(action.trigger) > -1) {
  47848. return true;
  47849. }
  47850. }
  47851. return false;
  47852. };
  47853. /**
  47854. * Does this action manager handles actions of a given trigger
  47855. * @param {number} trigger - the trigger to be tested
  47856. * @return {boolean} whether the trigger is handeled
  47857. */
  47858. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  47859. for (var index = 0; index < this.actions.length; index++) {
  47860. var action = this.actions[index];
  47861. if (action.trigger === trigger) {
  47862. return true;
  47863. }
  47864. }
  47865. return false;
  47866. };
  47867. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  47868. /**
  47869. * Does this action manager has pointer triggers
  47870. * @return {boolean} whether or not it has pointer triggers
  47871. */
  47872. get: function () {
  47873. for (var index = 0; index < this.actions.length; index++) {
  47874. var action = this.actions[index];
  47875. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  47876. return true;
  47877. }
  47878. }
  47879. return false;
  47880. },
  47881. enumerable: true,
  47882. configurable: true
  47883. });
  47884. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  47885. /**
  47886. * Does this action manager has pick triggers
  47887. * @return {boolean} whether or not it has pick triggers
  47888. */
  47889. get: function () {
  47890. for (var index = 0; index < this.actions.length; index++) {
  47891. var action = this.actions[index];
  47892. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  47893. return true;
  47894. }
  47895. }
  47896. return false;
  47897. },
  47898. enumerable: true,
  47899. configurable: true
  47900. });
  47901. Object.defineProperty(ActionManager, "HasTriggers", {
  47902. /**
  47903. * Does exist one action manager with at least one trigger
  47904. * @return {boolean} whether or not it exists one action manager with one trigger
  47905. **/
  47906. get: function () {
  47907. for (var t in ActionManager.Triggers) {
  47908. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47909. return true;
  47910. }
  47911. }
  47912. return false;
  47913. },
  47914. enumerable: true,
  47915. configurable: true
  47916. });
  47917. Object.defineProperty(ActionManager, "HasPickTriggers", {
  47918. /**
  47919. * Does exist one action manager with at least one pick trigger
  47920. * @return {boolean} whether or not it exists one action manager with one pick trigger
  47921. **/
  47922. get: function () {
  47923. for (var t in ActionManager.Triggers) {
  47924. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47925. var t_int = parseInt(t);
  47926. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  47927. return true;
  47928. }
  47929. }
  47930. }
  47931. return false;
  47932. },
  47933. enumerable: true,
  47934. configurable: true
  47935. });
  47936. /**
  47937. * Does exist one action manager that handles actions of a given trigger
  47938. * @param {number} trigger - the trigger to be tested
  47939. * @return {boolean} whether the trigger is handeled by at least one action manager
  47940. **/
  47941. ActionManager.HasSpecificTrigger = function (trigger) {
  47942. for (var t in ActionManager.Triggers) {
  47943. if (ActionManager.Triggers.hasOwnProperty(t)) {
  47944. var t_int = parseInt(t);
  47945. if (t_int === trigger) {
  47946. return true;
  47947. }
  47948. }
  47949. }
  47950. return false;
  47951. };
  47952. /**
  47953. * Registers an action to this action manager
  47954. * @param {BABYLON.Action} action - the action to be registered
  47955. * @return {BABYLON.Action} the action amended (prepared) after registration
  47956. */
  47957. ActionManager.prototype.registerAction = function (action) {
  47958. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  47959. if (this.getScene().actionManager !== this) {
  47960. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  47961. return null;
  47962. }
  47963. }
  47964. this.actions.push(action);
  47965. if (ActionManager.Triggers[action.trigger]) {
  47966. ActionManager.Triggers[action.trigger]++;
  47967. }
  47968. else {
  47969. ActionManager.Triggers[action.trigger] = 1;
  47970. }
  47971. action._actionManager = this;
  47972. action._prepare();
  47973. return action;
  47974. };
  47975. /**
  47976. * Unregisters an action to this action manager
  47977. * @param action The action to be unregistered
  47978. * @return whether the action has been unregistered
  47979. */
  47980. ActionManager.prototype.unregisterAction = function (action) {
  47981. var index = this.actions.indexOf(action);
  47982. if (index !== -1) {
  47983. this.actions.splice(index, 1);
  47984. ActionManager.Triggers[action.trigger] -= 1;
  47985. if (ActionManager.Triggers[action.trigger] === 0) {
  47986. delete ActionManager.Triggers[action.trigger];
  47987. }
  47988. delete action._actionManager;
  47989. return true;
  47990. }
  47991. return false;
  47992. };
  47993. /**
  47994. * Process a specific trigger
  47995. * @param {number} trigger - the trigger to process
  47996. * @param evt {BABYLON.ActionEvent} the event details to be processed
  47997. */
  47998. ActionManager.prototype.processTrigger = function (trigger, evt) {
  47999. for (var index = 0; index < this.actions.length; index++) {
  48000. var action = this.actions[index];
  48001. if (action.trigger === trigger) {
  48002. if (evt) {
  48003. if (trigger === ActionManager.OnKeyUpTrigger
  48004. || trigger === ActionManager.OnKeyDownTrigger) {
  48005. var parameter = action.getTriggerParameter();
  48006. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  48007. if (!parameter.toLowerCase) {
  48008. continue;
  48009. }
  48010. var lowerCase = parameter.toLowerCase();
  48011. if (lowerCase !== evt.sourceEvent.key) {
  48012. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  48013. var actualkey = String.fromCharCode(unicode).toLowerCase();
  48014. if (actualkey !== lowerCase) {
  48015. continue;
  48016. }
  48017. }
  48018. }
  48019. }
  48020. }
  48021. action._executeCurrent(evt);
  48022. }
  48023. }
  48024. };
  48025. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  48026. var properties = propertyPath.split(".");
  48027. for (var index = 0; index < properties.length - 1; index++) {
  48028. target = target[properties[index]];
  48029. }
  48030. return target;
  48031. };
  48032. ActionManager.prototype._getProperty = function (propertyPath) {
  48033. var properties = propertyPath.split(".");
  48034. return properties[properties.length - 1];
  48035. };
  48036. ActionManager.prototype.serialize = function (name) {
  48037. var root = {
  48038. children: new Array(),
  48039. name: name,
  48040. type: 3,
  48041. properties: new Array() // Empty for root but required
  48042. };
  48043. for (var i = 0; i < this.actions.length; i++) {
  48044. var triggerObject = {
  48045. type: 0,
  48046. children: new Array(),
  48047. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  48048. properties: new Array()
  48049. };
  48050. var triggerOptions = this.actions[i].triggerOptions;
  48051. if (triggerOptions && typeof triggerOptions !== "number") {
  48052. if (triggerOptions.parameter instanceof BABYLON.Node) {
  48053. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  48054. }
  48055. else {
  48056. var parameter = {};
  48057. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  48058. if (triggerOptions.parameter.mesh) {
  48059. parameter._meshId = triggerOptions.parameter.mesh.id;
  48060. }
  48061. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  48062. }
  48063. }
  48064. // Serialize child action, recursively
  48065. this.actions[i].serialize(triggerObject);
  48066. // Add serialized trigger
  48067. root.children.push(triggerObject);
  48068. }
  48069. return root;
  48070. };
  48071. ActionManager.Parse = function (parsedActions, object, scene) {
  48072. var actionManager = new ActionManager(scene);
  48073. if (object === null)
  48074. scene.actionManager = actionManager;
  48075. else
  48076. object.actionManager = actionManager;
  48077. // instanciate a new object
  48078. var instanciate = function (name, params) {
  48079. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  48080. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  48081. newInstance.constructor.apply(newInstance, params);
  48082. return newInstance;
  48083. };
  48084. var parseParameter = function (name, value, target, propertyPath) {
  48085. if (propertyPath === null) {
  48086. // String, boolean or float
  48087. var floatValue = parseFloat(value);
  48088. if (value === "true" || value === "false")
  48089. return value === "true";
  48090. else
  48091. return isNaN(floatValue) ? value : floatValue;
  48092. }
  48093. var effectiveTarget = propertyPath.split(".");
  48094. var values = value.split(",");
  48095. // Get effective Target
  48096. for (var i = 0; i < effectiveTarget.length; i++) {
  48097. target = target[effectiveTarget[i]];
  48098. }
  48099. // Return appropriate value with its type
  48100. if (typeof (target) === "boolean")
  48101. return values[0] === "true";
  48102. if (typeof (target) === "string")
  48103. return values[0];
  48104. // Parameters with multiple values such as Vector3 etc.
  48105. var split = new Array();
  48106. for (var i = 0; i < values.length; i++)
  48107. split.push(parseFloat(values[i]));
  48108. if (target instanceof BABYLON.Vector3)
  48109. return BABYLON.Vector3.FromArray(split);
  48110. if (target instanceof BABYLON.Vector4)
  48111. return BABYLON.Vector4.FromArray(split);
  48112. if (target instanceof BABYLON.Color3)
  48113. return BABYLON.Color3.FromArray(split);
  48114. if (target instanceof BABYLON.Color4)
  48115. return BABYLON.Color4.FromArray(split);
  48116. return parseFloat(values[0]);
  48117. };
  48118. // traverse graph per trigger
  48119. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  48120. if (combineArray === void 0) { combineArray = null; }
  48121. if (parsedAction.detached)
  48122. return;
  48123. var parameters = new Array();
  48124. var target = null;
  48125. var propertyPath = null;
  48126. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  48127. // Parameters
  48128. if (parsedAction.type === 2)
  48129. parameters.push(actionManager);
  48130. else
  48131. parameters.push(trigger);
  48132. if (combine) {
  48133. var actions = new Array();
  48134. for (var j = 0; j < parsedAction.combine.length; j++) {
  48135. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  48136. }
  48137. parameters.push(actions);
  48138. }
  48139. else {
  48140. for (var i = 0; i < parsedAction.properties.length; i++) {
  48141. var value = parsedAction.properties[i].value;
  48142. var name = parsedAction.properties[i].name;
  48143. var targetType = parsedAction.properties[i].targetType;
  48144. if (name === "target")
  48145. if (targetType !== null && targetType === "SceneProperties")
  48146. value = target = scene;
  48147. else
  48148. value = target = scene.getNodeByName(value);
  48149. else if (name === "parent")
  48150. value = scene.getNodeByName(value);
  48151. else if (name === "sound")
  48152. value = scene.getSoundByName(value);
  48153. else if (name !== "propertyPath") {
  48154. if (parsedAction.type === 2 && name === "operator")
  48155. value = BABYLON.ValueCondition[value];
  48156. else
  48157. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  48158. }
  48159. else {
  48160. propertyPath = value;
  48161. }
  48162. parameters.push(value);
  48163. }
  48164. }
  48165. if (combineArray === null) {
  48166. parameters.push(condition);
  48167. }
  48168. else {
  48169. parameters.push(null);
  48170. }
  48171. // If interpolate value action
  48172. if (parsedAction.name === "InterpolateValueAction") {
  48173. var param = parameters[parameters.length - 2];
  48174. parameters[parameters.length - 1] = param;
  48175. parameters[parameters.length - 2] = condition;
  48176. }
  48177. // Action or condition(s) and not CombineAction
  48178. var newAction = instanciate(parsedAction.name, parameters);
  48179. if (newAction instanceof BABYLON.Condition && condition !== null) {
  48180. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  48181. if (action)
  48182. action.then(nothing);
  48183. else
  48184. actionManager.registerAction(nothing);
  48185. action = nothing;
  48186. }
  48187. if (combineArray === null) {
  48188. if (newAction instanceof BABYLON.Condition) {
  48189. condition = newAction;
  48190. newAction = action;
  48191. }
  48192. else {
  48193. condition = null;
  48194. if (action)
  48195. action.then(newAction);
  48196. else
  48197. actionManager.registerAction(newAction);
  48198. }
  48199. }
  48200. else {
  48201. combineArray.push(newAction);
  48202. }
  48203. for (var i = 0; i < parsedAction.children.length; i++)
  48204. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  48205. };
  48206. // triggers
  48207. for (var i = 0; i < parsedActions.children.length; i++) {
  48208. var triggerParams;
  48209. var trigger = parsedActions.children[i];
  48210. if (trigger.properties.length > 0) {
  48211. var param = trigger.properties[0].value;
  48212. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  48213. if (value._meshId) {
  48214. value.mesh = scene.getMeshByID(value._meshId);
  48215. }
  48216. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  48217. }
  48218. else
  48219. triggerParams = ActionManager[trigger.name];
  48220. for (var j = 0; j < trigger.children.length; j++) {
  48221. if (!trigger.detached)
  48222. traverse(trigger.children[j], triggerParams, null, null);
  48223. }
  48224. }
  48225. };
  48226. ActionManager.GetTriggerName = function (trigger) {
  48227. switch (trigger) {
  48228. case 0: return "NothingTrigger";
  48229. case 1: return "OnPickTrigger";
  48230. case 2: return "OnLeftPickTrigger";
  48231. case 3: return "OnRightPickTrigger";
  48232. case 4: return "OnCenterPickTrigger";
  48233. case 5: return "OnPickDownTrigger";
  48234. case 6: return "OnPickUpTrigger";
  48235. case 7: return "OnLongPressTrigger";
  48236. case 8: return "OnPointerOverTrigger";
  48237. case 9: return "OnPointerOutTrigger";
  48238. case 10: return "OnEveryFrameTrigger";
  48239. case 11: return "OnIntersectionEnterTrigger";
  48240. case 12: return "OnIntersectionExitTrigger";
  48241. case 13: return "OnKeyDownTrigger";
  48242. case 14: return "OnKeyUpTrigger";
  48243. case 15: return "OnPickOutTrigger";
  48244. default: return "";
  48245. }
  48246. };
  48247. // Statics
  48248. ActionManager._NothingTrigger = 0;
  48249. ActionManager._OnPickTrigger = 1;
  48250. ActionManager._OnLeftPickTrigger = 2;
  48251. ActionManager._OnRightPickTrigger = 3;
  48252. ActionManager._OnCenterPickTrigger = 4;
  48253. ActionManager._OnPickDownTrigger = 5;
  48254. ActionManager._OnDoublePickTrigger = 6;
  48255. ActionManager._OnPickUpTrigger = 7;
  48256. ActionManager._OnLongPressTrigger = 8;
  48257. ActionManager._OnPointerOverTrigger = 9;
  48258. ActionManager._OnPointerOutTrigger = 10;
  48259. ActionManager._OnEveryFrameTrigger = 11;
  48260. ActionManager._OnIntersectionEnterTrigger = 12;
  48261. ActionManager._OnIntersectionExitTrigger = 13;
  48262. ActionManager._OnKeyDownTrigger = 14;
  48263. ActionManager._OnKeyUpTrigger = 15;
  48264. ActionManager._OnPickOutTrigger = 16;
  48265. ActionManager.Triggers = {};
  48266. return ActionManager;
  48267. }());
  48268. BABYLON.ActionManager = ActionManager;
  48269. })(BABYLON || (BABYLON = {}));
  48270. //# sourceMappingURL=babylon.actionManager.js.map
  48271. var BABYLON;
  48272. (function (BABYLON) {
  48273. var InterpolateValueAction = /** @class */ (function (_super) {
  48274. __extends(InterpolateValueAction, _super);
  48275. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  48276. if (duration === void 0) { duration = 1000; }
  48277. var _this = _super.call(this, triggerOptions, condition) || this;
  48278. _this.propertyPath = propertyPath;
  48279. _this.value = value;
  48280. _this.duration = duration;
  48281. _this.stopOtherAnimations = stopOtherAnimations;
  48282. _this.onInterpolationDone = onInterpolationDone;
  48283. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  48284. _this._target = _this._effectiveTarget = target;
  48285. return _this;
  48286. }
  48287. InterpolateValueAction.prototype._prepare = function () {
  48288. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48289. this._property = this._getProperty(this.propertyPath);
  48290. };
  48291. InterpolateValueAction.prototype.execute = function () {
  48292. var _this = this;
  48293. var scene = this._actionManager.getScene();
  48294. var keys = [
  48295. {
  48296. frame: 0,
  48297. value: this._effectiveTarget[this._property]
  48298. }, {
  48299. frame: 100,
  48300. value: this.value
  48301. }
  48302. ];
  48303. var dataType;
  48304. if (typeof this.value === "number") {
  48305. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  48306. }
  48307. else if (this.value instanceof BABYLON.Color3) {
  48308. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  48309. }
  48310. else if (this.value instanceof BABYLON.Vector3) {
  48311. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  48312. }
  48313. else if (this.value instanceof BABYLON.Matrix) {
  48314. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  48315. }
  48316. else if (this.value instanceof BABYLON.Quaternion) {
  48317. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  48318. }
  48319. else {
  48320. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  48321. return;
  48322. }
  48323. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  48324. animation.setKeys(keys);
  48325. if (this.stopOtherAnimations) {
  48326. scene.stopAnimation(this._effectiveTarget);
  48327. }
  48328. var wrapper = function () {
  48329. _this.onInterpolationDoneObservable.notifyObservers(_this);
  48330. if (_this.onInterpolationDone) {
  48331. _this.onInterpolationDone();
  48332. }
  48333. };
  48334. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  48335. };
  48336. InterpolateValueAction.prototype.serialize = function (parent) {
  48337. return _super.prototype._serialize.call(this, {
  48338. name: "InterpolateValueAction",
  48339. properties: [
  48340. BABYLON.Action._GetTargetProperty(this._target),
  48341. { name: "propertyPath", value: this.propertyPath },
  48342. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48343. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  48344. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  48345. ]
  48346. }, parent);
  48347. };
  48348. return InterpolateValueAction;
  48349. }(BABYLON.Action));
  48350. BABYLON.InterpolateValueAction = InterpolateValueAction;
  48351. })(BABYLON || (BABYLON = {}));
  48352. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  48353. var BABYLON;
  48354. (function (BABYLON) {
  48355. var SwitchBooleanAction = /** @class */ (function (_super) {
  48356. __extends(SwitchBooleanAction, _super);
  48357. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  48358. var _this = _super.call(this, triggerOptions, condition) || this;
  48359. _this.propertyPath = propertyPath;
  48360. _this._target = _this._effectiveTarget = target;
  48361. return _this;
  48362. }
  48363. SwitchBooleanAction.prototype._prepare = function () {
  48364. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48365. this._property = this._getProperty(this.propertyPath);
  48366. };
  48367. SwitchBooleanAction.prototype.execute = function () {
  48368. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  48369. };
  48370. SwitchBooleanAction.prototype.serialize = function (parent) {
  48371. return _super.prototype._serialize.call(this, {
  48372. name: "SwitchBooleanAction",
  48373. properties: [
  48374. BABYLON.Action._GetTargetProperty(this._target),
  48375. { name: "propertyPath", value: this.propertyPath }
  48376. ]
  48377. }, parent);
  48378. };
  48379. return SwitchBooleanAction;
  48380. }(BABYLON.Action));
  48381. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  48382. var SetStateAction = /** @class */ (function (_super) {
  48383. __extends(SetStateAction, _super);
  48384. function SetStateAction(triggerOptions, target, value, condition) {
  48385. var _this = _super.call(this, triggerOptions, condition) || this;
  48386. _this.value = value;
  48387. _this._target = target;
  48388. return _this;
  48389. }
  48390. SetStateAction.prototype.execute = function () {
  48391. this._target.state = this.value;
  48392. };
  48393. SetStateAction.prototype.serialize = function (parent) {
  48394. return _super.prototype._serialize.call(this, {
  48395. name: "SetStateAction",
  48396. properties: [
  48397. BABYLON.Action._GetTargetProperty(this._target),
  48398. { name: "value", value: this.value }
  48399. ]
  48400. }, parent);
  48401. };
  48402. return SetStateAction;
  48403. }(BABYLON.Action));
  48404. BABYLON.SetStateAction = SetStateAction;
  48405. var SetValueAction = /** @class */ (function (_super) {
  48406. __extends(SetValueAction, _super);
  48407. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  48408. var _this = _super.call(this, triggerOptions, condition) || this;
  48409. _this.propertyPath = propertyPath;
  48410. _this.value = value;
  48411. _this._target = _this._effectiveTarget = target;
  48412. return _this;
  48413. }
  48414. SetValueAction.prototype._prepare = function () {
  48415. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48416. this._property = this._getProperty(this.propertyPath);
  48417. };
  48418. SetValueAction.prototype.execute = function () {
  48419. this._effectiveTarget[this._property] = this.value;
  48420. if (this._target.markAsDirty) {
  48421. this._target.markAsDirty(this._property);
  48422. }
  48423. };
  48424. SetValueAction.prototype.serialize = function (parent) {
  48425. return _super.prototype._serialize.call(this, {
  48426. name: "SetValueAction",
  48427. properties: [
  48428. BABYLON.Action._GetTargetProperty(this._target),
  48429. { name: "propertyPath", value: this.propertyPath },
  48430. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48431. ]
  48432. }, parent);
  48433. };
  48434. return SetValueAction;
  48435. }(BABYLON.Action));
  48436. BABYLON.SetValueAction = SetValueAction;
  48437. var IncrementValueAction = /** @class */ (function (_super) {
  48438. __extends(IncrementValueAction, _super);
  48439. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  48440. var _this = _super.call(this, triggerOptions, condition) || this;
  48441. _this.propertyPath = propertyPath;
  48442. _this.value = value;
  48443. _this._target = _this._effectiveTarget = target;
  48444. return _this;
  48445. }
  48446. IncrementValueAction.prototype._prepare = function () {
  48447. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  48448. this._property = this._getProperty(this.propertyPath);
  48449. if (typeof this._effectiveTarget[this._property] !== "number") {
  48450. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  48451. }
  48452. };
  48453. IncrementValueAction.prototype.execute = function () {
  48454. this._effectiveTarget[this._property] += this.value;
  48455. if (this._target.markAsDirty) {
  48456. this._target.markAsDirty(this._property);
  48457. }
  48458. };
  48459. IncrementValueAction.prototype.serialize = function (parent) {
  48460. return _super.prototype._serialize.call(this, {
  48461. name: "IncrementValueAction",
  48462. properties: [
  48463. BABYLON.Action._GetTargetProperty(this._target),
  48464. { name: "propertyPath", value: this.propertyPath },
  48465. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  48466. ]
  48467. }, parent);
  48468. };
  48469. return IncrementValueAction;
  48470. }(BABYLON.Action));
  48471. BABYLON.IncrementValueAction = IncrementValueAction;
  48472. var PlayAnimationAction = /** @class */ (function (_super) {
  48473. __extends(PlayAnimationAction, _super);
  48474. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  48475. var _this = _super.call(this, triggerOptions, condition) || this;
  48476. _this.from = from;
  48477. _this.to = to;
  48478. _this.loop = loop;
  48479. _this._target = target;
  48480. return _this;
  48481. }
  48482. PlayAnimationAction.prototype._prepare = function () {
  48483. };
  48484. PlayAnimationAction.prototype.execute = function () {
  48485. var scene = this._actionManager.getScene();
  48486. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  48487. };
  48488. PlayAnimationAction.prototype.serialize = function (parent) {
  48489. return _super.prototype._serialize.call(this, {
  48490. name: "PlayAnimationAction",
  48491. properties: [
  48492. BABYLON.Action._GetTargetProperty(this._target),
  48493. { name: "from", value: String(this.from) },
  48494. { name: "to", value: String(this.to) },
  48495. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  48496. ]
  48497. }, parent);
  48498. };
  48499. return PlayAnimationAction;
  48500. }(BABYLON.Action));
  48501. BABYLON.PlayAnimationAction = PlayAnimationAction;
  48502. var StopAnimationAction = /** @class */ (function (_super) {
  48503. __extends(StopAnimationAction, _super);
  48504. function StopAnimationAction(triggerOptions, target, condition) {
  48505. var _this = _super.call(this, triggerOptions, condition) || this;
  48506. _this._target = target;
  48507. return _this;
  48508. }
  48509. StopAnimationAction.prototype._prepare = function () {
  48510. };
  48511. StopAnimationAction.prototype.execute = function () {
  48512. var scene = this._actionManager.getScene();
  48513. scene.stopAnimation(this._target);
  48514. };
  48515. StopAnimationAction.prototype.serialize = function (parent) {
  48516. return _super.prototype._serialize.call(this, {
  48517. name: "StopAnimationAction",
  48518. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  48519. }, parent);
  48520. };
  48521. return StopAnimationAction;
  48522. }(BABYLON.Action));
  48523. BABYLON.StopAnimationAction = StopAnimationAction;
  48524. var DoNothingAction = /** @class */ (function (_super) {
  48525. __extends(DoNothingAction, _super);
  48526. function DoNothingAction(triggerOptions, condition) {
  48527. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  48528. return _super.call(this, triggerOptions, condition) || this;
  48529. }
  48530. DoNothingAction.prototype.execute = function () {
  48531. };
  48532. DoNothingAction.prototype.serialize = function (parent) {
  48533. return _super.prototype._serialize.call(this, {
  48534. name: "DoNothingAction",
  48535. properties: []
  48536. }, parent);
  48537. };
  48538. return DoNothingAction;
  48539. }(BABYLON.Action));
  48540. BABYLON.DoNothingAction = DoNothingAction;
  48541. var CombineAction = /** @class */ (function (_super) {
  48542. __extends(CombineAction, _super);
  48543. function CombineAction(triggerOptions, children, condition) {
  48544. var _this = _super.call(this, triggerOptions, condition) || this;
  48545. _this.children = children;
  48546. return _this;
  48547. }
  48548. CombineAction.prototype._prepare = function () {
  48549. for (var index = 0; index < this.children.length; index++) {
  48550. this.children[index]._actionManager = this._actionManager;
  48551. this.children[index]._prepare();
  48552. }
  48553. };
  48554. CombineAction.prototype.execute = function (evt) {
  48555. for (var index = 0; index < this.children.length; index++) {
  48556. this.children[index].execute(evt);
  48557. }
  48558. };
  48559. CombineAction.prototype.serialize = function (parent) {
  48560. var serializationObject = _super.prototype._serialize.call(this, {
  48561. name: "CombineAction",
  48562. properties: [],
  48563. combine: []
  48564. }, parent);
  48565. for (var i = 0; i < this.children.length; i++) {
  48566. serializationObject.combine.push(this.children[i].serialize(null));
  48567. }
  48568. return serializationObject;
  48569. };
  48570. return CombineAction;
  48571. }(BABYLON.Action));
  48572. BABYLON.CombineAction = CombineAction;
  48573. var ExecuteCodeAction = /** @class */ (function (_super) {
  48574. __extends(ExecuteCodeAction, _super);
  48575. function ExecuteCodeAction(triggerOptions, func, condition) {
  48576. var _this = _super.call(this, triggerOptions, condition) || this;
  48577. _this.func = func;
  48578. return _this;
  48579. }
  48580. ExecuteCodeAction.prototype.execute = function (evt) {
  48581. this.func(evt);
  48582. };
  48583. return ExecuteCodeAction;
  48584. }(BABYLON.Action));
  48585. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  48586. var SetParentAction = /** @class */ (function (_super) {
  48587. __extends(SetParentAction, _super);
  48588. function SetParentAction(triggerOptions, target, parent, condition) {
  48589. var _this = _super.call(this, triggerOptions, condition) || this;
  48590. _this._target = target;
  48591. _this._parent = parent;
  48592. return _this;
  48593. }
  48594. SetParentAction.prototype._prepare = function () {
  48595. };
  48596. SetParentAction.prototype.execute = function () {
  48597. if (this._target.parent === this._parent) {
  48598. return;
  48599. }
  48600. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  48601. invertParentWorldMatrix.invert();
  48602. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  48603. this._target.parent = this._parent;
  48604. };
  48605. SetParentAction.prototype.serialize = function (parent) {
  48606. return _super.prototype._serialize.call(this, {
  48607. name: "SetParentAction",
  48608. properties: [
  48609. BABYLON.Action._GetTargetProperty(this._target),
  48610. BABYLON.Action._GetTargetProperty(this._parent),
  48611. ]
  48612. }, parent);
  48613. };
  48614. return SetParentAction;
  48615. }(BABYLON.Action));
  48616. BABYLON.SetParentAction = SetParentAction;
  48617. var PlaySoundAction = /** @class */ (function (_super) {
  48618. __extends(PlaySoundAction, _super);
  48619. function PlaySoundAction(triggerOptions, sound, condition) {
  48620. var _this = _super.call(this, triggerOptions, condition) || this;
  48621. _this._sound = sound;
  48622. return _this;
  48623. }
  48624. PlaySoundAction.prototype._prepare = function () {
  48625. };
  48626. PlaySoundAction.prototype.execute = function () {
  48627. if (this._sound !== undefined)
  48628. this._sound.play();
  48629. };
  48630. PlaySoundAction.prototype.serialize = function (parent) {
  48631. return _super.prototype._serialize.call(this, {
  48632. name: "PlaySoundAction",
  48633. properties: [{ name: "sound", value: this._sound.name }]
  48634. }, parent);
  48635. };
  48636. return PlaySoundAction;
  48637. }(BABYLON.Action));
  48638. BABYLON.PlaySoundAction = PlaySoundAction;
  48639. var StopSoundAction = /** @class */ (function (_super) {
  48640. __extends(StopSoundAction, _super);
  48641. function StopSoundAction(triggerOptions, sound, condition) {
  48642. var _this = _super.call(this, triggerOptions, condition) || this;
  48643. _this._sound = sound;
  48644. return _this;
  48645. }
  48646. StopSoundAction.prototype._prepare = function () {
  48647. };
  48648. StopSoundAction.prototype.execute = function () {
  48649. if (this._sound !== undefined)
  48650. this._sound.stop();
  48651. };
  48652. StopSoundAction.prototype.serialize = function (parent) {
  48653. return _super.prototype._serialize.call(this, {
  48654. name: "StopSoundAction",
  48655. properties: [{ name: "sound", value: this._sound.name }]
  48656. }, parent);
  48657. };
  48658. return StopSoundAction;
  48659. }(BABYLON.Action));
  48660. BABYLON.StopSoundAction = StopSoundAction;
  48661. })(BABYLON || (BABYLON = {}));
  48662. //# sourceMappingURL=babylon.directActions.js.map
  48663. var BABYLON;
  48664. (function (BABYLON) {
  48665. var SpriteManager = /** @class */ (function () {
  48666. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  48667. if (epsilon === void 0) { epsilon = 0.01; }
  48668. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  48669. this.name = name;
  48670. this.sprites = new Array();
  48671. this.renderingGroupId = 0;
  48672. this.layerMask = 0x0FFFFFFF;
  48673. this.fogEnabled = true;
  48674. this.isPickable = false;
  48675. /**
  48676. * An event triggered when the manager is disposed.
  48677. * @type {BABYLON.Observable}
  48678. */
  48679. this.onDisposeObservable = new BABYLON.Observable();
  48680. this._vertexBuffers = {};
  48681. this._capacity = capacity;
  48682. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  48683. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48684. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48685. if (cellSize.width && cellSize.height) {
  48686. this.cellWidth = cellSize.width;
  48687. this.cellHeight = cellSize.height;
  48688. }
  48689. else if (cellSize !== undefined) {
  48690. this.cellWidth = cellSize;
  48691. this.cellHeight = cellSize;
  48692. }
  48693. else {
  48694. return;
  48695. }
  48696. this._epsilon = epsilon;
  48697. this._scene = scene;
  48698. this._scene.spriteManagers.push(this);
  48699. var indices = [];
  48700. var index = 0;
  48701. for (var count = 0; count < capacity; count++) {
  48702. indices.push(index);
  48703. indices.push(index + 1);
  48704. indices.push(index + 2);
  48705. indices.push(index);
  48706. indices.push(index + 2);
  48707. indices.push(index + 3);
  48708. index += 4;
  48709. }
  48710. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  48711. // VBO
  48712. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  48713. this._vertexData = new Float32Array(capacity * 16 * 4);
  48714. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  48715. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  48716. var options = this._buffer.createVertexBuffer("options", 4, 4);
  48717. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  48718. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  48719. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  48720. this._vertexBuffers["options"] = options;
  48721. this._vertexBuffers["cellInfo"] = cellInfo;
  48722. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  48723. // Effects
  48724. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  48725. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  48726. }
  48727. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  48728. set: function (callback) {
  48729. if (this._onDisposeObserver) {
  48730. this.onDisposeObservable.remove(this._onDisposeObserver);
  48731. }
  48732. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  48733. },
  48734. enumerable: true,
  48735. configurable: true
  48736. });
  48737. Object.defineProperty(SpriteManager.prototype, "texture", {
  48738. get: function () {
  48739. return this._spriteTexture;
  48740. },
  48741. set: function (value) {
  48742. this._spriteTexture = value;
  48743. },
  48744. enumerable: true,
  48745. configurable: true
  48746. });
  48747. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  48748. var arrayOffset = index * 16;
  48749. if (offsetX === 0)
  48750. offsetX = this._epsilon;
  48751. else if (offsetX === 1)
  48752. offsetX = 1 - this._epsilon;
  48753. if (offsetY === 0)
  48754. offsetY = this._epsilon;
  48755. else if (offsetY === 1)
  48756. offsetY = 1 - this._epsilon;
  48757. this._vertexData[arrayOffset] = sprite.position.x;
  48758. this._vertexData[arrayOffset + 1] = sprite.position.y;
  48759. this._vertexData[arrayOffset + 2] = sprite.position.z;
  48760. this._vertexData[arrayOffset + 3] = sprite.angle;
  48761. this._vertexData[arrayOffset + 4] = sprite.width;
  48762. this._vertexData[arrayOffset + 5] = sprite.height;
  48763. this._vertexData[arrayOffset + 6] = offsetX;
  48764. this._vertexData[arrayOffset + 7] = offsetY;
  48765. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  48766. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  48767. var offset = (sprite.cellIndex / rowSize) >> 0;
  48768. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  48769. this._vertexData[arrayOffset + 11] = offset;
  48770. // Color
  48771. this._vertexData[arrayOffset + 12] = sprite.color.r;
  48772. this._vertexData[arrayOffset + 13] = sprite.color.g;
  48773. this._vertexData[arrayOffset + 14] = sprite.color.b;
  48774. this._vertexData[arrayOffset + 15] = sprite.color.a;
  48775. };
  48776. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  48777. var count = Math.min(this._capacity, this.sprites.length);
  48778. var min = BABYLON.Vector3.Zero();
  48779. var max = BABYLON.Vector3.Zero();
  48780. var distance = Number.MAX_VALUE;
  48781. var currentSprite = null;
  48782. var cameraSpacePosition = BABYLON.Vector3.Zero();
  48783. var cameraView = camera.getViewMatrix();
  48784. for (var index = 0; index < count; index++) {
  48785. var sprite = this.sprites[index];
  48786. if (!sprite) {
  48787. continue;
  48788. }
  48789. if (predicate) {
  48790. if (!predicate(sprite)) {
  48791. continue;
  48792. }
  48793. }
  48794. else if (!sprite.isPickable) {
  48795. continue;
  48796. }
  48797. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  48798. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  48799. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  48800. if (ray.intersectsBoxMinMax(min, max)) {
  48801. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  48802. if (distance > currentDistance) {
  48803. distance = currentDistance;
  48804. currentSprite = sprite;
  48805. if (fastCheck) {
  48806. break;
  48807. }
  48808. }
  48809. }
  48810. }
  48811. if (currentSprite) {
  48812. var result = new BABYLON.PickingInfo();
  48813. result.hit = true;
  48814. result.pickedSprite = currentSprite;
  48815. result.distance = distance;
  48816. return result;
  48817. }
  48818. return null;
  48819. };
  48820. SpriteManager.prototype.render = function () {
  48821. // Check
  48822. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  48823. return;
  48824. var engine = this._scene.getEngine();
  48825. var baseSize = this._spriteTexture.getBaseSize();
  48826. // Sprites
  48827. var deltaTime = engine.getDeltaTime();
  48828. var max = Math.min(this._capacity, this.sprites.length);
  48829. var rowSize = baseSize.width / this.cellWidth;
  48830. var offset = 0;
  48831. for (var index = 0; index < max; index++) {
  48832. var sprite = this.sprites[index];
  48833. if (!sprite) {
  48834. continue;
  48835. }
  48836. sprite._animate(deltaTime);
  48837. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  48838. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  48839. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  48840. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  48841. }
  48842. this._buffer.update(this._vertexData);
  48843. // Render
  48844. var effect = this._effectBase;
  48845. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48846. effect = this._effectFog;
  48847. }
  48848. engine.enableEffect(effect);
  48849. var viewMatrix = this._scene.getViewMatrix();
  48850. effect.setTexture("diffuseSampler", this._spriteTexture);
  48851. effect.setMatrix("view", viewMatrix);
  48852. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  48853. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  48854. // Fog
  48855. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  48856. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  48857. effect.setColor3("vFogColor", this._scene.fogColor);
  48858. }
  48859. // VBOs
  48860. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  48861. // Draw order
  48862. engine.setDepthFunctionToLessOrEqual();
  48863. effect.setBool("alphaTest", true);
  48864. engine.setColorWrite(false);
  48865. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48866. engine.setColorWrite(true);
  48867. effect.setBool("alphaTest", false);
  48868. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48869. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  48870. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48871. };
  48872. SpriteManager.prototype.dispose = function () {
  48873. if (this._buffer) {
  48874. this._buffer.dispose();
  48875. this._buffer = null;
  48876. }
  48877. if (this._indexBuffer) {
  48878. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  48879. this._indexBuffer = null;
  48880. }
  48881. if (this._spriteTexture) {
  48882. this._spriteTexture.dispose();
  48883. this._spriteTexture = null;
  48884. }
  48885. // Remove from scene
  48886. var index = this._scene.spriteManagers.indexOf(this);
  48887. this._scene.spriteManagers.splice(index, 1);
  48888. // Callback
  48889. this.onDisposeObservable.notifyObservers(this);
  48890. this.onDisposeObservable.clear();
  48891. };
  48892. return SpriteManager;
  48893. }());
  48894. BABYLON.SpriteManager = SpriteManager;
  48895. })(BABYLON || (BABYLON = {}));
  48896. //# sourceMappingURL=babylon.spriteManager.js.map
  48897. var BABYLON;
  48898. (function (BABYLON) {
  48899. var Sprite = /** @class */ (function () {
  48900. function Sprite(name, manager) {
  48901. this.name = name;
  48902. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  48903. this.width = 1.0;
  48904. this.height = 1.0;
  48905. this.angle = 0;
  48906. this.cellIndex = 0;
  48907. this.invertU = 0;
  48908. this.invertV = 0;
  48909. this.animations = new Array();
  48910. this.isPickable = false;
  48911. this._animationStarted = false;
  48912. this._loopAnimation = false;
  48913. this._fromIndex = 0;
  48914. this._toIndex = 0;
  48915. this._delay = 0;
  48916. this._direction = 1;
  48917. this._time = 0;
  48918. this._manager = manager;
  48919. this._manager.sprites.push(this);
  48920. this.position = BABYLON.Vector3.Zero();
  48921. }
  48922. Object.defineProperty(Sprite.prototype, "size", {
  48923. get: function () {
  48924. return this.width;
  48925. },
  48926. set: function (value) {
  48927. this.width = value;
  48928. this.height = value;
  48929. },
  48930. enumerable: true,
  48931. configurable: true
  48932. });
  48933. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  48934. this._fromIndex = from;
  48935. this._toIndex = to;
  48936. this._loopAnimation = loop;
  48937. this._delay = delay;
  48938. this._animationStarted = true;
  48939. this._direction = from < to ? 1 : -1;
  48940. this.cellIndex = from;
  48941. this._time = 0;
  48942. this._onAnimationEnd = onAnimationEnd;
  48943. };
  48944. Sprite.prototype.stopAnimation = function () {
  48945. this._animationStarted = false;
  48946. };
  48947. Sprite.prototype._animate = function (deltaTime) {
  48948. if (!this._animationStarted)
  48949. return;
  48950. this._time += deltaTime;
  48951. if (this._time > this._delay) {
  48952. this._time = this._time % this._delay;
  48953. this.cellIndex += this._direction;
  48954. if (this.cellIndex > this._toIndex) {
  48955. if (this._loopAnimation) {
  48956. this.cellIndex = this._fromIndex;
  48957. }
  48958. else {
  48959. this.cellIndex = this._toIndex;
  48960. this._animationStarted = false;
  48961. if (this._onAnimationEnd) {
  48962. this._onAnimationEnd();
  48963. }
  48964. if (this.disposeWhenFinishedAnimating) {
  48965. this.dispose();
  48966. }
  48967. }
  48968. }
  48969. }
  48970. };
  48971. Sprite.prototype.dispose = function () {
  48972. for (var i = 0; i < this._manager.sprites.length; i++) {
  48973. if (this._manager.sprites[i] == this) {
  48974. this._manager.sprites.splice(i, 1);
  48975. }
  48976. }
  48977. };
  48978. return Sprite;
  48979. }());
  48980. BABYLON.Sprite = Sprite;
  48981. })(BABYLON || (BABYLON = {}));
  48982. //# sourceMappingURL=babylon.sprite.js.map
  48983. var BABYLON;
  48984. (function (BABYLON) {
  48985. var IntersectionInfo = /** @class */ (function () {
  48986. function IntersectionInfo(bu, bv, distance) {
  48987. this.bu = bu;
  48988. this.bv = bv;
  48989. this.distance = distance;
  48990. this.faceId = 0;
  48991. this.subMeshId = 0;
  48992. }
  48993. return IntersectionInfo;
  48994. }());
  48995. BABYLON.IntersectionInfo = IntersectionInfo;
  48996. var PickingInfo = /** @class */ (function () {
  48997. function PickingInfo() {
  48998. this.hit = false;
  48999. this.distance = 0;
  49000. this.pickedPoint = null;
  49001. this.pickedMesh = null;
  49002. this.bu = 0;
  49003. this.bv = 0;
  49004. this.faceId = -1;
  49005. this.subMeshId = 0;
  49006. this.pickedSprite = null;
  49007. }
  49008. // Methods
  49009. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  49010. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  49011. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  49012. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  49013. return null;
  49014. }
  49015. var indices = this.pickedMesh.getIndices();
  49016. if (!indices) {
  49017. return null;
  49018. }
  49019. var result;
  49020. if (useVerticesNormals) {
  49021. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49022. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  49023. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  49024. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  49025. normal0 = normal0.scale(this.bu);
  49026. normal1 = normal1.scale(this.bv);
  49027. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  49028. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  49029. }
  49030. else {
  49031. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49032. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  49033. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  49034. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  49035. var p1p2 = vertex1.subtract(vertex2);
  49036. var p3p2 = vertex3.subtract(vertex2);
  49037. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  49038. }
  49039. if (useWorldCoordinates) {
  49040. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  49041. }
  49042. return BABYLON.Vector3.Normalize(result);
  49043. };
  49044. PickingInfo.prototype.getTextureCoordinates = function () {
  49045. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  49046. return null;
  49047. }
  49048. var indices = this.pickedMesh.getIndices();
  49049. if (!indices) {
  49050. return null;
  49051. }
  49052. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49053. if (!uvs) {
  49054. return null;
  49055. }
  49056. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  49057. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  49058. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  49059. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  49060. uv1 = uv1.scale(this.bu);
  49061. uv2 = uv2.scale(this.bv);
  49062. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  49063. };
  49064. return PickingInfo;
  49065. }());
  49066. BABYLON.PickingInfo = PickingInfo;
  49067. })(BABYLON || (BABYLON = {}));
  49068. //# sourceMappingURL=babylon.pickingInfo.js.map
  49069. var BABYLON;
  49070. (function (BABYLON) {
  49071. var Ray = /** @class */ (function () {
  49072. function Ray(origin, direction, length) {
  49073. if (length === void 0) { length = Number.MAX_VALUE; }
  49074. this.origin = origin;
  49075. this.direction = direction;
  49076. this.length = length;
  49077. }
  49078. // Methods
  49079. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  49080. var d = 0.0;
  49081. var maxValue = Number.MAX_VALUE;
  49082. var inv;
  49083. var min;
  49084. var max;
  49085. var temp;
  49086. if (Math.abs(this.direction.x) < 0.0000001) {
  49087. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  49088. return false;
  49089. }
  49090. }
  49091. else {
  49092. inv = 1.0 / this.direction.x;
  49093. min = (minimum.x - this.origin.x) * inv;
  49094. max = (maximum.x - this.origin.x) * inv;
  49095. if (max === -Infinity) {
  49096. max = Infinity;
  49097. }
  49098. if (min > max) {
  49099. temp = min;
  49100. min = max;
  49101. max = temp;
  49102. }
  49103. d = Math.max(min, d);
  49104. maxValue = Math.min(max, maxValue);
  49105. if (d > maxValue) {
  49106. return false;
  49107. }
  49108. }
  49109. if (Math.abs(this.direction.y) < 0.0000001) {
  49110. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  49111. return false;
  49112. }
  49113. }
  49114. else {
  49115. inv = 1.0 / this.direction.y;
  49116. min = (minimum.y - this.origin.y) * inv;
  49117. max = (maximum.y - this.origin.y) * inv;
  49118. if (max === -Infinity) {
  49119. max = Infinity;
  49120. }
  49121. if (min > max) {
  49122. temp = min;
  49123. min = max;
  49124. max = temp;
  49125. }
  49126. d = Math.max(min, d);
  49127. maxValue = Math.min(max, maxValue);
  49128. if (d > maxValue) {
  49129. return false;
  49130. }
  49131. }
  49132. if (Math.abs(this.direction.z) < 0.0000001) {
  49133. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  49134. return false;
  49135. }
  49136. }
  49137. else {
  49138. inv = 1.0 / this.direction.z;
  49139. min = (minimum.z - this.origin.z) * inv;
  49140. max = (maximum.z - this.origin.z) * inv;
  49141. if (max === -Infinity) {
  49142. max = Infinity;
  49143. }
  49144. if (min > max) {
  49145. temp = min;
  49146. min = max;
  49147. max = temp;
  49148. }
  49149. d = Math.max(min, d);
  49150. maxValue = Math.min(max, maxValue);
  49151. if (d > maxValue) {
  49152. return false;
  49153. }
  49154. }
  49155. return true;
  49156. };
  49157. Ray.prototype.intersectsBox = function (box) {
  49158. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  49159. };
  49160. Ray.prototype.intersectsSphere = function (sphere) {
  49161. var x = sphere.center.x - this.origin.x;
  49162. var y = sphere.center.y - this.origin.y;
  49163. var z = sphere.center.z - this.origin.z;
  49164. var pyth = (x * x) + (y * y) + (z * z);
  49165. var rr = sphere.radius * sphere.radius;
  49166. if (pyth <= rr) {
  49167. return true;
  49168. }
  49169. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  49170. if (dot < 0.0) {
  49171. return false;
  49172. }
  49173. var temp = pyth - (dot * dot);
  49174. return temp <= rr;
  49175. };
  49176. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  49177. if (!this._edge1) {
  49178. this._edge1 = BABYLON.Vector3.Zero();
  49179. this._edge2 = BABYLON.Vector3.Zero();
  49180. this._pvec = BABYLON.Vector3.Zero();
  49181. this._tvec = BABYLON.Vector3.Zero();
  49182. this._qvec = BABYLON.Vector3.Zero();
  49183. }
  49184. vertex1.subtractToRef(vertex0, this._edge1);
  49185. vertex2.subtractToRef(vertex0, this._edge2);
  49186. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  49187. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  49188. if (det === 0) {
  49189. return null;
  49190. }
  49191. var invdet = 1 / det;
  49192. this.origin.subtractToRef(vertex0, this._tvec);
  49193. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  49194. if (bu < 0 || bu > 1.0) {
  49195. return null;
  49196. }
  49197. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  49198. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  49199. if (bv < 0 || bu + bv > 1.0) {
  49200. return null;
  49201. }
  49202. //check if the distance is longer than the predefined length.
  49203. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  49204. if (distance > this.length) {
  49205. return null;
  49206. }
  49207. return new BABYLON.IntersectionInfo(bu, bv, distance);
  49208. };
  49209. Ray.prototype.intersectsPlane = function (plane) {
  49210. var distance;
  49211. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  49212. if (Math.abs(result1) < 9.99999997475243E-07) {
  49213. return null;
  49214. }
  49215. else {
  49216. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  49217. distance = (-plane.d - result2) / result1;
  49218. if (distance < 0.0) {
  49219. if (distance < -9.99999997475243E-07) {
  49220. return null;
  49221. }
  49222. else {
  49223. return 0;
  49224. }
  49225. }
  49226. return distance;
  49227. }
  49228. };
  49229. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  49230. var tm = BABYLON.Tmp.Matrix[0];
  49231. mesh.getWorldMatrix().invertToRef(tm);
  49232. if (this._tmpRay) {
  49233. Ray.TransformToRef(this, tm, this._tmpRay);
  49234. }
  49235. else {
  49236. this._tmpRay = Ray.Transform(this, tm);
  49237. }
  49238. return mesh.intersects(this._tmpRay, fastCheck);
  49239. };
  49240. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  49241. if (results) {
  49242. results.length = 0;
  49243. }
  49244. else {
  49245. results = [];
  49246. }
  49247. for (var i = 0; i < meshes.length; i++) {
  49248. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  49249. if (pickInfo.hit) {
  49250. results.push(pickInfo);
  49251. }
  49252. }
  49253. results.sort(this._comparePickingInfo);
  49254. return results;
  49255. };
  49256. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  49257. if (pickingInfoA.distance < pickingInfoB.distance) {
  49258. return -1;
  49259. }
  49260. else if (pickingInfoA.distance > pickingInfoB.distance) {
  49261. return 1;
  49262. }
  49263. else {
  49264. return 0;
  49265. }
  49266. };
  49267. /**
  49268. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  49269. * @param sega the first point of the segment to test the intersection against
  49270. * @param segb the second point of the segment to test the intersection against
  49271. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  49272. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  49273. */
  49274. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  49275. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  49276. var u = segb.subtract(sega);
  49277. var v = rsegb.subtract(this.origin);
  49278. var w = sega.subtract(this.origin);
  49279. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  49280. var b = BABYLON.Vector3.Dot(u, v);
  49281. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  49282. var d = BABYLON.Vector3.Dot(u, w);
  49283. var e = BABYLON.Vector3.Dot(v, w);
  49284. var D = a * c - b * b; // always >= 0
  49285. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  49286. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  49287. // compute the line parameters of the two closest points
  49288. if (D < Ray.smallnum) {
  49289. sN = 0.0; // force using point P0 on segment S1
  49290. sD = 1.0; // to prevent possible division by 0.0 later
  49291. tN = e;
  49292. tD = c;
  49293. }
  49294. else {
  49295. sN = (b * e - c * d);
  49296. tN = (a * e - b * d);
  49297. if (sN < 0.0) {
  49298. sN = 0.0;
  49299. tN = e;
  49300. tD = c;
  49301. }
  49302. else if (sN > sD) {
  49303. sN = sD;
  49304. tN = e + b;
  49305. tD = c;
  49306. }
  49307. }
  49308. if (tN < 0.0) {
  49309. tN = 0.0;
  49310. // recompute sc for this edge
  49311. if (-d < 0.0) {
  49312. sN = 0.0;
  49313. }
  49314. else if (-d > a)
  49315. sN = sD;
  49316. else {
  49317. sN = -d;
  49318. sD = a;
  49319. }
  49320. }
  49321. else if (tN > tD) {
  49322. tN = tD;
  49323. // recompute sc for this edge
  49324. if ((-d + b) < 0.0) {
  49325. sN = 0;
  49326. }
  49327. else if ((-d + b) > a) {
  49328. sN = sD;
  49329. }
  49330. else {
  49331. sN = (-d + b);
  49332. sD = a;
  49333. }
  49334. }
  49335. // finally do the division to get sc and tc
  49336. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  49337. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  49338. // get the difference of the two closest points
  49339. var qtc = v.multiplyByFloats(tc, tc, tc);
  49340. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  49341. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  49342. if (isIntersected) {
  49343. return qtc.length();
  49344. }
  49345. return -1;
  49346. };
  49347. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49348. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  49349. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  49350. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  49351. this.direction.normalize();
  49352. return this;
  49353. };
  49354. // Statics
  49355. Ray.Zero = function () {
  49356. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  49357. };
  49358. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  49359. var result = Ray.Zero();
  49360. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  49361. };
  49362. /**
  49363. * 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
  49364. * transformed to the given world matrix.
  49365. * @param origin The origin point
  49366. * @param end The end point
  49367. * @param world a matrix to transform the ray to. Default is the identity matrix.
  49368. */
  49369. Ray.CreateNewFromTo = function (origin, end, world) {
  49370. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  49371. var direction = end.subtract(origin);
  49372. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  49373. direction.normalize();
  49374. return Ray.Transform(new Ray(origin, direction, length), world);
  49375. };
  49376. Ray.Transform = function (ray, matrix) {
  49377. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  49378. Ray.TransformToRef(ray, matrix, result);
  49379. return result;
  49380. };
  49381. Ray.TransformToRef = function (ray, matrix, result) {
  49382. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  49383. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  49384. result.length = ray.length;
  49385. var dir = result.direction;
  49386. var len = dir.length();
  49387. if (!(len === 0 || len === 1)) {
  49388. var num = 1.0 / len;
  49389. dir.x *= num;
  49390. dir.y *= num;
  49391. dir.z *= num;
  49392. result.length *= len;
  49393. }
  49394. };
  49395. Ray.smallnum = 0.00000001;
  49396. Ray.rayl = 10e8;
  49397. return Ray;
  49398. }());
  49399. BABYLON.Ray = Ray;
  49400. })(BABYLON || (BABYLON = {}));
  49401. //# sourceMappingURL=babylon.ray.js.map
  49402. var BABYLON;
  49403. (function (BABYLON) {
  49404. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  49405. if (boxMin.x > sphereCenter.x + sphereRadius)
  49406. return false;
  49407. if (sphereCenter.x - sphereRadius > boxMax.x)
  49408. return false;
  49409. if (boxMin.y > sphereCenter.y + sphereRadius)
  49410. return false;
  49411. if (sphereCenter.y - sphereRadius > boxMax.y)
  49412. return false;
  49413. if (boxMin.z > sphereCenter.z + sphereRadius)
  49414. return false;
  49415. if (sphereCenter.z - sphereRadius > boxMax.z)
  49416. return false;
  49417. return true;
  49418. };
  49419. var getLowestRoot = (function () {
  49420. var result = { root: 0, found: false };
  49421. return function (a, b, c, maxR) {
  49422. result.root = 0;
  49423. result.found = false;
  49424. var determinant = b * b - 4.0 * a * c;
  49425. if (determinant < 0)
  49426. return result;
  49427. var sqrtD = Math.sqrt(determinant);
  49428. var r1 = (-b - sqrtD) / (2.0 * a);
  49429. var r2 = (-b + sqrtD) / (2.0 * a);
  49430. if (r1 > r2) {
  49431. var temp = r2;
  49432. r2 = r1;
  49433. r1 = temp;
  49434. }
  49435. if (r1 > 0 && r1 < maxR) {
  49436. result.root = r1;
  49437. result.found = true;
  49438. return result;
  49439. }
  49440. if (r2 > 0 && r2 < maxR) {
  49441. result.root = r2;
  49442. result.found = true;
  49443. return result;
  49444. }
  49445. return result;
  49446. };
  49447. })();
  49448. var Collider = /** @class */ (function () {
  49449. function Collider() {
  49450. this._collisionPoint = BABYLON.Vector3.Zero();
  49451. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  49452. this._tempVector = BABYLON.Vector3.Zero();
  49453. this._tempVector2 = BABYLON.Vector3.Zero();
  49454. this._tempVector3 = BABYLON.Vector3.Zero();
  49455. this._tempVector4 = BABYLON.Vector3.Zero();
  49456. this._edge = BABYLON.Vector3.Zero();
  49457. this._baseToVertex = BABYLON.Vector3.Zero();
  49458. this._destinationPoint = BABYLON.Vector3.Zero();
  49459. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  49460. this._displacementVector = BABYLON.Vector3.Zero();
  49461. this._radius = BABYLON.Vector3.One();
  49462. this._retry = 0;
  49463. this._basePointWorld = BABYLON.Vector3.Zero();
  49464. this._velocityWorld = BABYLON.Vector3.Zero();
  49465. this._normalizedVelocity = BABYLON.Vector3.Zero();
  49466. this._collisionMask = -1;
  49467. }
  49468. Object.defineProperty(Collider.prototype, "collisionMask", {
  49469. get: function () {
  49470. return this._collisionMask;
  49471. },
  49472. set: function (mask) {
  49473. this._collisionMask = !isNaN(mask) ? mask : -1;
  49474. },
  49475. enumerable: true,
  49476. configurable: true
  49477. });
  49478. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  49479. /**
  49480. * Gets the plane normal used to compute the sliding response (in local space)
  49481. */
  49482. get: function () {
  49483. return this._slidePlaneNormal;
  49484. },
  49485. enumerable: true,
  49486. configurable: true
  49487. });
  49488. // Methods
  49489. Collider.prototype._initialize = function (source, dir, e) {
  49490. this._velocity = dir;
  49491. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  49492. this._basePoint = source;
  49493. source.multiplyToRef(this._radius, this._basePointWorld);
  49494. dir.multiplyToRef(this._radius, this._velocityWorld);
  49495. this._velocityWorldLength = this._velocityWorld.length();
  49496. this._epsilon = e;
  49497. this.collisionFound = false;
  49498. };
  49499. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  49500. pa.subtractToRef(point, this._tempVector);
  49501. pb.subtractToRef(point, this._tempVector2);
  49502. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  49503. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49504. if (d < 0)
  49505. return false;
  49506. pc.subtractToRef(point, this._tempVector3);
  49507. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  49508. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49509. if (d < 0)
  49510. return false;
  49511. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  49512. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  49513. return d >= 0;
  49514. };
  49515. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  49516. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  49517. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  49518. if (distance > this._velocityWorldLength + max + sphereRadius) {
  49519. return false;
  49520. }
  49521. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  49522. return false;
  49523. return true;
  49524. };
  49525. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  49526. var t0;
  49527. var embeddedInPlane = false;
  49528. //defensive programming, actually not needed.
  49529. if (!trianglePlaneArray) {
  49530. trianglePlaneArray = [];
  49531. }
  49532. if (!trianglePlaneArray[faceIndex]) {
  49533. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  49534. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  49535. }
  49536. var trianglePlane = trianglePlaneArray[faceIndex];
  49537. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  49538. return;
  49539. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  49540. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  49541. if (normalDotVelocity == 0) {
  49542. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  49543. return;
  49544. embeddedInPlane = true;
  49545. t0 = 0;
  49546. }
  49547. else {
  49548. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49549. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  49550. if (t0 > t1) {
  49551. var temp = t1;
  49552. t1 = t0;
  49553. t0 = temp;
  49554. }
  49555. if (t0 > 1.0 || t1 < 0.0)
  49556. return;
  49557. if (t0 < 0)
  49558. t0 = 0;
  49559. if (t0 > 1.0)
  49560. t0 = 1.0;
  49561. }
  49562. this._collisionPoint.copyFromFloats(0, 0, 0);
  49563. var found = false;
  49564. var t = 1.0;
  49565. if (!embeddedInPlane) {
  49566. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  49567. this._velocity.scaleToRef(t0, this._tempVector);
  49568. this._planeIntersectionPoint.addInPlace(this._tempVector);
  49569. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  49570. found = true;
  49571. t = t0;
  49572. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  49573. }
  49574. }
  49575. if (!found) {
  49576. var velocitySquaredLength = this._velocity.lengthSquared();
  49577. var a = velocitySquaredLength;
  49578. this._basePoint.subtractToRef(p1, this._tempVector);
  49579. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49580. var c = this._tempVector.lengthSquared() - 1.0;
  49581. var lowestRoot = getLowestRoot(a, b, c, t);
  49582. if (lowestRoot.found) {
  49583. t = lowestRoot.root;
  49584. found = true;
  49585. this._collisionPoint.copyFrom(p1);
  49586. }
  49587. this._basePoint.subtractToRef(p2, this._tempVector);
  49588. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49589. c = this._tempVector.lengthSquared() - 1.0;
  49590. lowestRoot = getLowestRoot(a, b, c, t);
  49591. if (lowestRoot.found) {
  49592. t = lowestRoot.root;
  49593. found = true;
  49594. this._collisionPoint.copyFrom(p2);
  49595. }
  49596. this._basePoint.subtractToRef(p3, this._tempVector);
  49597. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  49598. c = this._tempVector.lengthSquared() - 1.0;
  49599. lowestRoot = getLowestRoot(a, b, c, t);
  49600. if (lowestRoot.found) {
  49601. t = lowestRoot.root;
  49602. found = true;
  49603. this._collisionPoint.copyFrom(p3);
  49604. }
  49605. p2.subtractToRef(p1, this._edge);
  49606. p1.subtractToRef(this._basePoint, this._baseToVertex);
  49607. var edgeSquaredLength = this._edge.lengthSquared();
  49608. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49609. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49610. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49611. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49612. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49613. lowestRoot = getLowestRoot(a, b, c, t);
  49614. if (lowestRoot.found) {
  49615. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49616. if (f >= 0.0 && f <= 1.0) {
  49617. t = lowestRoot.root;
  49618. found = true;
  49619. this._edge.scaleInPlace(f);
  49620. p1.addToRef(this._edge, this._collisionPoint);
  49621. }
  49622. }
  49623. p3.subtractToRef(p2, this._edge);
  49624. p2.subtractToRef(this._basePoint, this._baseToVertex);
  49625. edgeSquaredLength = this._edge.lengthSquared();
  49626. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49627. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49628. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49629. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49630. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49631. lowestRoot = getLowestRoot(a, b, c, t);
  49632. if (lowestRoot.found) {
  49633. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49634. if (f >= 0.0 && f <= 1.0) {
  49635. t = lowestRoot.root;
  49636. found = true;
  49637. this._edge.scaleInPlace(f);
  49638. p2.addToRef(this._edge, this._collisionPoint);
  49639. }
  49640. }
  49641. p1.subtractToRef(p3, this._edge);
  49642. p3.subtractToRef(this._basePoint, this._baseToVertex);
  49643. edgeSquaredLength = this._edge.lengthSquared();
  49644. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  49645. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  49646. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  49647. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  49648. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  49649. lowestRoot = getLowestRoot(a, b, c, t);
  49650. if (lowestRoot.found) {
  49651. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  49652. if (f >= 0.0 && f <= 1.0) {
  49653. t = lowestRoot.root;
  49654. found = true;
  49655. this._edge.scaleInPlace(f);
  49656. p3.addToRef(this._edge, this._collisionPoint);
  49657. }
  49658. }
  49659. }
  49660. if (found) {
  49661. var distToCollision = t * this._velocity.length();
  49662. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  49663. if (!this.intersectionPoint) {
  49664. this.intersectionPoint = this._collisionPoint.clone();
  49665. }
  49666. else {
  49667. this.intersectionPoint.copyFrom(this._collisionPoint);
  49668. }
  49669. this._nearestDistance = distToCollision;
  49670. this.collisionFound = true;
  49671. }
  49672. }
  49673. };
  49674. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  49675. for (var i = indexStart; i < indexEnd; i += 3) {
  49676. var p1 = pts[indices[i] - decal];
  49677. var p2 = pts[indices[i + 1] - decal];
  49678. var p3 = pts[indices[i + 2] - decal];
  49679. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  49680. }
  49681. };
  49682. Collider.prototype._getResponse = function (pos, vel) {
  49683. pos.addToRef(vel, this._destinationPoint);
  49684. vel.scaleInPlace((this._nearestDistance / vel.length()));
  49685. this._basePoint.addToRef(vel, pos);
  49686. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  49687. this._slidePlaneNormal.normalize();
  49688. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  49689. pos.addInPlace(this._displacementVector);
  49690. this.intersectionPoint.addInPlace(this._displacementVector);
  49691. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  49692. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  49693. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  49694. };
  49695. return Collider;
  49696. }());
  49697. BABYLON.Collider = Collider;
  49698. })(BABYLON || (BABYLON = {}));
  49699. //# sourceMappingURL=babylon.collider.js.map
  49700. var BABYLON;
  49701. (function (BABYLON) {
  49702. //WebWorker code will be inserted to this variable.
  49703. BABYLON.CollisionWorker = "";
  49704. var WorkerTaskType;
  49705. (function (WorkerTaskType) {
  49706. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  49707. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  49708. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  49709. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  49710. var WorkerReplyType;
  49711. (function (WorkerReplyType) {
  49712. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  49713. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  49714. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  49715. var CollisionCoordinatorWorker = /** @class */ (function () {
  49716. function CollisionCoordinatorWorker() {
  49717. var _this = this;
  49718. this._scaledPosition = BABYLON.Vector3.Zero();
  49719. this._scaledVelocity = BABYLON.Vector3.Zero();
  49720. this.onMeshUpdated = function (transformNode) {
  49721. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  49722. };
  49723. this.onGeometryUpdated = function (geometry) {
  49724. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  49725. };
  49726. this._afterRender = function () {
  49727. if (!_this._init)
  49728. return;
  49729. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  49730. return;
  49731. }
  49732. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  49733. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  49734. if (_this._runningUpdated > 4) {
  49735. return;
  49736. }
  49737. ++_this._runningUpdated;
  49738. var payload = {
  49739. updatedMeshes: _this._addUpdateMeshesList,
  49740. updatedGeometries: _this._addUpdateGeometriesList,
  49741. removedGeometries: _this._toRemoveGeometryArray,
  49742. removedMeshes: _this._toRemoveMeshesArray
  49743. };
  49744. var message = {
  49745. payload: payload,
  49746. taskType: WorkerTaskType.UPDATE
  49747. };
  49748. var serializable = [];
  49749. for (var id in payload.updatedGeometries) {
  49750. if (payload.updatedGeometries.hasOwnProperty(id)) {
  49751. //prepare transferables
  49752. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  49753. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  49754. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  49755. }
  49756. }
  49757. _this._worker.postMessage(message, serializable);
  49758. _this._addUpdateMeshesList = {};
  49759. _this._addUpdateGeometriesList = {};
  49760. _this._toRemoveGeometryArray = [];
  49761. _this._toRemoveMeshesArray = [];
  49762. };
  49763. this._onMessageFromWorker = function (e) {
  49764. var returnData = e.data;
  49765. if (returnData.error != WorkerReplyType.SUCCESS) {
  49766. //TODO what errors can be returned from the worker?
  49767. BABYLON.Tools.Warn("error returned from worker!");
  49768. return;
  49769. }
  49770. switch (returnData.taskType) {
  49771. case WorkerTaskType.INIT:
  49772. _this._init = true;
  49773. //Update the worked with ALL of the scene's current state
  49774. _this._scene.meshes.forEach(function (mesh) {
  49775. _this.onMeshAdded(mesh);
  49776. });
  49777. _this._scene.getGeometries().forEach(function (geometry) {
  49778. _this.onGeometryAdded(geometry);
  49779. });
  49780. break;
  49781. case WorkerTaskType.UPDATE:
  49782. _this._runningUpdated--;
  49783. break;
  49784. case WorkerTaskType.COLLIDE:
  49785. var returnPayload = returnData.payload;
  49786. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  49787. return;
  49788. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  49789. if (callback) {
  49790. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  49791. if (mesh) {
  49792. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  49793. }
  49794. }
  49795. //cleanup
  49796. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  49797. break;
  49798. }
  49799. };
  49800. this._collisionsCallbackArray = [];
  49801. this._init = false;
  49802. this._runningUpdated = 0;
  49803. this._addUpdateMeshesList = {};
  49804. this._addUpdateGeometriesList = {};
  49805. this._toRemoveGeometryArray = [];
  49806. this._toRemoveMeshesArray = [];
  49807. }
  49808. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49809. if (!this._init)
  49810. return;
  49811. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  49812. return;
  49813. position.divideToRef(collider._radius, this._scaledPosition);
  49814. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49815. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  49816. var payload = {
  49817. collider: {
  49818. position: this._scaledPosition.asArray(),
  49819. velocity: this._scaledVelocity.asArray(),
  49820. radius: collider._radius.asArray()
  49821. },
  49822. collisionId: collisionIndex,
  49823. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  49824. maximumRetry: maximumRetry
  49825. };
  49826. var message = {
  49827. payload: payload,
  49828. taskType: WorkerTaskType.COLLIDE
  49829. };
  49830. this._worker.postMessage(message);
  49831. };
  49832. CollisionCoordinatorWorker.prototype.init = function (scene) {
  49833. this._scene = scene;
  49834. this._scene.registerAfterRender(this._afterRender);
  49835. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  49836. this._worker = new Worker(workerUrl);
  49837. this._worker.onmessage = this._onMessageFromWorker;
  49838. var message = {
  49839. payload: {},
  49840. taskType: WorkerTaskType.INIT
  49841. };
  49842. this._worker.postMessage(message);
  49843. };
  49844. CollisionCoordinatorWorker.prototype.destroy = function () {
  49845. this._scene.unregisterAfterRender(this._afterRender);
  49846. this._worker.terminate();
  49847. };
  49848. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  49849. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  49850. this.onMeshUpdated(mesh);
  49851. };
  49852. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  49853. this._toRemoveMeshesArray.push(mesh.uniqueId);
  49854. };
  49855. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  49856. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  49857. geometry.onGeometryUpdated = this.onGeometryUpdated;
  49858. this.onGeometryUpdated(geometry);
  49859. };
  49860. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  49861. this._toRemoveGeometryArray.push(geometry.id);
  49862. };
  49863. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  49864. var submeshes = [];
  49865. if (mesh.subMeshes) {
  49866. submeshes = mesh.subMeshes.map(function (sm, idx) {
  49867. var boundingInfo = sm.getBoundingInfo();
  49868. return {
  49869. position: idx,
  49870. verticesStart: sm.verticesStart,
  49871. verticesCount: sm.verticesCount,
  49872. indexStart: sm.indexStart,
  49873. indexCount: sm.indexCount,
  49874. hasMaterial: !!sm.getMaterial(),
  49875. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49876. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49877. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49878. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  49879. };
  49880. });
  49881. }
  49882. var geometryId = null;
  49883. if (mesh instanceof BABYLON.Mesh) {
  49884. var geometry = mesh.geometry;
  49885. geometryId = geometry ? geometry.id : null;
  49886. }
  49887. else if (mesh instanceof BABYLON.InstancedMesh) {
  49888. var geometry = mesh.sourceMesh.geometry;
  49889. geometryId = geometry ? geometry.id : null;
  49890. }
  49891. var boundingInfo = mesh.getBoundingInfo();
  49892. return {
  49893. uniqueId: mesh.uniqueId,
  49894. id: mesh.id,
  49895. name: mesh.name,
  49896. geometryId: geometryId,
  49897. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  49898. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  49899. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  49900. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  49901. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  49902. subMeshes: submeshes,
  49903. checkCollisions: mesh.checkCollisions
  49904. };
  49905. };
  49906. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  49907. return {
  49908. id: geometry.id,
  49909. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  49910. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  49911. indices: new Uint32Array(geometry.getIndices() || []),
  49912. };
  49913. };
  49914. return CollisionCoordinatorWorker;
  49915. }());
  49916. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  49917. var CollisionCoordinatorLegacy = /** @class */ (function () {
  49918. function CollisionCoordinatorLegacy() {
  49919. this._scaledPosition = BABYLON.Vector3.Zero();
  49920. this._scaledVelocity = BABYLON.Vector3.Zero();
  49921. this._finalPosition = BABYLON.Vector3.Zero();
  49922. }
  49923. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  49924. position.divideToRef(collider._radius, this._scaledPosition);
  49925. displacement.divideToRef(collider._radius, this._scaledVelocity);
  49926. collider.collidedMesh = null;
  49927. collider._retry = 0;
  49928. collider._initialVelocity = this._scaledVelocity;
  49929. collider._initialPosition = this._scaledPosition;
  49930. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  49931. this._finalPosition.multiplyInPlace(collider._radius);
  49932. //run the callback
  49933. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  49934. };
  49935. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  49936. this._scene = scene;
  49937. };
  49938. CollisionCoordinatorLegacy.prototype.destroy = function () {
  49939. //Legacy need no destruction method.
  49940. };
  49941. //No update in legacy mode
  49942. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  49943. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  49944. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  49945. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  49946. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  49947. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  49948. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  49949. if (excludedMesh === void 0) { excludedMesh = null; }
  49950. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  49951. if (collider._retry >= maximumRetry) {
  49952. finalPosition.copyFrom(position);
  49953. return;
  49954. }
  49955. // Check if this is a mesh else camera or -1
  49956. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  49957. collider._initialize(position, velocity, closeDistance);
  49958. // Check all meshes
  49959. for (var index = 0; index < this._scene.meshes.length; index++) {
  49960. var mesh = this._scene.meshes[index];
  49961. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  49962. mesh._checkCollision(collider);
  49963. }
  49964. }
  49965. if (!collider.collisionFound) {
  49966. position.addToRef(velocity, finalPosition);
  49967. return;
  49968. }
  49969. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  49970. collider._getResponse(position, velocity);
  49971. }
  49972. if (velocity.length() <= closeDistance) {
  49973. finalPosition.copyFrom(position);
  49974. return;
  49975. }
  49976. collider._retry++;
  49977. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  49978. };
  49979. return CollisionCoordinatorLegacy;
  49980. }());
  49981. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  49982. })(BABYLON || (BABYLON = {}));
  49983. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  49984. var BABYLON;
  49985. (function (BABYLON) {
  49986. /**
  49987. * A particle represents one of the element emitted by a particle system.
  49988. * This is mainly define by its coordinates, direction, velocity and age.
  49989. */
  49990. var Particle = /** @class */ (function () {
  49991. /**
  49992. * Creates a new instance of @see Particle
  49993. * @param particleSystem the particle system the particle belongs to
  49994. */
  49995. function Particle(particleSystem) {
  49996. this.particleSystem = particleSystem;
  49997. /**
  49998. * The world position of the particle in the scene.
  49999. */
  50000. this.position = BABYLON.Vector3.Zero();
  50001. /**
  50002. * The world direction of the particle in the scene.
  50003. */
  50004. this.direction = BABYLON.Vector3.Zero();
  50005. /**
  50006. * The color of the particle.
  50007. */
  50008. this.color = new BABYLON.Color4(0, 0, 0, 0);
  50009. /**
  50010. * The color change of the particle per step.
  50011. */
  50012. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  50013. /**
  50014. * Defines how long will the life of the particle be.
  50015. */
  50016. this.lifeTime = 1.0;
  50017. /**
  50018. * The current age of the particle.
  50019. */
  50020. this.age = 0;
  50021. /**
  50022. * The current size of the particle.
  50023. */
  50024. this.size = 0;
  50025. /**
  50026. * The current angle of the particle.
  50027. */
  50028. this.angle = 0;
  50029. /**
  50030. * Defines how fast is the angle changing.
  50031. */
  50032. this.angularSpeed = 0;
  50033. /**
  50034. * Defines the cell index used by the particle to be rendered from a sprite.
  50035. */
  50036. this.cellIndex = 0;
  50037. this._currentFrameCounter = 0;
  50038. if (!this.particleSystem.isAnimationSheetEnabled) {
  50039. return;
  50040. }
  50041. this.cellIndex = this.particleSystem.startSpriteCellID;
  50042. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  50043. this.updateCellIndex = this.updateCellIndexWithSpeedCalculated;
  50044. }
  50045. else {
  50046. this.updateCellIndex = this.updateCellIndexWithCustomSpeed;
  50047. }
  50048. }
  50049. Particle.prototype.updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  50050. // (ageOffset / scaledUpdateSpeed) / available cells
  50051. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  50052. this._currentFrameCounter += scaledUpdateSpeed;
  50053. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  50054. this._currentFrameCounter = 0;
  50055. this.cellIndex++;
  50056. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50057. this.cellIndex = this.particleSystem.endSpriteCellID;
  50058. }
  50059. }
  50060. };
  50061. Particle.prototype.updateCellIndexWithCustomSpeed = function () {
  50062. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  50063. this.cellIndex++;
  50064. this._currentFrameCounter = 0;
  50065. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  50066. if (this.particleSystem.spriteCellLoop) {
  50067. this.cellIndex = this.particleSystem.startSpriteCellID;
  50068. }
  50069. else {
  50070. this.cellIndex = this.particleSystem.endSpriteCellID;
  50071. }
  50072. }
  50073. }
  50074. else {
  50075. this._currentFrameCounter++;
  50076. }
  50077. };
  50078. /**
  50079. * Copy the properties of particle to another one.
  50080. * @param other the particle to copy the information to.
  50081. */
  50082. Particle.prototype.copyTo = function (other) {
  50083. other.position.copyFrom(this.position);
  50084. other.direction.copyFrom(this.direction);
  50085. other.color.copyFrom(this.color);
  50086. other.colorStep.copyFrom(this.colorStep);
  50087. other.lifeTime = this.lifeTime;
  50088. other.age = this.age;
  50089. other.size = this.size;
  50090. other.angle = this.angle;
  50091. other.angularSpeed = this.angularSpeed;
  50092. other.particleSystem = this.particleSystem;
  50093. other.cellIndex = this.cellIndex;
  50094. };
  50095. return Particle;
  50096. }());
  50097. BABYLON.Particle = Particle;
  50098. })(BABYLON || (BABYLON = {}));
  50099. //# sourceMappingURL=babylon.particle.js.map
  50100. var BABYLON;
  50101. (function (BABYLON) {
  50102. /**
  50103. * This represents a particle system in Babylon.
  50104. * 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.
  50105. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  50106. * @example https://doc.babylonjs.com/babylon101/particles
  50107. */
  50108. var ParticleSystem = /** @class */ (function () {
  50109. /**
  50110. * Instantiates a particle system.
  50111. * 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.
  50112. * @param name The name of the particle system
  50113. * @param capacity The max number of particles alive at the same time
  50114. * @param scene The scene the particle system belongs to
  50115. * @param customEffect a custom effect used to change the way particles are rendered by default
  50116. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  50117. * @param epsilon Offset used to render the particles
  50118. */
  50119. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  50120. if (customEffect === void 0) { customEffect = null; }
  50121. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  50122. if (epsilon === void 0) { epsilon = 0.01; }
  50123. var _this = this;
  50124. /**
  50125. * List of animations used by the particle system.
  50126. */
  50127. this.animations = [];
  50128. /**
  50129. * The rendering group used by the Particle system to chose when to render.
  50130. */
  50131. this.renderingGroupId = 0;
  50132. /**
  50133. * The emitter represents the Mesh or position we are attaching the particle system to.
  50134. */
  50135. this.emitter = null;
  50136. /**
  50137. * The maximum number of particles to emit per frame
  50138. */
  50139. this.emitRate = 10;
  50140. /**
  50141. * If you want to launch only a few particles at once, that can be done, as well.
  50142. */
  50143. this.manualEmitCount = -1;
  50144. /**
  50145. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  50146. */
  50147. this.updateSpeed = 0.01;
  50148. /**
  50149. * The amount of time the particle system is running (depends of the overall update speed).
  50150. */
  50151. this.targetStopDuration = 0;
  50152. /**
  50153. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  50154. */
  50155. this.disposeOnStop = false;
  50156. /**
  50157. * Minimum power of emitting particles.
  50158. */
  50159. this.minEmitPower = 1;
  50160. /**
  50161. * Maximum power of emitting particles.
  50162. */
  50163. this.maxEmitPower = 1;
  50164. /**
  50165. * Minimum life time of emitting particles.
  50166. */
  50167. this.minLifeTime = 1;
  50168. /**
  50169. * Maximum life time of emitting particles.
  50170. */
  50171. this.maxLifeTime = 1;
  50172. /**
  50173. * Minimum Size of emitting particles.
  50174. */
  50175. this.minSize = 1;
  50176. /**
  50177. * Maximum Size of emitting particles.
  50178. */
  50179. this.maxSize = 1;
  50180. /**
  50181. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  50182. */
  50183. this.minAngularSpeed = 0;
  50184. /**
  50185. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  50186. */
  50187. this.maxAngularSpeed = 0;
  50188. /**
  50189. * The layer mask we are rendering the particles through.
  50190. */
  50191. this.layerMask = 0x0FFFFFFF;
  50192. /**
  50193. * This can help using your own shader to render the particle system.
  50194. * The according effect will be created
  50195. */
  50196. this.customShader = null;
  50197. /**
  50198. * By default particle system starts as soon as they are created. This prevents the
  50199. * automatic start to happen and let you decide when to start emitting particles.
  50200. */
  50201. this.preventAutoStart = false;
  50202. /**
  50203. * Callback triggered when the particle animation is ending.
  50204. */
  50205. this.onAnimationEnd = null;
  50206. /**
  50207. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  50208. */
  50209. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  50210. /**
  50211. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  50212. * to override the particles.
  50213. */
  50214. this.forceDepthWrite = false;
  50215. /**
  50216. * You can use gravity if you want to give an orientation to your particles.
  50217. */
  50218. this.gravity = BABYLON.Vector3.Zero();
  50219. /**
  50220. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50221. */
  50222. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50223. /**
  50224. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  50225. */
  50226. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50227. /**
  50228. * Color the particle will have at the end of its lifetime.
  50229. */
  50230. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  50231. /**
  50232. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  50233. */
  50234. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50235. /**
  50236. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  50237. */
  50238. this.spriteCellLoop = true;
  50239. /**
  50240. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  50241. */
  50242. this.spriteCellChangeSpeed = 0;
  50243. /**
  50244. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  50245. */
  50246. this.startSpriteCellID = 0;
  50247. /**
  50248. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  50249. */
  50250. this.endSpriteCellID = 0;
  50251. /**
  50252. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  50253. */
  50254. this.spriteCellWidth = 0;
  50255. /**
  50256. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  50257. */
  50258. this.spriteCellHeight = 0;
  50259. /**
  50260. * An event triggered when the system is disposed.
  50261. */
  50262. this.onDisposeObservable = new BABYLON.Observable();
  50263. this._particles = new Array();
  50264. this._stockParticles = new Array();
  50265. this._newPartsExcess = 0;
  50266. this._vertexBuffers = {};
  50267. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  50268. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  50269. this._scaledDirection = BABYLON.Vector3.Zero();
  50270. this._scaledGravity = BABYLON.Vector3.Zero();
  50271. this._currentRenderId = -1;
  50272. this._started = false;
  50273. this._stopped = false;
  50274. this._actualFrame = 0;
  50275. this._vertexBufferSize = 11;
  50276. this._appendParticleVertexes = null;
  50277. this.id = name;
  50278. this.name = name;
  50279. this._capacity = capacity;
  50280. this._epsilon = epsilon;
  50281. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  50282. if (isAnimationSheetEnabled) {
  50283. this._vertexBufferSize = 12;
  50284. }
  50285. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50286. this._customEffect = customEffect;
  50287. scene.particleSystems.push(this);
  50288. this._createIndexBuffer();
  50289. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  50290. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  50291. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  50292. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  50293. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  50294. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  50295. if (this._isAnimationSheetEnabled) {
  50296. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  50297. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  50298. }
  50299. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  50300. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  50301. this._vertexBuffers["options"] = options;
  50302. // Default emitter type
  50303. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  50304. this.updateFunction = function (particles) {
  50305. for (var index = 0; index < particles.length; index++) {
  50306. var particle = particles[index];
  50307. particle.age += _this._scaledUpdateSpeed;
  50308. if (particle.age >= particle.lifeTime) {
  50309. _this.recycleParticle(particle);
  50310. index--;
  50311. continue;
  50312. }
  50313. else {
  50314. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  50315. particle.color.addInPlace(_this._scaledColorStep);
  50316. if (particle.color.a < 0)
  50317. particle.color.a = 0;
  50318. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  50319. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  50320. particle.position.addInPlace(_this._scaledDirection);
  50321. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  50322. particle.direction.addInPlace(_this._scaledGravity);
  50323. if (_this._isAnimationSheetEnabled) {
  50324. particle.updateCellIndex(_this._scaledUpdateSpeed);
  50325. }
  50326. }
  50327. }
  50328. };
  50329. }
  50330. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  50331. /**
  50332. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50333. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50334. */
  50335. get: function () {
  50336. if (this.particleEmitterType.direction1) {
  50337. return this.particleEmitterType.direction1;
  50338. }
  50339. return BABYLON.Vector3.Zero();
  50340. },
  50341. set: function (value) {
  50342. if (this.particleEmitterType.direction1) {
  50343. this.particleEmitterType.direction1 = value;
  50344. }
  50345. },
  50346. enumerable: true,
  50347. configurable: true
  50348. });
  50349. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  50350. /**
  50351. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  50352. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50353. */
  50354. get: function () {
  50355. if (this.particleEmitterType.direction2) {
  50356. return this.particleEmitterType.direction2;
  50357. }
  50358. return BABYLON.Vector3.Zero();
  50359. },
  50360. set: function (value) {
  50361. if (this.particleEmitterType.direction2) {
  50362. this.particleEmitterType.direction2 = value;
  50363. }
  50364. },
  50365. enumerable: true,
  50366. configurable: true
  50367. });
  50368. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  50369. /**
  50370. * 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.
  50371. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50372. */
  50373. get: function () {
  50374. if (this.particleEmitterType.minEmitBox) {
  50375. return this.particleEmitterType.minEmitBox;
  50376. }
  50377. return BABYLON.Vector3.Zero();
  50378. },
  50379. set: function (value) {
  50380. if (this.particleEmitterType.minEmitBox) {
  50381. this.particleEmitterType.minEmitBox = value;
  50382. }
  50383. },
  50384. enumerable: true,
  50385. configurable: true
  50386. });
  50387. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  50388. /**
  50389. * 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.
  50390. * This only works when particleEmitterTyps is a BoxParticleEmitter
  50391. */
  50392. get: function () {
  50393. if (this.particleEmitterType.maxEmitBox) {
  50394. return this.particleEmitterType.maxEmitBox;
  50395. }
  50396. return BABYLON.Vector3.Zero();
  50397. },
  50398. set: function (value) {
  50399. if (this.particleEmitterType.maxEmitBox) {
  50400. this.particleEmitterType.maxEmitBox = value;
  50401. }
  50402. },
  50403. enumerable: true,
  50404. configurable: true
  50405. });
  50406. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  50407. /**
  50408. * Sets a callback that will be triggered when the system is disposed.
  50409. */
  50410. set: function (callback) {
  50411. if (this._onDisposeObserver) {
  50412. this.onDisposeObservable.remove(this._onDisposeObserver);
  50413. }
  50414. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50415. },
  50416. enumerable: true,
  50417. configurable: true
  50418. });
  50419. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  50420. /**
  50421. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  50422. */
  50423. get: function () {
  50424. return this._isAnimationSheetEnabled;
  50425. },
  50426. enumerable: true,
  50427. configurable: true
  50428. });
  50429. /**
  50430. * Returns the string "ParticleSystem"
  50431. * @returns a string containing the class name
  50432. */
  50433. ParticleSystem.prototype.getClassName = function () {
  50434. return "ParticleSystem";
  50435. };
  50436. ParticleSystem.prototype._createIndexBuffer = function () {
  50437. var indices = [];
  50438. var index = 0;
  50439. for (var count = 0; count < this._capacity; count++) {
  50440. indices.push(index);
  50441. indices.push(index + 1);
  50442. indices.push(index + 2);
  50443. indices.push(index);
  50444. indices.push(index + 2);
  50445. indices.push(index + 3);
  50446. index += 4;
  50447. }
  50448. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  50449. };
  50450. /**
  50451. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  50452. * Its lifetime will start back at 0.
  50453. * @param particle The particle to recycle
  50454. */
  50455. ParticleSystem.prototype.recycleParticle = function (particle) {
  50456. var lastParticle = this._particles.pop();
  50457. if (lastParticle !== particle) {
  50458. lastParticle.copyTo(particle);
  50459. this._stockParticles.push(lastParticle);
  50460. }
  50461. };
  50462. /**
  50463. * Gets the maximum number of particles active at the same time.
  50464. * @returns The max number of active particles.
  50465. */
  50466. ParticleSystem.prototype.getCapacity = function () {
  50467. return this._capacity;
  50468. };
  50469. /**
  50470. * Gets Wether there are still active particles in the system.
  50471. * @returns True if it is alive, otherwise false.
  50472. */
  50473. ParticleSystem.prototype.isAlive = function () {
  50474. return this._alive;
  50475. };
  50476. /**
  50477. * Gets Wether the system has been started.
  50478. * @returns True if it has been started, otherwise false.
  50479. */
  50480. ParticleSystem.prototype.isStarted = function () {
  50481. return this._started;
  50482. };
  50483. /**
  50484. * Starts the particle system and begins to emit.
  50485. */
  50486. ParticleSystem.prototype.start = function () {
  50487. this._started = true;
  50488. this._stopped = false;
  50489. this._actualFrame = 0;
  50490. };
  50491. /**
  50492. * Stops the particle system.
  50493. */
  50494. ParticleSystem.prototype.stop = function () {
  50495. this._stopped = true;
  50496. };
  50497. /**
  50498. * Remove all active particles
  50499. */
  50500. ParticleSystem.prototype.reset = function () {
  50501. this._stockParticles = [];
  50502. this._particles = [];
  50503. };
  50504. /**
  50505. * @ignore (for internal use only)
  50506. */
  50507. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  50508. var offset = index * this._vertexBufferSize;
  50509. this._vertexData[offset] = particle.position.x;
  50510. this._vertexData[offset + 1] = particle.position.y;
  50511. this._vertexData[offset + 2] = particle.position.z;
  50512. this._vertexData[offset + 3] = particle.color.r;
  50513. this._vertexData[offset + 4] = particle.color.g;
  50514. this._vertexData[offset + 5] = particle.color.b;
  50515. this._vertexData[offset + 6] = particle.color.a;
  50516. this._vertexData[offset + 7] = particle.angle;
  50517. this._vertexData[offset + 8] = particle.size;
  50518. this._vertexData[offset + 9] = offsetX;
  50519. this._vertexData[offset + 10] = offsetY;
  50520. };
  50521. /**
  50522. * @ignore (for internal use only)
  50523. */
  50524. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  50525. if (offsetX === 0)
  50526. offsetX = this._epsilon;
  50527. else if (offsetX === 1)
  50528. offsetX = 1 - this._epsilon;
  50529. if (offsetY === 0)
  50530. offsetY = this._epsilon;
  50531. else if (offsetY === 1)
  50532. offsetY = 1 - this._epsilon;
  50533. var offset = index * this._vertexBufferSize;
  50534. this._vertexData[offset] = particle.position.x;
  50535. this._vertexData[offset + 1] = particle.position.y;
  50536. this._vertexData[offset + 2] = particle.position.z;
  50537. this._vertexData[offset + 3] = particle.color.r;
  50538. this._vertexData[offset + 4] = particle.color.g;
  50539. this._vertexData[offset + 5] = particle.color.b;
  50540. this._vertexData[offset + 6] = particle.color.a;
  50541. this._vertexData[offset + 7] = particle.angle;
  50542. this._vertexData[offset + 8] = particle.size;
  50543. this._vertexData[offset + 9] = offsetX;
  50544. this._vertexData[offset + 10] = offsetY;
  50545. this._vertexData[offset + 11] = particle.cellIndex;
  50546. };
  50547. ParticleSystem.prototype._update = function (newParticles) {
  50548. // Update current
  50549. this._alive = this._particles.length > 0;
  50550. this.updateFunction(this._particles);
  50551. // Add new ones
  50552. var worldMatrix;
  50553. if (this.emitter.position) {
  50554. var emitterMesh = this.emitter;
  50555. worldMatrix = emitterMesh.getWorldMatrix();
  50556. }
  50557. else {
  50558. var emitterPosition = this.emitter;
  50559. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  50560. }
  50561. var particle;
  50562. for (var index = 0; index < newParticles; index++) {
  50563. if (this._particles.length === this._capacity) {
  50564. break;
  50565. }
  50566. if (this._stockParticles.length !== 0) {
  50567. particle = this._stockParticles.pop();
  50568. particle.age = 0;
  50569. particle.cellIndex = this.startSpriteCellID;
  50570. }
  50571. else {
  50572. particle = new BABYLON.Particle(this);
  50573. }
  50574. this._particles.push(particle);
  50575. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  50576. if (this.startPositionFunction) {
  50577. this.startPositionFunction(worldMatrix, particle.position, particle);
  50578. }
  50579. else {
  50580. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  50581. }
  50582. if (this.startDirectionFunction) {
  50583. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50584. }
  50585. else {
  50586. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  50587. }
  50588. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  50589. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  50590. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  50591. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  50592. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  50593. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  50594. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  50595. }
  50596. };
  50597. ParticleSystem.prototype._getEffect = function () {
  50598. if (this._customEffect) {
  50599. return this._customEffect;
  50600. }
  50601. ;
  50602. var defines = [];
  50603. if (this._scene.clipPlane) {
  50604. defines.push("#define CLIPPLANE");
  50605. }
  50606. if (this._isAnimationSheetEnabled) {
  50607. defines.push("#define ANIMATESHEET");
  50608. }
  50609. // Effect
  50610. var join = defines.join("\n");
  50611. if (this._cachedDefines !== join) {
  50612. this._cachedDefines = join;
  50613. var attributesNamesOrOptions;
  50614. var effectCreationOption;
  50615. if (this._isAnimationSheetEnabled) {
  50616. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  50617. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  50618. }
  50619. else {
  50620. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  50621. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  50622. }
  50623. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  50624. }
  50625. return this._effect;
  50626. };
  50627. /**
  50628. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  50629. */
  50630. ParticleSystem.prototype.animate = function () {
  50631. if (!this._started)
  50632. return;
  50633. var effect = this._getEffect();
  50634. // Check
  50635. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  50636. return;
  50637. if (this._currentRenderId === this._scene.getRenderId()) {
  50638. return;
  50639. }
  50640. this._currentRenderId = this._scene.getRenderId();
  50641. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  50642. // determine the number of particles we need to create
  50643. var newParticles;
  50644. if (this.manualEmitCount > -1) {
  50645. newParticles = this.manualEmitCount;
  50646. this._newPartsExcess = 0;
  50647. this.manualEmitCount = 0;
  50648. }
  50649. else {
  50650. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  50651. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  50652. }
  50653. if (this._newPartsExcess > 1.0) {
  50654. newParticles += this._newPartsExcess >> 0;
  50655. this._newPartsExcess -= this._newPartsExcess >> 0;
  50656. }
  50657. this._alive = false;
  50658. if (!this._stopped) {
  50659. this._actualFrame += this._scaledUpdateSpeed;
  50660. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  50661. this.stop();
  50662. }
  50663. else {
  50664. newParticles = 0;
  50665. }
  50666. this._update(newParticles);
  50667. // Stopped?
  50668. if (this._stopped) {
  50669. if (!this._alive) {
  50670. this._started = false;
  50671. if (this.onAnimationEnd) {
  50672. this.onAnimationEnd();
  50673. }
  50674. if (this.disposeOnStop) {
  50675. this._scene._toBeDisposed.push(this);
  50676. }
  50677. }
  50678. }
  50679. // Animation sheet
  50680. if (this._isAnimationSheetEnabled) {
  50681. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  50682. }
  50683. else {
  50684. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  50685. }
  50686. // Update VBO
  50687. var offset = 0;
  50688. for (var index = 0; index < this._particles.length; index++) {
  50689. var particle = this._particles[index];
  50690. this._appendParticleVertexes(offset, particle);
  50691. offset += 4;
  50692. }
  50693. if (this._vertexBuffer) {
  50694. this._vertexBuffer.update(this._vertexData);
  50695. }
  50696. };
  50697. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  50698. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  50699. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  50700. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  50701. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  50702. };
  50703. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  50704. this._appendParticleVertex(offset++, particle, 0, 0);
  50705. this._appendParticleVertex(offset++, particle, 1, 0);
  50706. this._appendParticleVertex(offset++, particle, 1, 1);
  50707. this._appendParticleVertex(offset++, particle, 0, 1);
  50708. };
  50709. /**
  50710. * Rebuilds the particle system.
  50711. */
  50712. ParticleSystem.prototype.rebuild = function () {
  50713. this._createIndexBuffer();
  50714. if (this._vertexBuffer) {
  50715. this._vertexBuffer._rebuild();
  50716. }
  50717. };
  50718. /**
  50719. * Renders the particle system in its current state.
  50720. * @returns the current number of particles
  50721. */
  50722. ParticleSystem.prototype.render = function () {
  50723. var effect = this._getEffect();
  50724. // Check
  50725. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this._particles.length) {
  50726. return 0;
  50727. }
  50728. var engine = this._scene.getEngine();
  50729. // Render
  50730. engine.enableEffect(effect);
  50731. engine.setState(false);
  50732. var viewMatrix = this._scene.getViewMatrix();
  50733. effect.setTexture("diffuseSampler", this.particleTexture);
  50734. effect.setMatrix("view", viewMatrix);
  50735. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50736. if (this._isAnimationSheetEnabled) {
  50737. var baseSize = this.particleTexture.getBaseSize();
  50738. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  50739. }
  50740. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  50741. if (this._scene.clipPlane) {
  50742. var clipPlane = this._scene.clipPlane;
  50743. var invView = viewMatrix.clone();
  50744. invView.invert();
  50745. effect.setMatrix("invView", invView);
  50746. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  50747. }
  50748. // VBOs
  50749. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50750. // Draw order
  50751. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  50752. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  50753. }
  50754. else {
  50755. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50756. }
  50757. if (this.forceDepthWrite) {
  50758. engine.setDepthWrite(true);
  50759. }
  50760. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  50761. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50762. return this._particles.length;
  50763. };
  50764. /**
  50765. * Disposes the particle system and free the associated resources.
  50766. */
  50767. ParticleSystem.prototype.dispose = function () {
  50768. if (this._vertexBuffer) {
  50769. this._vertexBuffer.dispose();
  50770. this._vertexBuffer = null;
  50771. }
  50772. if (this._indexBuffer) {
  50773. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50774. this._indexBuffer = null;
  50775. }
  50776. if (this.particleTexture) {
  50777. this.particleTexture.dispose();
  50778. this.particleTexture = null;
  50779. }
  50780. // Remove from scene
  50781. var index = this._scene.particleSystems.indexOf(this);
  50782. if (index > -1) {
  50783. this._scene.particleSystems.splice(index, 1);
  50784. }
  50785. // Callback
  50786. this.onDisposeObservable.notifyObservers(this);
  50787. this.onDisposeObservable.clear();
  50788. };
  50789. /**
  50790. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  50791. * @param radius The radius of the sphere to emit from
  50792. * @returns the emitter
  50793. */
  50794. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  50795. if (radius === void 0) { radius = 1; }
  50796. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  50797. this.particleEmitterType = particleEmitter;
  50798. return particleEmitter;
  50799. };
  50800. /**
  50801. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  50802. * @param radius The radius of the sphere to emit from
  50803. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  50804. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  50805. * @returns the emitter
  50806. */
  50807. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  50808. if (radius === void 0) { radius = 1; }
  50809. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  50810. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  50811. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  50812. this.particleEmitterType = particleEmitter;
  50813. return particleEmitter;
  50814. };
  50815. /**
  50816. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  50817. * @param radius The radius of the cone to emit from
  50818. * @param angle The base angle of the cone
  50819. * @returns the emitter
  50820. */
  50821. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  50822. if (radius === void 0) { radius = 1; }
  50823. if (angle === void 0) { angle = Math.PI / 4; }
  50824. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  50825. this.particleEmitterType = particleEmitter;
  50826. return particleEmitter;
  50827. };
  50828. // 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.
  50829. /**
  50830. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  50831. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  50832. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  50833. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50834. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  50835. * @returns the emitter
  50836. */
  50837. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  50838. var particleEmitter = new BABYLON.BoxParticleEmitter();
  50839. this.direction1 = direction1;
  50840. this.direction2 = direction2;
  50841. this.minEmitBox = minEmitBox;
  50842. this.maxEmitBox = maxEmitBox;
  50843. this.particleEmitterType = particleEmitter;
  50844. return particleEmitter;
  50845. };
  50846. /**
  50847. * Clones the particle system.
  50848. * @param name The name of the cloned object
  50849. * @param newEmitter The new emitter to use
  50850. * @returns the cloned particle system
  50851. */
  50852. ParticleSystem.prototype.clone = function (name, newEmitter) {
  50853. var custom = null;
  50854. var program = null;
  50855. if (this.customShader != null) {
  50856. program = this.customShader;
  50857. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50858. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50859. }
  50860. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  50861. result.customShader = program;
  50862. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  50863. if (newEmitter === undefined) {
  50864. newEmitter = this.emitter;
  50865. }
  50866. result.emitter = newEmitter;
  50867. if (this.particleTexture) {
  50868. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  50869. }
  50870. if (!this.preventAutoStart) {
  50871. result.start();
  50872. }
  50873. return result;
  50874. };
  50875. /**
  50876. * Serializes the particle system to a JSON object.
  50877. * @returns the JSON object
  50878. */
  50879. ParticleSystem.prototype.serialize = function () {
  50880. var serializationObject = {};
  50881. serializationObject.name = this.name;
  50882. serializationObject.id = this.id;
  50883. // Emitter
  50884. if (this.emitter.position) {
  50885. var emitterMesh = this.emitter;
  50886. serializationObject.emitterId = emitterMesh.id;
  50887. }
  50888. else {
  50889. var emitterPosition = this.emitter;
  50890. serializationObject.emitter = emitterPosition.asArray();
  50891. }
  50892. serializationObject.capacity = this.getCapacity();
  50893. if (this.particleTexture) {
  50894. serializationObject.textureName = this.particleTexture.name;
  50895. }
  50896. // Animations
  50897. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  50898. // Particle system
  50899. serializationObject.minAngularSpeed = this.minAngularSpeed;
  50900. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  50901. serializationObject.minSize = this.minSize;
  50902. serializationObject.maxSize = this.maxSize;
  50903. serializationObject.minEmitPower = this.minEmitPower;
  50904. serializationObject.maxEmitPower = this.maxEmitPower;
  50905. serializationObject.minLifeTime = this.minLifeTime;
  50906. serializationObject.maxLifeTime = this.maxLifeTime;
  50907. serializationObject.emitRate = this.emitRate;
  50908. serializationObject.minEmitBox = this.minEmitBox.asArray();
  50909. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  50910. serializationObject.gravity = this.gravity.asArray();
  50911. serializationObject.direction1 = this.direction1.asArray();
  50912. serializationObject.direction2 = this.direction2.asArray();
  50913. serializationObject.color1 = this.color1.asArray();
  50914. serializationObject.color2 = this.color2.asArray();
  50915. serializationObject.colorDead = this.colorDead.asArray();
  50916. serializationObject.updateSpeed = this.updateSpeed;
  50917. serializationObject.targetStopDuration = this.targetStopDuration;
  50918. serializationObject.textureMask = this.textureMask.asArray();
  50919. serializationObject.blendMode = this.blendMode;
  50920. serializationObject.customShader = this.customShader;
  50921. serializationObject.preventAutoStart = this.preventAutoStart;
  50922. serializationObject.startSpriteCellID = this.startSpriteCellID;
  50923. serializationObject.endSpriteCellID = this.endSpriteCellID;
  50924. serializationObject.spriteCellLoop = this.spriteCellLoop;
  50925. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  50926. serializationObject.spriteCellWidth = this.spriteCellWidth;
  50927. serializationObject.spriteCellHeight = this.spriteCellHeight;
  50928. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  50929. // Emitter
  50930. if (this.particleEmitterType) {
  50931. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  50932. }
  50933. return serializationObject;
  50934. };
  50935. /**
  50936. * Parses a JSON object to create a particle system.
  50937. * @param parsedParticleSystem The JSON object to parse
  50938. * @param scene The scene to create the particle system in
  50939. * @param rootUrl The root url to use to load external dependencies like texture
  50940. * @returns the Parsed particle system
  50941. */
  50942. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  50943. var name = parsedParticleSystem.name;
  50944. var custom = null;
  50945. var program = null;
  50946. if (parsedParticleSystem.customShader) {
  50947. program = parsedParticleSystem.customShader;
  50948. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  50949. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  50950. }
  50951. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  50952. particleSystem.customShader = program;
  50953. if (parsedParticleSystem.id) {
  50954. particleSystem.id = parsedParticleSystem.id;
  50955. }
  50956. // Auto start
  50957. if (parsedParticleSystem.preventAutoStart) {
  50958. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  50959. }
  50960. // Texture
  50961. if (parsedParticleSystem.textureName) {
  50962. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  50963. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  50964. }
  50965. // Emitter
  50966. if (parsedParticleSystem.emitterId) {
  50967. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  50968. }
  50969. else {
  50970. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  50971. }
  50972. // Animations
  50973. if (parsedParticleSystem.animations) {
  50974. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  50975. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  50976. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  50977. }
  50978. }
  50979. if (parsedParticleSystem.autoAnimate) {
  50980. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  50981. }
  50982. // Particle system
  50983. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  50984. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  50985. particleSystem.minSize = parsedParticleSystem.minSize;
  50986. particleSystem.maxSize = parsedParticleSystem.maxSize;
  50987. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  50988. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  50989. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  50990. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  50991. particleSystem.emitRate = parsedParticleSystem.emitRate;
  50992. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  50993. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  50994. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  50995. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  50996. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  50997. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  50998. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  50999. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  51000. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  51001. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  51002. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  51003. particleSystem.blendMode = parsedParticleSystem.blendMode;
  51004. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  51005. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  51006. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  51007. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  51008. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  51009. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  51010. if (!particleSystem.preventAutoStart) {
  51011. particleSystem.start();
  51012. }
  51013. return particleSystem;
  51014. };
  51015. /**
  51016. * Source color is added to the destination color without alpha affecting the result.
  51017. */
  51018. ParticleSystem.BLENDMODE_ONEONE = 0;
  51019. /**
  51020. * Blend current color and particle color using particle’s alpha.
  51021. */
  51022. ParticleSystem.BLENDMODE_STANDARD = 1;
  51023. return ParticleSystem;
  51024. }());
  51025. BABYLON.ParticleSystem = ParticleSystem;
  51026. })(BABYLON || (BABYLON = {}));
  51027. //# sourceMappingURL=babylon.particleSystem.js.map
  51028. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  51029. var BABYLON;
  51030. (function (BABYLON) {
  51031. /**
  51032. * Particle emitter emitting particles from the inside of a box.
  51033. * It emits the particles randomly between 2 given directions.
  51034. */
  51035. var BoxParticleEmitter = /** @class */ (function () {
  51036. /**
  51037. * Creates a new instance of @see BoxParticleEmitter
  51038. */
  51039. function BoxParticleEmitter() {
  51040. /**
  51041. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51042. */
  51043. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  51044. /**
  51045. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51046. */
  51047. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  51048. /**
  51049. * 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.
  51050. */
  51051. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  51052. /**
  51053. * 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.
  51054. */
  51055. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  51056. }
  51057. /**
  51058. * Called by the particle System when the direction is computed for the created particle.
  51059. * @param emitPower is the power of the particle (speed)
  51060. * @param worldMatrix is the world matrix of the particle system
  51061. * @param directionToUpdate is the direction vector to update with the result
  51062. * @param particle is the particle we are computed the direction for
  51063. */
  51064. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51065. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51066. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51067. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51068. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51069. };
  51070. /**
  51071. * Called by the particle System when the position is computed for the created particle.
  51072. * @param worldMatrix is the world matrix of the particle system
  51073. * @param positionToUpdate is the position vector to update with the result
  51074. * @param particle is the particle we are computed the position for
  51075. */
  51076. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51077. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  51078. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  51079. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  51080. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51081. };
  51082. /**
  51083. * Clones the current emitter and returns a copy of it
  51084. * @returns the new emitter
  51085. */
  51086. BoxParticleEmitter.prototype.clone = function () {
  51087. var newOne = new BoxParticleEmitter();
  51088. BABYLON.Tools.DeepCopy(this, newOne);
  51089. return newOne;
  51090. };
  51091. /**
  51092. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51093. * @param effect defines the update shader
  51094. */
  51095. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  51096. effect.setVector3("direction1", this.direction1);
  51097. effect.setVector3("direction2", this.direction2);
  51098. effect.setVector3("minEmitBox", this.minEmitBox);
  51099. effect.setVector3("maxEmitBox", this.maxEmitBox);
  51100. };
  51101. /**
  51102. * Returns a string to use to update the GPU particles update shader
  51103. * @returns a string containng the defines string
  51104. */
  51105. BoxParticleEmitter.prototype.getEffectDefines = function () {
  51106. return "#define BOXEMITTER";
  51107. };
  51108. /**
  51109. * Returns the string "BoxEmitter"
  51110. * @returns a string containing the class name
  51111. */
  51112. BoxParticleEmitter.prototype.getClassName = function () {
  51113. return "BoxEmitter";
  51114. };
  51115. /**
  51116. * Serializes the particle system to a JSON object.
  51117. * @returns the JSON object
  51118. */
  51119. BoxParticleEmitter.prototype.serialize = function () {
  51120. var serializationObject = {};
  51121. serializationObject.type = this.getClassName();
  51122. serializationObject.direction1 = this.direction1.asArray();
  51123. ;
  51124. serializationObject.direction2 = this.direction2.asArray();
  51125. ;
  51126. serializationObject.minEmitBox = this.minEmitBox.asArray();
  51127. ;
  51128. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  51129. ;
  51130. return serializationObject;
  51131. };
  51132. /**
  51133. * Parse properties from a JSON object
  51134. * @param serializationObject defines the JSON object
  51135. */
  51136. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  51137. this.direction1.copyFrom(serializationObject.direction1);
  51138. this.direction2.copyFrom(serializationObject.direction2);
  51139. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  51140. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  51141. };
  51142. return BoxParticleEmitter;
  51143. }());
  51144. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  51145. })(BABYLON || (BABYLON = {}));
  51146. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  51147. var BABYLON;
  51148. (function (BABYLON) {
  51149. /**
  51150. * Particle emitter emitting particles from the inside of a cone.
  51151. * It emits the particles alongside the cone volume from the base to the particle.
  51152. * The emission direction might be randomized.
  51153. */
  51154. var ConeParticleEmitter = /** @class */ (function () {
  51155. /**
  51156. * Creates a new instance of @see ConeParticleEmitter
  51157. * @param radius the radius of the emission cone (1 by default)
  51158. * @param angles the cone base angle (PI by default)
  51159. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51160. */
  51161. function ConeParticleEmitter(radius,
  51162. /**
  51163. * The radius of the emission cone.
  51164. */
  51165. angle,
  51166. /**
  51167. * The cone base angle.
  51168. */
  51169. directionRandomizer) {
  51170. if (radius === void 0) { radius = 1; }
  51171. if (angle === void 0) { angle = Math.PI; }
  51172. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51173. this.angle = angle;
  51174. this.directionRandomizer = directionRandomizer;
  51175. this.radius = radius;
  51176. }
  51177. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  51178. /**
  51179. * Gets the radius of the emission cone.
  51180. */
  51181. get: function () {
  51182. return this._radius;
  51183. },
  51184. /**
  51185. * Sets the radius of the emission cone.
  51186. */
  51187. set: function (value) {
  51188. this._radius = value;
  51189. if (this.angle !== 0) {
  51190. this._height = value / Math.tan(this.angle / 2);
  51191. }
  51192. else {
  51193. this._height = 1;
  51194. }
  51195. },
  51196. enumerable: true,
  51197. configurable: true
  51198. });
  51199. /**
  51200. * Called by the particle System when the direction is computed for the created particle.
  51201. * @param emitPower is the power of the particle (speed)
  51202. * @param worldMatrix is the world matrix of the particle system
  51203. * @param directionToUpdate is the direction vector to update with the result
  51204. * @param particle is the particle we are computed the direction for
  51205. */
  51206. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51207. if (this.angle === 0) {
  51208. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  51209. }
  51210. else {
  51211. // measure the direction Vector from the emitter to the particle.
  51212. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51213. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51214. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51215. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51216. direction.x += randX;
  51217. direction.y += randY;
  51218. direction.z += randZ;
  51219. direction.normalize();
  51220. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51221. }
  51222. };
  51223. /**
  51224. * Called by the particle System when the position is computed for the created particle.
  51225. * @param worldMatrix is the world matrix of the particle system
  51226. * @param positionToUpdate is the position vector to update with the result
  51227. * @param particle is the particle we are computed the position for
  51228. */
  51229. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51230. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  51231. var h = BABYLON.Scalar.RandomRange(0, 1);
  51232. // Better distribution in a cone at normal angles.
  51233. h = 1 - h * h;
  51234. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  51235. radius = radius * h / this._height;
  51236. var randX = radius * Math.sin(s);
  51237. var randZ = radius * Math.cos(s);
  51238. var randY = h * this._height;
  51239. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51240. };
  51241. /**
  51242. * Clones the current emitter and returns a copy of it
  51243. * @returns the new emitter
  51244. */
  51245. ConeParticleEmitter.prototype.clone = function () {
  51246. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  51247. BABYLON.Tools.DeepCopy(this, newOne);
  51248. return newOne;
  51249. };
  51250. /**
  51251. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51252. * @param effect defines the update shader
  51253. */
  51254. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  51255. effect.setFloat("radius", this.radius);
  51256. effect.setFloat("angle", this.angle);
  51257. effect.setFloat("height", this._height);
  51258. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51259. };
  51260. /**
  51261. * Returns a string to use to update the GPU particles update shader
  51262. * @returns a string containng the defines string
  51263. */
  51264. ConeParticleEmitter.prototype.getEffectDefines = function () {
  51265. return "#define CONEEMITTER";
  51266. };
  51267. /**
  51268. * Returns the string "BoxEmitter"
  51269. * @returns a string containing the class name
  51270. */
  51271. ConeParticleEmitter.prototype.getClassName = function () {
  51272. return "ConeEmitter";
  51273. };
  51274. /**
  51275. * Serializes the particle system to a JSON object.
  51276. * @returns the JSON object
  51277. */
  51278. ConeParticleEmitter.prototype.serialize = function () {
  51279. var serializationObject = {};
  51280. serializationObject.type = this.getClassName();
  51281. serializationObject.radius = this.radius;
  51282. serializationObject.angle = this.angle;
  51283. serializationObject.directionRandomizer = this.directionRandomizer;
  51284. return serializationObject;
  51285. };
  51286. /**
  51287. * Parse properties from a JSON object
  51288. * @param serializationObject defines the JSON object
  51289. */
  51290. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  51291. this.radius = serializationObject.radius;
  51292. this.angle = serializationObject.angle;
  51293. this.directionRandomizer = serializationObject.directionRandomizer;
  51294. };
  51295. return ConeParticleEmitter;
  51296. }());
  51297. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  51298. })(BABYLON || (BABYLON = {}));
  51299. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  51300. var BABYLON;
  51301. (function (BABYLON) {
  51302. /**
  51303. * Particle emitter emitting particles from the inside of a sphere.
  51304. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  51305. */
  51306. var SphereParticleEmitter = /** @class */ (function () {
  51307. /**
  51308. * Creates a new instance of @see SphereParticleEmitter
  51309. * @param radius the radius of the emission sphere (1 by default)
  51310. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  51311. */
  51312. function SphereParticleEmitter(
  51313. /**
  51314. * The radius of the emission sphere.
  51315. */
  51316. radius,
  51317. /**
  51318. * How much to randomize the particle direction [0-1].
  51319. */
  51320. directionRandomizer) {
  51321. if (radius === void 0) { radius = 1; }
  51322. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  51323. this.radius = radius;
  51324. this.directionRandomizer = directionRandomizer;
  51325. }
  51326. /**
  51327. * Called by the particle System when the direction is computed for the created particle.
  51328. * @param emitPower is the power of the particle (speed)
  51329. * @param worldMatrix is the world matrix of the particle system
  51330. * @param directionToUpdate is the direction vector to update with the result
  51331. * @param particle is the particle we are computed the direction for
  51332. */
  51333. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51334. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  51335. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51336. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51337. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  51338. direction.x += randX;
  51339. direction.y += randY;
  51340. direction.z += randZ;
  51341. direction.normalize();
  51342. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  51343. };
  51344. /**
  51345. * Called by the particle System when the position is computed for the created particle.
  51346. * @param worldMatrix is the world matrix of the particle system
  51347. * @param positionToUpdate is the position vector to update with the result
  51348. * @param particle is the particle we are computed the position for
  51349. */
  51350. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  51351. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  51352. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  51353. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  51354. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  51355. var randY = randRadius * Math.cos(theta);
  51356. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  51357. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  51358. };
  51359. /**
  51360. * Clones the current emitter and returns a copy of it
  51361. * @returns the new emitter
  51362. */
  51363. SphereParticleEmitter.prototype.clone = function () {
  51364. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  51365. BABYLON.Tools.DeepCopy(this, newOne);
  51366. return newOne;
  51367. };
  51368. /**
  51369. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51370. * @param effect defines the update shader
  51371. */
  51372. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  51373. effect.setFloat("radius", this.radius);
  51374. effect.setFloat("directionRandomizer", this.directionRandomizer);
  51375. };
  51376. /**
  51377. * Returns a string to use to update the GPU particles update shader
  51378. * @returns a string containng the defines string
  51379. */
  51380. SphereParticleEmitter.prototype.getEffectDefines = function () {
  51381. return "#define SPHEREEMITTER";
  51382. };
  51383. /**
  51384. * Returns the string "SphereParticleEmitter"
  51385. * @returns a string containing the class name
  51386. */
  51387. SphereParticleEmitter.prototype.getClassName = function () {
  51388. return "SphereParticleEmitter";
  51389. };
  51390. /**
  51391. * Serializes the particle system to a JSON object.
  51392. * @returns the JSON object
  51393. */
  51394. SphereParticleEmitter.prototype.serialize = function () {
  51395. var serializationObject = {};
  51396. serializationObject.type = this.getClassName();
  51397. serializationObject.radius = this.radius;
  51398. serializationObject.directionRandomizer = this.directionRandomizer;
  51399. return serializationObject;
  51400. };
  51401. /**
  51402. * Parse properties from a JSON object
  51403. * @param serializationObject defines the JSON object
  51404. */
  51405. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  51406. this.radius = serializationObject.radius;
  51407. this.directionRandomizer = serializationObject.directionRandomizer;
  51408. };
  51409. return SphereParticleEmitter;
  51410. }());
  51411. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  51412. /**
  51413. * Particle emitter emitting particles from the inside of a sphere.
  51414. * It emits the particles randomly between two vectors.
  51415. */
  51416. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  51417. __extends(SphereDirectedParticleEmitter, _super);
  51418. /**
  51419. * Creates a new instance of @see SphereDirectedParticleEmitter
  51420. * @param radius the radius of the emission sphere (1 by default)
  51421. * @param direction1 the min limit of the emission direction (up vector by default)
  51422. * @param direction2 the max limit of the emission direction (up vector by default)
  51423. */
  51424. function SphereDirectedParticleEmitter(radius,
  51425. /**
  51426. * The min limit of the emission direction.
  51427. */
  51428. direction1,
  51429. /**
  51430. * The max limit of the emission direction.
  51431. */
  51432. direction2) {
  51433. if (radius === void 0) { radius = 1; }
  51434. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  51435. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  51436. var _this = _super.call(this, radius) || this;
  51437. _this.direction1 = direction1;
  51438. _this.direction2 = direction2;
  51439. return _this;
  51440. }
  51441. /**
  51442. * Called by the particle System when the direction is computed for the created particle.
  51443. * @param emitPower is the power of the particle (speed)
  51444. * @param worldMatrix is the world matrix of the particle system
  51445. * @param directionToUpdate is the direction vector to update with the result
  51446. * @param particle is the particle we are computed the direction for
  51447. */
  51448. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  51449. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  51450. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  51451. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  51452. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  51453. };
  51454. /**
  51455. * Clones the current emitter and returns a copy of it
  51456. * @returns the new emitter
  51457. */
  51458. SphereDirectedParticleEmitter.prototype.clone = function () {
  51459. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  51460. BABYLON.Tools.DeepCopy(this, newOne);
  51461. return newOne;
  51462. };
  51463. /**
  51464. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  51465. * @param effect defines the update shader
  51466. */
  51467. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  51468. effect.setFloat("radius", this.radius);
  51469. effect.setVector3("direction1", this.direction1);
  51470. effect.setVector3("direction2", this.direction2);
  51471. };
  51472. /**
  51473. * Returns a string to use to update the GPU particles update shader
  51474. * @returns a string containng the defines string
  51475. */
  51476. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  51477. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  51478. };
  51479. /**
  51480. * Returns the string "SphereDirectedParticleEmitter"
  51481. * @returns a string containing the class name
  51482. */
  51483. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  51484. return "SphereDirectedParticleEmitter";
  51485. };
  51486. /**
  51487. * Serializes the particle system to a JSON object.
  51488. * @returns the JSON object
  51489. */
  51490. SphereDirectedParticleEmitter.prototype.serialize = function () {
  51491. var serializationObject = _super.prototype.serialize.call(this);
  51492. ;
  51493. serializationObject.direction1 = this.direction1.asArray();
  51494. ;
  51495. serializationObject.direction2 = this.direction2.asArray();
  51496. ;
  51497. return serializationObject;
  51498. };
  51499. /**
  51500. * Parse properties from a JSON object
  51501. * @param serializationObject defines the JSON object
  51502. */
  51503. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  51504. _super.prototype.parse.call(this, serializationObject);
  51505. this.direction1.copyFrom(serializationObject.direction1);
  51506. this.direction2.copyFrom(serializationObject.direction2);
  51507. };
  51508. return SphereDirectedParticleEmitter;
  51509. }(SphereParticleEmitter));
  51510. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  51511. })(BABYLON || (BABYLON = {}));
  51512. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  51513. var __assign = (this && this.__assign) || Object.assign || function(t) {
  51514. for (var s, i = 1, n = arguments.length; i < n; i++) {
  51515. s = arguments[i];
  51516. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  51517. t[p] = s[p];
  51518. }
  51519. return t;
  51520. };
  51521. var BABYLON;
  51522. (function (BABYLON) {
  51523. /**
  51524. * This represents a GPU particle system in Babylon
  51525. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  51526. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  51527. */
  51528. var GPUParticleSystem = /** @class */ (function () {
  51529. /**
  51530. * Instantiates a GPU particle system.
  51531. * 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.
  51532. * @param name The name of the particle system
  51533. * @param capacity The max number of particles alive at the same time
  51534. * @param scene The scene the particle system belongs to
  51535. */
  51536. function GPUParticleSystem(name, options, scene) {
  51537. /**
  51538. * The emitter represents the Mesh or position we are attaching the particle system to.
  51539. */
  51540. this.emitter = null;
  51541. /**
  51542. * The rendering group used by the Particle system to chose when to render.
  51543. */
  51544. this.renderingGroupId = 0;
  51545. /**
  51546. * The layer mask we are rendering the particles through.
  51547. */
  51548. this.layerMask = 0x0FFFFFFF;
  51549. this._targetIndex = 0;
  51550. this._currentRenderId = -1;
  51551. this._started = false;
  51552. this._stopped = false;
  51553. this._timeDelta = 0;
  51554. this._attributesStrideSize = 14;
  51555. this._actualFrame = 0;
  51556. /**
  51557. * List of animations used by the particle system.
  51558. */
  51559. this.animations = [];
  51560. /**
  51561. * An event triggered when the system is disposed.
  51562. */
  51563. this.onDisposeObservable = new BABYLON.Observable();
  51564. /**
  51565. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51566. */
  51567. this.updateSpeed = 0.01;
  51568. /**
  51569. * The amount of time the particle system is running (depends of the overall update speed).
  51570. */
  51571. this.targetStopDuration = 0;
  51572. /**
  51573. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51574. */
  51575. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  51576. /**
  51577. * Minimum life time of emitting particles.
  51578. */
  51579. this.minLifeTime = 1;
  51580. /**
  51581. * Maximum life time of emitting particles.
  51582. */
  51583. this.maxLifeTime = 1;
  51584. /**
  51585. * Minimum Size of emitting particles.
  51586. */
  51587. this.minSize = 1;
  51588. /**
  51589. * Maximum Size of emitting particles.
  51590. */
  51591. this.maxSize = 1;
  51592. /**
  51593. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51594. */
  51595. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51596. /**
  51597. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51598. */
  51599. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51600. /**
  51601. * Color the particle will have at the end of its lifetime.
  51602. */
  51603. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  51604. /**
  51605. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  51606. */
  51607. this.emitRate = 100;
  51608. /**
  51609. * You can use gravity if you want to give an orientation to your particles.
  51610. */
  51611. this.gravity = BABYLON.Vector3.Zero();
  51612. /**
  51613. * Minimum power of emitting particles.
  51614. */
  51615. this.minEmitPower = 1;
  51616. /**
  51617. * Maximum power of emitting particles.
  51618. */
  51619. this.maxEmitPower = 1;
  51620. this.id = name;
  51621. this.name = name;
  51622. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51623. this._engine = this._scene.getEngine();
  51624. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  51625. this._capacity = fullOptions.capacity;
  51626. this._activeCount = fullOptions.capacity;
  51627. this._currentActiveCount = 0;
  51628. this._scene.particleSystems.push(this);
  51629. this._updateEffectOptions = {
  51630. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  51631. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  51632. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle"],
  51633. uniformBuffersNames: [],
  51634. samplers: ["randomSampler"],
  51635. defines: "",
  51636. fallbacks: null,
  51637. onCompiled: null,
  51638. onError: null,
  51639. indexParameters: null,
  51640. maxSimultaneousLights: 0,
  51641. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  51642. };
  51643. // Random data
  51644. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  51645. var d = [];
  51646. for (var i = 0; i < maxTextureSize; ++i) {
  51647. d.push(Math.random());
  51648. d.push(Math.random());
  51649. d.push(Math.random());
  51650. d.push(Math.random());
  51651. }
  51652. 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);
  51653. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  51654. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  51655. this._randomTextureSize = maxTextureSize;
  51656. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51657. }
  51658. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  51659. /**
  51660. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  51661. */
  51662. get: function () {
  51663. if (!BABYLON.Engine.LastCreatedEngine) {
  51664. return false;
  51665. }
  51666. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  51667. },
  51668. enumerable: true,
  51669. configurable: true
  51670. });
  51671. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  51672. /**
  51673. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51674. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51675. */
  51676. get: function () {
  51677. if (this.particleEmitterType.direction1) {
  51678. return this.particleEmitterType.direction1;
  51679. }
  51680. return BABYLON.Vector3.Zero();
  51681. },
  51682. set: function (value) {
  51683. if (this.particleEmitterType.direction1) {
  51684. this.particleEmitterType.direction1 = value;
  51685. }
  51686. },
  51687. enumerable: true,
  51688. configurable: true
  51689. });
  51690. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  51691. /**
  51692. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51693. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51694. */
  51695. get: function () {
  51696. if (this.particleEmitterType.direction2) {
  51697. return this.particleEmitterType.direction2;
  51698. }
  51699. return BABYLON.Vector3.Zero();
  51700. },
  51701. set: function (value) {
  51702. if (this.particleEmitterType.direction2) {
  51703. this.particleEmitterType.direction2 = value;
  51704. }
  51705. },
  51706. enumerable: true,
  51707. configurable: true
  51708. });
  51709. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  51710. /**
  51711. * 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.
  51712. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51713. */
  51714. get: function () {
  51715. if (this.particleEmitterType.minEmitBox) {
  51716. return this.particleEmitterType.minEmitBox;
  51717. }
  51718. return BABYLON.Vector3.Zero();
  51719. },
  51720. set: function (value) {
  51721. if (this.particleEmitterType.minEmitBox) {
  51722. this.particleEmitterType.minEmitBox = value;
  51723. }
  51724. },
  51725. enumerable: true,
  51726. configurable: true
  51727. });
  51728. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  51729. /**
  51730. * 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.
  51731. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51732. */
  51733. get: function () {
  51734. if (this.particleEmitterType.maxEmitBox) {
  51735. return this.particleEmitterType.maxEmitBox;
  51736. }
  51737. return BABYLON.Vector3.Zero();
  51738. },
  51739. set: function (value) {
  51740. if (this.particleEmitterType.maxEmitBox) {
  51741. this.particleEmitterType.maxEmitBox = value;
  51742. }
  51743. },
  51744. enumerable: true,
  51745. configurable: true
  51746. });
  51747. /**
  51748. * Gets the maximum number of particles active at the same time.
  51749. * @returns The max number of active particles.
  51750. */
  51751. GPUParticleSystem.prototype.getCapacity = function () {
  51752. return this._capacity;
  51753. };
  51754. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  51755. /**
  51756. * Gets or set the number of active particles
  51757. */
  51758. get: function () {
  51759. return this._activeCount;
  51760. },
  51761. set: function (value) {
  51762. this._activeCount = Math.min(value, this._capacity);
  51763. },
  51764. enumerable: true,
  51765. configurable: true
  51766. });
  51767. /**
  51768. * Gets Wether the system has been started.
  51769. * @returns True if it has been started, otherwise false.
  51770. */
  51771. GPUParticleSystem.prototype.isStarted = function () {
  51772. return this._started;
  51773. };
  51774. /**
  51775. * Starts the particle system and begins to emit.
  51776. */
  51777. GPUParticleSystem.prototype.start = function () {
  51778. this._started = true;
  51779. this._stopped = false;
  51780. };
  51781. /**
  51782. * Stops the particle system.
  51783. */
  51784. GPUParticleSystem.prototype.stop = function () {
  51785. this._stopped = true;
  51786. };
  51787. /**
  51788. * Remove all active particles
  51789. */
  51790. GPUParticleSystem.prototype.reset = function () {
  51791. this._releaseBuffers();
  51792. this._releaseVAOs();
  51793. this._currentActiveCount = 0;
  51794. this._targetIndex = 0;
  51795. };
  51796. /**
  51797. * Returns the string "GPUParticleSystem"
  51798. * @returns a string containing the class name
  51799. */
  51800. GPUParticleSystem.prototype.getClassName = function () {
  51801. return "GPUParticleSystem";
  51802. };
  51803. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  51804. var updateVertexBuffers = {};
  51805. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  51806. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  51807. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  51808. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  51809. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  51810. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  51811. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  51812. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  51813. this._engine.bindArrayBuffer(null);
  51814. return vao;
  51815. };
  51816. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  51817. var renderVertexBuffers = {};
  51818. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  51819. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  51820. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  51821. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  51822. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  51823. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  51824. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  51825. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  51826. this._engine.bindArrayBuffer(null);
  51827. return vao;
  51828. };
  51829. GPUParticleSystem.prototype._initialize = function (force) {
  51830. if (force === void 0) { force = false; }
  51831. if (this._buffer0 && !force) {
  51832. return;
  51833. }
  51834. var engine = this._scene.getEngine();
  51835. var data = new Array();
  51836. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  51837. // position
  51838. data.push(0.0);
  51839. data.push(0.0);
  51840. data.push(0.0);
  51841. // Age and life
  51842. data.push(0.0); // create the particle as a dead one to create a new one at start
  51843. data.push(0.0);
  51844. // Seed
  51845. data.push(Math.random());
  51846. // Size
  51847. data.push(0.0);
  51848. // color
  51849. data.push(0.0);
  51850. data.push(0.0);
  51851. data.push(0.0);
  51852. data.push(0.0);
  51853. // direction
  51854. data.push(0.0);
  51855. data.push(0.0);
  51856. data.push(0.0);
  51857. }
  51858. // Sprite data
  51859. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  51860. -0.5, 0.5, 0, 1,
  51861. -0.5, -0.5, 0, 0,
  51862. 0.5, -0.5, 1, 0]);
  51863. // Buffers
  51864. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  51865. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  51866. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  51867. // Update VAO
  51868. this._updateVAO = [];
  51869. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  51870. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  51871. // Render VAO
  51872. this._renderVAO = [];
  51873. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  51874. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  51875. // Links
  51876. this._sourceBuffer = this._buffer0;
  51877. this._targetBuffer = this._buffer1;
  51878. };
  51879. /** @ignore */
  51880. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  51881. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  51882. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  51883. return;
  51884. }
  51885. this._updateEffectOptions.defines = defines;
  51886. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  51887. };
  51888. /** @ignore */
  51889. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  51890. var defines = "";
  51891. if (this._scene.clipPlane) {
  51892. defines = "\n#define CLIPPLANE";
  51893. }
  51894. if (this._renderEffect && this._renderEffect.defines === defines) {
  51895. return;
  51896. }
  51897. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  51898. };
  51899. /**
  51900. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51901. */
  51902. GPUParticleSystem.prototype.animate = function () {
  51903. if (!this._stopped) {
  51904. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  51905. this._actualFrame += this._timeDelta;
  51906. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  51907. this.stop();
  51908. }
  51909. else {
  51910. this._timeDelta = 0;
  51911. }
  51912. };
  51913. /**
  51914. * Renders the particle system in its current state.
  51915. * @returns the current number of particles
  51916. */
  51917. GPUParticleSystem.prototype.render = function () {
  51918. if (!this._started) {
  51919. return 0;
  51920. }
  51921. this._recreateUpdateEffect();
  51922. this._recreateRenderEffect();
  51923. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady()) {
  51924. return 0;
  51925. }
  51926. if (this._currentRenderId === this._scene.getRenderId()) {
  51927. return 0;
  51928. }
  51929. this._currentRenderId = this._scene.getRenderId();
  51930. // Get everything ready to render
  51931. this._initialize();
  51932. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  51933. // Enable update effect
  51934. this._engine.enableEffect(this._updateEffect);
  51935. this._engine.setState(false);
  51936. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  51937. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  51938. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  51939. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  51940. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  51941. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  51942. this._updateEffect.setDirectColor4("color1", this.color1);
  51943. this._updateEffect.setDirectColor4("color2", this.color2);
  51944. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  51945. this._updateEffect.setVector3("gravity", this.gravity);
  51946. if (this.particleEmitterType) {
  51947. this.particleEmitterType.applyToShader(this._updateEffect);
  51948. }
  51949. var emitterWM;
  51950. if (this.emitter.position) {
  51951. var emitterMesh = this.emitter;
  51952. emitterWM = emitterMesh.getWorldMatrix();
  51953. }
  51954. else {
  51955. var emitterPosition = this.emitter;
  51956. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51957. }
  51958. this._updateEffect.setMatrix("emitterWM", emitterWM);
  51959. // Bind source VAO
  51960. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  51961. // Update
  51962. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  51963. this._engine.setRasterizerState(false);
  51964. this._engine.beginTransformFeedback();
  51965. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  51966. this._engine.endTransformFeedback();
  51967. this._engine.setRasterizerState(true);
  51968. this._engine.bindTransformFeedbackBuffer(null);
  51969. // Enable render effect
  51970. this._engine.enableEffect(this._renderEffect);
  51971. var viewMatrix = this._scene.getViewMatrix();
  51972. this._renderEffect.setMatrix("view", viewMatrix);
  51973. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  51974. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  51975. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  51976. if (this._scene.clipPlane) {
  51977. var clipPlane = this._scene.clipPlane;
  51978. var invView = viewMatrix.clone();
  51979. invView.invert();
  51980. this._renderEffect.setMatrix("invView", invView);
  51981. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  51982. }
  51983. // Draw order
  51984. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  51985. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  51986. }
  51987. else {
  51988. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  51989. }
  51990. // Bind source VAO
  51991. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  51992. // Render
  51993. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  51994. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  51995. // Switch VAOs
  51996. this._targetIndex++;
  51997. if (this._targetIndex === 2) {
  51998. this._targetIndex = 0;
  51999. }
  52000. // Switch buffers
  52001. var tmpBuffer = this._sourceBuffer;
  52002. this._sourceBuffer = this._targetBuffer;
  52003. this._targetBuffer = tmpBuffer;
  52004. return this._currentActiveCount;
  52005. };
  52006. /**
  52007. * Rebuilds the particle system
  52008. */
  52009. GPUParticleSystem.prototype.rebuild = function () {
  52010. this._initialize(true);
  52011. };
  52012. GPUParticleSystem.prototype._releaseBuffers = function () {
  52013. if (this._buffer0) {
  52014. this._buffer0.dispose();
  52015. this._buffer0 = null;
  52016. }
  52017. if (this._buffer1) {
  52018. this._buffer1.dispose();
  52019. this._buffer1 = null;
  52020. }
  52021. if (this._spriteBuffer) {
  52022. this._spriteBuffer.dispose();
  52023. this._spriteBuffer = null;
  52024. }
  52025. };
  52026. GPUParticleSystem.prototype._releaseVAOs = function () {
  52027. for (var index = 0; index < this._updateVAO.length; index++) {
  52028. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  52029. }
  52030. this._updateVAO = [];
  52031. for (var index = 0; index < this._renderVAO.length; index++) {
  52032. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  52033. }
  52034. this._renderVAO = [];
  52035. };
  52036. /**
  52037. * Disposes the particle system and free the associated resources.
  52038. */
  52039. GPUParticleSystem.prototype.dispose = function () {
  52040. var index = this._scene.particleSystems.indexOf(this);
  52041. if (index > -1) {
  52042. this._scene.particleSystems.splice(index, 1);
  52043. }
  52044. this._releaseBuffers();
  52045. this._releaseVAOs();
  52046. if (this._randomTexture) {
  52047. this._randomTexture.dispose();
  52048. this._randomTexture = null;
  52049. }
  52050. // Callback
  52051. this.onDisposeObservable.notifyObservers(this);
  52052. this.onDisposeObservable.clear();
  52053. };
  52054. /**
  52055. * Clones the particle system.
  52056. * @param name The name of the cloned object
  52057. * @param newEmitter The new emitter to use
  52058. * @returns the cloned particle system
  52059. */
  52060. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  52061. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  52062. BABYLON.Tools.DeepCopy(this, result);
  52063. if (newEmitter === undefined) {
  52064. newEmitter = this.emitter;
  52065. }
  52066. result.emitter = newEmitter;
  52067. if (this.particleTexture) {
  52068. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52069. }
  52070. return result;
  52071. };
  52072. /**
  52073. * Serializes the particle system to a JSON object.
  52074. * @returns the JSON object
  52075. */
  52076. GPUParticleSystem.prototype.serialize = function () {
  52077. var serializationObject = {};
  52078. serializationObject.name = this.name;
  52079. serializationObject.id = this.id;
  52080. // Emitter
  52081. if (this.emitter.position) {
  52082. var emitterMesh = this.emitter;
  52083. serializationObject.emitterId = emitterMesh.id;
  52084. }
  52085. else {
  52086. var emitterPosition = this.emitter;
  52087. serializationObject.emitter = emitterPosition.asArray();
  52088. }
  52089. serializationObject.capacity = this.getCapacity();
  52090. if (this.particleTexture) {
  52091. serializationObject.textureName = this.particleTexture.name;
  52092. }
  52093. // Animations
  52094. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52095. // Particle system
  52096. serializationObject.activeParticleCount = this.activeParticleCount;
  52097. serializationObject.randomTextureSize = this._randomTextureSize;
  52098. serializationObject.minSize = this.minSize;
  52099. serializationObject.maxSize = this.maxSize;
  52100. serializationObject.minEmitPower = this.minEmitPower;
  52101. serializationObject.maxEmitPower = this.maxEmitPower;
  52102. serializationObject.minLifeTime = this.minLifeTime;
  52103. serializationObject.maxLifeTime = this.maxLifeTime;
  52104. serializationObject.emitRate = this.emitRate;
  52105. serializationObject.gravity = this.gravity.asArray();
  52106. serializationObject.color1 = this.color1.asArray();
  52107. serializationObject.color2 = this.color2.asArray();
  52108. serializationObject.colorDead = this.colorDead.asArray();
  52109. serializationObject.updateSpeed = this.updateSpeed;
  52110. serializationObject.targetStopDuration = this.targetStopDuration;
  52111. serializationObject.blendMode = this.blendMode;
  52112. // Emitter
  52113. if (this.particleEmitterType) {
  52114. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52115. }
  52116. return serializationObject;
  52117. };
  52118. /**
  52119. * Parses a JSON object to create a GPU particle system.
  52120. * @param parsedParticleSystem The JSON object to parse
  52121. * @param scene The scene to create the particle system in
  52122. * @param rootUrl The root url to use to load external dependencies like texture
  52123. * @returns the parsed GPU particle system
  52124. */
  52125. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52126. var name = parsedParticleSystem.name;
  52127. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  52128. if (parsedParticleSystem.id) {
  52129. particleSystem.id = parsedParticleSystem.id;
  52130. }
  52131. // Texture
  52132. if (parsedParticleSystem.textureName) {
  52133. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52134. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52135. }
  52136. // Emitter
  52137. if (parsedParticleSystem.emitterId) {
  52138. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52139. }
  52140. else {
  52141. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52142. }
  52143. // Animations
  52144. if (parsedParticleSystem.animations) {
  52145. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52146. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52147. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52148. }
  52149. }
  52150. // Particle system
  52151. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  52152. particleSystem.minSize = parsedParticleSystem.minSize;
  52153. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52154. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52155. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52156. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52157. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52158. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52159. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52160. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52161. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52162. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52163. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52164. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52165. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52166. // Emitter
  52167. if (parsedParticleSystem.particleEmitterType) {
  52168. var emitterType = void 0;
  52169. switch (parsedParticleSystem.particleEmitterType.type) {
  52170. case "SphereEmitter":
  52171. emitterType = new BABYLON.SphereParticleEmitter();
  52172. break;
  52173. case "SphereDirectedParticleEmitter":
  52174. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  52175. break;
  52176. case "ConeEmitter":
  52177. emitterType = new BABYLON.ConeParticleEmitter();
  52178. break;
  52179. case "BoxEmitter":
  52180. default:
  52181. emitterType = new BABYLON.BoxParticleEmitter();
  52182. break;
  52183. }
  52184. emitterType.parse(parsedParticleSystem.particleEmitterType);
  52185. particleSystem.particleEmitterType = emitterType;
  52186. }
  52187. return particleSystem;
  52188. };
  52189. return GPUParticleSystem;
  52190. }());
  52191. BABYLON.GPUParticleSystem = GPUParticleSystem;
  52192. })(BABYLON || (BABYLON = {}));
  52193. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  52194. var BABYLON;
  52195. (function (BABYLON) {
  52196. /**
  52197. * Represents one particle of a solid particle system.
  52198. * @see SolidParticleSystem
  52199. */
  52200. var SolidParticle = /** @class */ (function () {
  52201. /**
  52202. * Creates a Solid Particle object.
  52203. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  52204. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  52205. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  52206. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  52207. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  52208. * @param shapeId (integer) is the model shape identifier in the SPS.
  52209. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  52210. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  52211. */
  52212. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  52213. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  52214. /**
  52215. * particle global index
  52216. */
  52217. this.idx = 0;
  52218. /**
  52219. * The color of the particle
  52220. */
  52221. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52222. /**
  52223. * The world space position of the particle.
  52224. */
  52225. this.position = BABYLON.Vector3.Zero();
  52226. /**
  52227. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  52228. */
  52229. this.rotation = BABYLON.Vector3.Zero();
  52230. /**
  52231. * The scaling of the particle.
  52232. */
  52233. this.scaling = BABYLON.Vector3.One();
  52234. /**
  52235. * The uvs of the particle.
  52236. */
  52237. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  52238. /**
  52239. * The current speed of the particle.
  52240. */
  52241. this.velocity = BABYLON.Vector3.Zero();
  52242. /**
  52243. * The pivot point in the particle local space.
  52244. */
  52245. this.pivot = BABYLON.Vector3.Zero();
  52246. /**
  52247. * Must the particle be translated from its pivot point in its local space ?
  52248. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  52249. * Default : false
  52250. */
  52251. this.translateFromPivot = false;
  52252. /**
  52253. * Is the particle active or not ?
  52254. */
  52255. this.alive = true;
  52256. /**
  52257. * Is the particle visible or not ?
  52258. */
  52259. this.isVisible = true;
  52260. /**
  52261. * Index of this particle in the global "positions" array (Internal use)
  52262. */
  52263. this._pos = 0;
  52264. /**
  52265. * Index of this particle in the global "indices" array (Internal use)
  52266. */
  52267. this._ind = 0;
  52268. /**
  52269. * ModelShape id of this particle
  52270. */
  52271. this.shapeId = 0;
  52272. /**
  52273. * Index of the particle in its shape id (Internal use)
  52274. */
  52275. this.idxInShape = 0;
  52276. /**
  52277. * Still set as invisible in order to skip useless computations (Internal use)
  52278. */
  52279. this._stillInvisible = false;
  52280. /**
  52281. * Last computed particle rotation matrix
  52282. */
  52283. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  52284. /**
  52285. * Parent particle Id, if any.
  52286. * Default null.
  52287. */
  52288. this.parentId = null;
  52289. /**
  52290. * Internal global position in the SPS.
  52291. */
  52292. this._globalPosition = BABYLON.Vector3.Zero();
  52293. this.idx = particleIndex;
  52294. this._pos = positionIndex;
  52295. this._ind = indiceIndex;
  52296. this._model = model;
  52297. this.shapeId = shapeId;
  52298. this.idxInShape = idxInShape;
  52299. this._sps = sps;
  52300. if (modelBoundingInfo) {
  52301. this._modelBoundingInfo = modelBoundingInfo;
  52302. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  52303. }
  52304. }
  52305. Object.defineProperty(SolidParticle.prototype, "scale", {
  52306. /**
  52307. * Legacy support, changed scale to scaling
  52308. */
  52309. get: function () {
  52310. return this.scaling;
  52311. },
  52312. /**
  52313. * Legacy support, changed scale to scaling
  52314. */
  52315. set: function (scale) {
  52316. this.scaling = scale;
  52317. },
  52318. enumerable: true,
  52319. configurable: true
  52320. });
  52321. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  52322. /**
  52323. * Legacy support, changed quaternion to rotationQuaternion
  52324. */
  52325. get: function () {
  52326. return this.rotationQuaternion;
  52327. },
  52328. /**
  52329. * Legacy support, changed quaternion to rotationQuaternion
  52330. */
  52331. set: function (q) {
  52332. this.rotationQuaternion = q;
  52333. },
  52334. enumerable: true,
  52335. configurable: true
  52336. });
  52337. /**
  52338. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  52339. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  52340. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  52341. * @returns true if it intersects
  52342. */
  52343. SolidParticle.prototype.intersectsMesh = function (target) {
  52344. if (!this._boundingInfo || !target._boundingInfo) {
  52345. return false;
  52346. }
  52347. if (this._sps._bSphereOnly) {
  52348. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  52349. }
  52350. return this._boundingInfo.intersects(target._boundingInfo, false);
  52351. };
  52352. return SolidParticle;
  52353. }());
  52354. BABYLON.SolidParticle = SolidParticle;
  52355. /**
  52356. * Represents the shape of the model used by one particle of a solid particle system.
  52357. * SPS internal tool, don't use it manually.
  52358. * @see SolidParticleSystem
  52359. */
  52360. var ModelShape = /** @class */ (function () {
  52361. /**
  52362. * 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.
  52363. * SPS internal tool, don't use it manually.
  52364. * @ignore
  52365. */
  52366. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  52367. /**
  52368. * length of the shape in the model indices array (internal use)
  52369. */
  52370. this._indicesLength = 0;
  52371. this.shapeID = id;
  52372. this._shape = shape;
  52373. this._indicesLength = indicesLength;
  52374. this._shapeUV = shapeUV;
  52375. this._positionFunction = posFunction;
  52376. this._vertexFunction = vtxFunction;
  52377. }
  52378. return ModelShape;
  52379. }());
  52380. BABYLON.ModelShape = ModelShape;
  52381. /**
  52382. * Represents a Depth Sorted Particle in the solid particle system.
  52383. * @see SolidParticleSystem
  52384. */
  52385. var DepthSortedParticle = /** @class */ (function () {
  52386. function DepthSortedParticle() {
  52387. /**
  52388. * Index of the particle in the "indices" array
  52389. */
  52390. this.ind = 0;
  52391. /**
  52392. * Length of the particle shape in the "indices" array
  52393. */
  52394. this.indicesLength = 0;
  52395. /**
  52396. * Squared distance from the particle to the camera
  52397. */
  52398. this.sqDistance = 0.0;
  52399. }
  52400. return DepthSortedParticle;
  52401. }());
  52402. BABYLON.DepthSortedParticle = DepthSortedParticle;
  52403. })(BABYLON || (BABYLON = {}));
  52404. //# sourceMappingURL=babylon.solidParticle.js.map
  52405. var BABYLON;
  52406. (function (BABYLON) {
  52407. /**
  52408. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  52409. *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.
  52410. * The SPS is also a particle system. It provides some methods to manage the particles.
  52411. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  52412. *
  52413. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  52414. */
  52415. var SolidParticleSystem = /** @class */ (function () {
  52416. /**
  52417. * Creates a SPS (Solid Particle System) object.
  52418. * @param name (String) is the SPS name, this will be the underlying mesh name.
  52419. * @param scene (Scene) is the scene in which the SPS is added.
  52420. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  52421. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  52422. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  52423. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  52424. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  52425. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  52426. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  52427. */
  52428. function SolidParticleSystem(name, scene, options) {
  52429. /**
  52430. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  52431. * Example : var p = SPS.particles[i];
  52432. */
  52433. this.particles = new Array();
  52434. /**
  52435. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  52436. */
  52437. this.nbParticles = 0;
  52438. /**
  52439. * If the particles must ever face the camera (default false). Useful for planar particles.
  52440. */
  52441. this.billboard = false;
  52442. /**
  52443. * Recompute normals when adding a shape
  52444. */
  52445. this.recomputeNormals = true;
  52446. /**
  52447. * This a counter ofr your own usage. It's not set by any SPS functions.
  52448. */
  52449. this.counter = 0;
  52450. /**
  52451. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  52452. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  52453. */
  52454. this.vars = {};
  52455. /**
  52456. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  52457. */
  52458. this._bSphereOnly = false;
  52459. /**
  52460. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  52461. */
  52462. this._bSphereRadiusFactor = 1.0;
  52463. this._positions = new Array();
  52464. this._indices = new Array();
  52465. this._normals = new Array();
  52466. this._colors = new Array();
  52467. this._uvs = new Array();
  52468. this._index = 0; // indices index
  52469. this._updatable = true;
  52470. this._pickable = false;
  52471. this._isVisibilityBoxLocked = false;
  52472. this._alwaysVisible = false;
  52473. this._depthSort = false;
  52474. this._shapeCounter = 0;
  52475. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  52476. this._color = new BABYLON.Color4(0, 0, 0, 0);
  52477. this._computeParticleColor = true;
  52478. this._computeParticleTexture = true;
  52479. this._computeParticleRotation = true;
  52480. this._computeParticleVertex = false;
  52481. this._computeBoundingBox = false;
  52482. this._depthSortParticles = true;
  52483. this._cam_axisZ = BABYLON.Vector3.Zero();
  52484. this._cam_axisY = BABYLON.Vector3.Zero();
  52485. this._cam_axisX = BABYLON.Vector3.Zero();
  52486. this._axisZ = BABYLON.Axis.Z;
  52487. this._camDir = BABYLON.Vector3.Zero();
  52488. this._camInvertedPosition = BABYLON.Vector3.Zero();
  52489. this._rotMatrix = new BABYLON.Matrix();
  52490. this._invertMatrix = new BABYLON.Matrix();
  52491. this._rotated = BABYLON.Vector3.Zero();
  52492. this._quaternion = new BABYLON.Quaternion();
  52493. this._vertex = BABYLON.Vector3.Zero();
  52494. this._normal = BABYLON.Vector3.Zero();
  52495. this._yaw = 0.0;
  52496. this._pitch = 0.0;
  52497. this._roll = 0.0;
  52498. this._halfroll = 0.0;
  52499. this._halfpitch = 0.0;
  52500. this._halfyaw = 0.0;
  52501. this._sinRoll = 0.0;
  52502. this._cosRoll = 0.0;
  52503. this._sinPitch = 0.0;
  52504. this._cosPitch = 0.0;
  52505. this._sinYaw = 0.0;
  52506. this._cosYaw = 0.0;
  52507. this._mustUnrotateFixedNormals = false;
  52508. this._minimum = BABYLON.Vector3.Zero();
  52509. this._maximum = BABYLON.Vector3.Zero();
  52510. this._minBbox = BABYLON.Vector3.Zero();
  52511. this._maxBbox = BABYLON.Vector3.Zero();
  52512. this._particlesIntersect = false;
  52513. this._depthSortFunction = function (p1, p2) {
  52514. return (p2.sqDistance - p1.sqDistance);
  52515. };
  52516. this._needs32Bits = false;
  52517. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  52518. this._scaledPivot = BABYLON.Vector3.Zero();
  52519. this._particleHasParent = false;
  52520. this.name = name;
  52521. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52522. this._camera = scene.activeCamera;
  52523. this._pickable = options ? options.isPickable : false;
  52524. this._depthSort = options ? options.enableDepthSort : false;
  52525. this._particlesIntersect = options ? options.particleIntersection : false;
  52526. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  52527. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  52528. if (options && options.updatable) {
  52529. this._updatable = options.updatable;
  52530. }
  52531. else {
  52532. this._updatable = true;
  52533. }
  52534. if (this._pickable) {
  52535. this.pickedParticles = [];
  52536. }
  52537. if (this._depthSort) {
  52538. this.depthSortedParticles = [];
  52539. }
  52540. }
  52541. /**
  52542. * Builds the SPS underlying mesh. Returns a standard Mesh.
  52543. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  52544. * @returns the created mesh
  52545. */
  52546. SolidParticleSystem.prototype.buildMesh = function () {
  52547. if (this.nbParticles === 0) {
  52548. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  52549. this.addShape(triangle, 1);
  52550. triangle.dispose();
  52551. }
  52552. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  52553. this._positions32 = new Float32Array(this._positions);
  52554. this._uvs32 = new Float32Array(this._uvs);
  52555. this._colors32 = new Float32Array(this._colors);
  52556. if (this.recomputeNormals) {
  52557. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  52558. }
  52559. this._normals32 = new Float32Array(this._normals);
  52560. this._fixedNormal32 = new Float32Array(this._normals);
  52561. if (this._mustUnrotateFixedNormals) {
  52562. this._unrotateFixedNormals();
  52563. }
  52564. var vertexData = new BABYLON.VertexData();
  52565. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  52566. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  52567. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  52568. if (this._uvs32) {
  52569. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  52570. ;
  52571. }
  52572. if (this._colors32) {
  52573. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  52574. }
  52575. var mesh = new BABYLON.Mesh(this.name, this._scene);
  52576. vertexData.applyToMesh(mesh, this._updatable);
  52577. this.mesh = mesh;
  52578. this.mesh.isPickable = this._pickable;
  52579. // free memory
  52580. if (!this._depthSort) {
  52581. this._indices = null;
  52582. }
  52583. this._positions = null;
  52584. this._normals = null;
  52585. this._uvs = null;
  52586. this._colors = null;
  52587. if (!this._updatable) {
  52588. this.particles.length = 0;
  52589. }
  52590. return mesh;
  52591. };
  52592. /**
  52593. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  52594. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  52595. * Thus the particles generated from `digest()` have their property `position` set yet.
  52596. * @param mesh ( Mesh ) is the mesh to be digested
  52597. * @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
  52598. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  52599. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  52600. * @returns the current SPS
  52601. */
  52602. SolidParticleSystem.prototype.digest = function (mesh, options) {
  52603. var size = (options && options.facetNb) || 1;
  52604. var number = (options && options.number) || 0;
  52605. var delta = (options && options.delta) || 0;
  52606. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52607. var meshInd = mesh.getIndices();
  52608. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52609. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52610. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52611. var f = 0; // facet counter
  52612. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  52613. // compute size from number
  52614. if (number) {
  52615. number = (number > totalFacets) ? totalFacets : number;
  52616. size = Math.round(totalFacets / number);
  52617. delta = 0;
  52618. }
  52619. else {
  52620. size = (size > totalFacets) ? totalFacets : size;
  52621. }
  52622. var facetPos = []; // submesh positions
  52623. var facetInd = []; // submesh indices
  52624. var facetUV = []; // submesh UV
  52625. var facetCol = []; // submesh colors
  52626. var barycenter = BABYLON.Vector3.Zero();
  52627. var sizeO = size;
  52628. while (f < totalFacets) {
  52629. size = sizeO + Math.floor((1 + delta) * Math.random());
  52630. if (f > totalFacets - size) {
  52631. size = totalFacets - f;
  52632. }
  52633. // reset temp arrays
  52634. facetPos.length = 0;
  52635. facetInd.length = 0;
  52636. facetUV.length = 0;
  52637. facetCol.length = 0;
  52638. // iterate over "size" facets
  52639. var fi = 0;
  52640. for (var j = f * 3; j < (f + size) * 3; j++) {
  52641. facetInd.push(fi);
  52642. var i = meshInd[j];
  52643. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  52644. if (meshUV) {
  52645. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  52646. }
  52647. if (meshCol) {
  52648. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  52649. }
  52650. fi++;
  52651. }
  52652. // create a model shape for each single particle
  52653. var idx = this.nbParticles;
  52654. var shape = this._posToShape(facetPos);
  52655. var shapeUV = this._uvsToShapeUV(facetUV);
  52656. // compute the barycenter of the shape
  52657. var v;
  52658. for (v = 0; v < shape.length; v++) {
  52659. barycenter.addInPlace(shape[v]);
  52660. }
  52661. barycenter.scaleInPlace(1 / shape.length);
  52662. // shift the shape from its barycenter to the origin
  52663. for (v = 0; v < shape.length; v++) {
  52664. shape[v].subtractInPlace(barycenter);
  52665. }
  52666. var bInfo;
  52667. if (this._particlesIntersect) {
  52668. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  52669. }
  52670. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  52671. // add the particle in the SPS
  52672. var currentPos = this._positions.length;
  52673. var currentInd = this._indices.length;
  52674. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  52675. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  52676. // initialize the particle position
  52677. this.particles[this.nbParticles].position.addInPlace(barycenter);
  52678. this._index += shape.length;
  52679. idx++;
  52680. this.nbParticles++;
  52681. this._shapeCounter++;
  52682. f += size;
  52683. }
  52684. return this;
  52685. };
  52686. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  52687. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  52688. var index = 0;
  52689. var idx = 0;
  52690. for (var p = 0; p < this.particles.length; p++) {
  52691. this._particle = this.particles[p];
  52692. this._shape = this._particle._model._shape;
  52693. if (this._particle.rotationQuaternion) {
  52694. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  52695. }
  52696. else {
  52697. this._yaw = this._particle.rotation.y;
  52698. this._pitch = this._particle.rotation.x;
  52699. this._roll = this._particle.rotation.z;
  52700. this._quaternionRotationYPR();
  52701. }
  52702. this._quaternionToRotationMatrix();
  52703. this._rotMatrix.invertToRef(this._invertMatrix);
  52704. for (var pt = 0; pt < this._shape.length; pt++) {
  52705. idx = index + pt * 3;
  52706. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  52707. this._fixedNormal32[idx] = this._normal.x;
  52708. this._fixedNormal32[idx + 1] = this._normal.y;
  52709. this._fixedNormal32[idx + 2] = this._normal.z;
  52710. }
  52711. index = idx + 3;
  52712. }
  52713. };
  52714. //reset copy
  52715. SolidParticleSystem.prototype._resetCopy = function () {
  52716. this._copy.position.x = 0;
  52717. this._copy.position.y = 0;
  52718. this._copy.position.z = 0;
  52719. this._copy.rotation.x = 0;
  52720. this._copy.rotation.y = 0;
  52721. this._copy.rotation.z = 0;
  52722. this._copy.rotationQuaternion = null;
  52723. this._copy.scaling.x = 1.0;
  52724. this._copy.scaling.y = 1.0;
  52725. this._copy.scaling.z = 1.0;
  52726. this._copy.uvs.x = 0;
  52727. this._copy.uvs.y = 0;
  52728. this._copy.uvs.z = 1.0;
  52729. this._copy.uvs.w = 1.0;
  52730. this._copy.color = null;
  52731. this._copy.translateFromPivot = false;
  52732. };
  52733. // _meshBuilder : inserts the shape model in the global SPS mesh
  52734. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  52735. var i;
  52736. var u = 0;
  52737. var c = 0;
  52738. var n = 0;
  52739. this._resetCopy();
  52740. if (options && options.positionFunction) {
  52741. options.positionFunction(this._copy, idx, idxInShape);
  52742. this._mustUnrotateFixedNormals = true;
  52743. }
  52744. if (this._copy.rotationQuaternion) {
  52745. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52746. }
  52747. else {
  52748. this._yaw = this._copy.rotation.y;
  52749. this._pitch = this._copy.rotation.x;
  52750. this._roll = this._copy.rotation.z;
  52751. this._quaternionRotationYPR();
  52752. }
  52753. this._quaternionToRotationMatrix();
  52754. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  52755. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  52756. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  52757. if (this._copy.translateFromPivot) {
  52758. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52759. }
  52760. else {
  52761. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52762. }
  52763. for (i = 0; i < shape.length; i++) {
  52764. this._vertex.x = shape[i].x;
  52765. this._vertex.y = shape[i].y;
  52766. this._vertex.z = shape[i].z;
  52767. if (options && options.vertexFunction) {
  52768. options.vertexFunction(this._copy, this._vertex, i);
  52769. }
  52770. this._vertex.x *= this._copy.scaling.x;
  52771. this._vertex.y *= this._copy.scaling.y;
  52772. this._vertex.z *= this._copy.scaling.z;
  52773. this._vertex.x -= this._scaledPivot.x;
  52774. this._vertex.y -= this._scaledPivot.y;
  52775. this._vertex.z -= this._scaledPivot.z;
  52776. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52777. this._rotated.addInPlace(this._pivotBackTranslation);
  52778. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  52779. if (meshUV) {
  52780. 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);
  52781. u += 2;
  52782. }
  52783. if (this._copy.color) {
  52784. this._color = this._copy.color;
  52785. }
  52786. else if (meshCol && meshCol[c] !== undefined) {
  52787. this._color.r = meshCol[c];
  52788. this._color.g = meshCol[c + 1];
  52789. this._color.b = meshCol[c + 2];
  52790. this._color.a = meshCol[c + 3];
  52791. }
  52792. else {
  52793. this._color.r = 1.0;
  52794. this._color.g = 1.0;
  52795. this._color.b = 1.0;
  52796. this._color.a = 1.0;
  52797. }
  52798. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  52799. c += 4;
  52800. if (!this.recomputeNormals && meshNor) {
  52801. this._normal.x = meshNor[n];
  52802. this._normal.y = meshNor[n + 1];
  52803. this._normal.z = meshNor[n + 2];
  52804. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  52805. normals.push(this._normal.x, this._normal.y, this._normal.z);
  52806. n += 3;
  52807. }
  52808. }
  52809. for (i = 0; i < meshInd.length; i++) {
  52810. var current_ind = p + meshInd[i];
  52811. indices.push(current_ind);
  52812. if (current_ind > 65535) {
  52813. this._needs32Bits = true;
  52814. }
  52815. }
  52816. if (this._pickable) {
  52817. var nbfaces = meshInd.length / 3;
  52818. for (i = 0; i < nbfaces; i++) {
  52819. this.pickedParticles.push({ idx: idx, faceId: i });
  52820. }
  52821. }
  52822. if (this._depthSort) {
  52823. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  52824. }
  52825. return this._copy;
  52826. };
  52827. // returns a shape array from positions array
  52828. SolidParticleSystem.prototype._posToShape = function (positions) {
  52829. var shape = [];
  52830. for (var i = 0; i < positions.length; i += 3) {
  52831. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  52832. }
  52833. return shape;
  52834. };
  52835. // returns a shapeUV array from a Vector4 uvs
  52836. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  52837. var shapeUV = [];
  52838. if (uvs) {
  52839. for (var i = 0; i < uvs.length; i++)
  52840. shapeUV.push(uvs[i]);
  52841. }
  52842. return shapeUV;
  52843. };
  52844. // adds a new particle object in the particles array
  52845. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  52846. if (bInfo === void 0) { bInfo = null; }
  52847. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  52848. this.particles.push(sp);
  52849. return sp;
  52850. };
  52851. /**
  52852. * Adds some particles to the SPS from the model shape. Returns the shape id.
  52853. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  52854. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  52855. * @param nb (positive integer) the number of particles to be created from this model
  52856. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  52857. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  52858. * @returns the number of shapes in the system
  52859. */
  52860. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  52861. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  52862. var meshInd = mesh.getIndices();
  52863. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  52864. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  52865. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  52866. var bbInfo;
  52867. if (this._particlesIntersect) {
  52868. bbInfo = mesh.getBoundingInfo();
  52869. }
  52870. var shape = this._posToShape(meshPos);
  52871. var shapeUV = this._uvsToShapeUV(meshUV);
  52872. var posfunc = options ? options.positionFunction : null;
  52873. var vtxfunc = options ? options.vertexFunction : null;
  52874. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  52875. // particles
  52876. var sp;
  52877. var currentCopy;
  52878. var idx = this.nbParticles;
  52879. for (var i = 0; i < nb; i++) {
  52880. var currentPos = this._positions.length;
  52881. var currentInd = this._indices.length;
  52882. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  52883. if (this._updatable) {
  52884. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  52885. sp.position.copyFrom(currentCopy.position);
  52886. sp.rotation.copyFrom(currentCopy.rotation);
  52887. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  52888. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  52889. }
  52890. if (currentCopy.color && sp.color) {
  52891. sp.color.copyFrom(currentCopy.color);
  52892. }
  52893. sp.scaling.copyFrom(currentCopy.scaling);
  52894. sp.uvs.copyFrom(currentCopy.uvs);
  52895. }
  52896. this._index += shape.length;
  52897. idx++;
  52898. }
  52899. this.nbParticles += nb;
  52900. this._shapeCounter++;
  52901. return this._shapeCounter - 1;
  52902. };
  52903. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  52904. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  52905. this._resetCopy();
  52906. if (particle._model._positionFunction) {
  52907. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  52908. }
  52909. if (this._copy.rotationQuaternion) {
  52910. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  52911. }
  52912. else {
  52913. this._yaw = this._copy.rotation.y;
  52914. this._pitch = this._copy.rotation.x;
  52915. this._roll = this._copy.rotation.z;
  52916. this._quaternionRotationYPR();
  52917. }
  52918. this._quaternionToRotationMatrix();
  52919. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  52920. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  52921. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  52922. if (this._copy.translateFromPivot) {
  52923. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  52924. }
  52925. else {
  52926. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  52927. }
  52928. this._shape = particle._model._shape;
  52929. for (var pt = 0; pt < this._shape.length; pt++) {
  52930. this._vertex.x = this._shape[pt].x;
  52931. this._vertex.y = this._shape[pt].y;
  52932. this._vertex.z = this._shape[pt].z;
  52933. if (particle._model._vertexFunction) {
  52934. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  52935. }
  52936. this._vertex.x *= this._copy.scaling.x;
  52937. this._vertex.y *= this._copy.scaling.y;
  52938. this._vertex.z *= this._copy.scaling.z;
  52939. this._vertex.x -= this._scaledPivot.x;
  52940. this._vertex.y -= this._scaledPivot.y;
  52941. this._vertex.z -= this._scaledPivot.z;
  52942. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  52943. this._rotated.addInPlace(this._pivotBackTranslation);
  52944. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  52945. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  52946. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  52947. }
  52948. particle.position.x = 0.0;
  52949. particle.position.y = 0.0;
  52950. particle.position.z = 0.0;
  52951. particle.rotation.x = 0.0;
  52952. particle.rotation.y = 0.0;
  52953. particle.rotation.z = 0.0;
  52954. particle.rotationQuaternion = null;
  52955. particle.scaling.x = 1.0;
  52956. particle.scaling.y = 1.0;
  52957. particle.scaling.z = 1.0;
  52958. particle.uvs.x = 0.0;
  52959. particle.uvs.y = 0.0;
  52960. particle.uvs.z = 1.0;
  52961. particle.uvs.w = 1.0;
  52962. particle.pivot.x = 0.0;
  52963. particle.pivot.y = 0.0;
  52964. particle.pivot.z = 0.0;
  52965. particle.translateFromPivot = false;
  52966. particle.parentId = null;
  52967. };
  52968. /**
  52969. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  52970. * @returns the SPS.
  52971. */
  52972. SolidParticleSystem.prototype.rebuildMesh = function () {
  52973. for (var p = 0; p < this.particles.length; p++) {
  52974. this._rebuildParticle(this.particles[p]);
  52975. }
  52976. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  52977. return this;
  52978. };
  52979. /**
  52980. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  52981. * This method calls `updateParticle()` for each particle of the SPS.
  52982. * For an animated SPS, it is usually called within the render loop.
  52983. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  52984. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  52985. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  52986. * @returns the SPS.
  52987. */
  52988. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  52989. if (start === void 0) { start = 0; }
  52990. if (end === void 0) { end = this.nbParticles - 1; }
  52991. if (update === void 0) { update = true; }
  52992. if (!this._updatable) {
  52993. return this;
  52994. }
  52995. // custom beforeUpdate
  52996. this.beforeUpdateParticles(start, end, update);
  52997. this._cam_axisX.x = 1.0;
  52998. this._cam_axisX.y = 0.0;
  52999. this._cam_axisX.z = 0.0;
  53000. this._cam_axisY.x = 0.0;
  53001. this._cam_axisY.y = 1.0;
  53002. this._cam_axisY.z = 0.0;
  53003. this._cam_axisZ.x = 0.0;
  53004. this._cam_axisZ.y = 0.0;
  53005. this._cam_axisZ.z = 1.0;
  53006. // cases when the World Matrix is to be computed first
  53007. if (this.billboard || this._depthSort) {
  53008. this.mesh.computeWorldMatrix(true);
  53009. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  53010. }
  53011. // if the particles will always face the camera
  53012. if (this.billboard) {
  53013. // compute the camera position and un-rotate it by the current mesh rotation
  53014. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  53015. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  53016. this._cam_axisZ.normalize();
  53017. // same for camera up vector extracted from the cam view matrix
  53018. var view = this._camera.getViewMatrix(true);
  53019. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  53020. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  53021. this._cam_axisY.normalize();
  53022. this._cam_axisX.normalize();
  53023. }
  53024. // if depthSort, compute the camera global position in the mesh local system
  53025. if (this._depthSort) {
  53026. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  53027. }
  53028. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  53029. var idx = 0; // current position index in the global array positions32
  53030. var index = 0; // position start index in the global array positions32 of the current particle
  53031. var colidx = 0; // current color index in the global array colors32
  53032. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  53033. var uvidx = 0; // current uv index in the global array uvs32
  53034. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  53035. var pt = 0; // current index in the particle model shape
  53036. if (this.mesh.isFacetDataEnabled) {
  53037. this._computeBoundingBox = true;
  53038. }
  53039. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  53040. if (this._computeBoundingBox) {
  53041. if (start == 0 && end == this.nbParticles - 1) {
  53042. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  53043. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  53044. }
  53045. else {
  53046. if (this.mesh._boundingInfo) {
  53047. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  53048. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  53049. }
  53050. }
  53051. }
  53052. // particle loop
  53053. index = this.particles[start]._pos;
  53054. var vpos = (index / 3) | 0;
  53055. colorIndex = vpos * 4;
  53056. uvIndex = vpos * 2;
  53057. for (var p = start; p <= end; p++) {
  53058. this._particle = this.particles[p];
  53059. this._shape = this._particle._model._shape;
  53060. this._shapeUV = this._particle._model._shapeUV;
  53061. // call to custom user function to update the particle properties
  53062. this.updateParticle(this._particle);
  53063. // camera-particle distance for depth sorting
  53064. if (this._depthSort && this._depthSortParticles) {
  53065. var dsp = this.depthSortedParticles[p];
  53066. dsp.ind = this._particle._ind;
  53067. dsp.indicesLength = this._particle._model._indicesLength;
  53068. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  53069. }
  53070. // skip the computations for inactive or already invisible particles
  53071. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  53072. // increment indexes for the next particle
  53073. pt = this._shape.length;
  53074. index += pt * 3;
  53075. colorIndex += pt * 4;
  53076. uvIndex += pt * 2;
  53077. continue;
  53078. }
  53079. if (this._particle.isVisible) {
  53080. this._particle._stillInvisible = false; // un-mark permanent invisibility
  53081. this._particleHasParent = (this._particle.parentId !== null);
  53082. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  53083. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  53084. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  53085. // particle rotation matrix
  53086. if (this.billboard) {
  53087. this._particle.rotation.x = 0.0;
  53088. this._particle.rotation.y = 0.0;
  53089. }
  53090. if (this._computeParticleRotation || this.billboard) {
  53091. if (this._particle.rotationQuaternion) {
  53092. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  53093. }
  53094. else {
  53095. this._yaw = this._particle.rotation.y;
  53096. this._pitch = this._particle.rotation.x;
  53097. this._roll = this._particle.rotation.z;
  53098. this._quaternionRotationYPR();
  53099. }
  53100. this._quaternionToRotationMatrix();
  53101. }
  53102. if (this._particleHasParent) {
  53103. this._parent = this.particles[this._particle.parentId];
  53104. 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];
  53105. 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];
  53106. 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];
  53107. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  53108. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  53109. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  53110. if (this._computeParticleRotation || this.billboard) {
  53111. 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];
  53112. 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];
  53113. 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];
  53114. 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];
  53115. 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];
  53116. 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];
  53117. 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];
  53118. 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];
  53119. 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];
  53120. }
  53121. }
  53122. else {
  53123. this._particle._globalPosition.x = this._particle.position.x;
  53124. this._particle._globalPosition.y = this._particle.position.y;
  53125. this._particle._globalPosition.z = this._particle.position.z;
  53126. if (this._computeParticleRotation || this.billboard) {
  53127. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  53128. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  53129. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  53130. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  53131. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  53132. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  53133. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  53134. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  53135. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  53136. }
  53137. }
  53138. if (this._particle.translateFromPivot) {
  53139. this._pivotBackTranslation.x = 0.0;
  53140. this._pivotBackTranslation.y = 0.0;
  53141. this._pivotBackTranslation.z = 0.0;
  53142. }
  53143. else {
  53144. this._pivotBackTranslation.x = this._scaledPivot.x;
  53145. this._pivotBackTranslation.y = this._scaledPivot.y;
  53146. this._pivotBackTranslation.z = this._scaledPivot.z;
  53147. }
  53148. // particle vertex loop
  53149. for (pt = 0; pt < this._shape.length; pt++) {
  53150. idx = index + pt * 3;
  53151. colidx = colorIndex + pt * 4;
  53152. uvidx = uvIndex + pt * 2;
  53153. this._vertex.x = this._shape[pt].x;
  53154. this._vertex.y = this._shape[pt].y;
  53155. this._vertex.z = this._shape[pt].z;
  53156. if (this._computeParticleVertex) {
  53157. this.updateParticleVertex(this._particle, this._vertex, pt);
  53158. }
  53159. // positions
  53160. this._vertex.x *= this._particle.scaling.x;
  53161. this._vertex.y *= this._particle.scaling.y;
  53162. this._vertex.z *= this._particle.scaling.z;
  53163. this._vertex.x -= this._scaledPivot.x;
  53164. this._vertex.y -= this._scaledPivot.y;
  53165. this._vertex.z -= this._scaledPivot.z;
  53166. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53167. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53168. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53169. this._rotated.x += this._pivotBackTranslation.x;
  53170. this._rotated.y += this._pivotBackTranslation.y;
  53171. this._rotated.z += this._pivotBackTranslation.z;
  53172. 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;
  53173. 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;
  53174. 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;
  53175. if (this._computeBoundingBox) {
  53176. if (this._positions32[idx] < this._minimum.x) {
  53177. this._minimum.x = this._positions32[idx];
  53178. }
  53179. if (this._positions32[idx] > this._maximum.x) {
  53180. this._maximum.x = this._positions32[idx];
  53181. }
  53182. if (this._positions32[idx + 1] < this._minimum.y) {
  53183. this._minimum.y = this._positions32[idx + 1];
  53184. }
  53185. if (this._positions32[idx + 1] > this._maximum.y) {
  53186. this._maximum.y = this._positions32[idx + 1];
  53187. }
  53188. if (this._positions32[idx + 2] < this._minimum.z) {
  53189. this._minimum.z = this._positions32[idx + 2];
  53190. }
  53191. if (this._positions32[idx + 2] > this._maximum.z) {
  53192. this._maximum.z = this._positions32[idx + 2];
  53193. }
  53194. }
  53195. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  53196. if (!this._computeParticleVertex) {
  53197. this._normal.x = this._fixedNormal32[idx];
  53198. this._normal.y = this._fixedNormal32[idx + 1];
  53199. this._normal.z = this._fixedNormal32[idx + 2];
  53200. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  53201. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  53202. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  53203. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  53204. 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;
  53205. 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;
  53206. }
  53207. if (this._computeParticleColor && this._particle.color) {
  53208. this._colors32[colidx] = this._particle.color.r;
  53209. this._colors32[colidx + 1] = this._particle.color.g;
  53210. this._colors32[colidx + 2] = this._particle.color.b;
  53211. this._colors32[colidx + 3] = this._particle.color.a;
  53212. }
  53213. if (this._computeParticleTexture) {
  53214. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53215. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53216. }
  53217. }
  53218. }
  53219. else {
  53220. this._particle._stillInvisible = true; // mark the particle as invisible
  53221. for (pt = 0; pt < this._shape.length; pt++) {
  53222. idx = index + pt * 3;
  53223. colidx = colorIndex + pt * 4;
  53224. uvidx = uvIndex + pt * 2;
  53225. this._positions32[idx] = 0.0;
  53226. this._positions32[idx + 1] = 0.0;
  53227. this._positions32[idx + 2] = 0.0;
  53228. this._normals32[idx] = 0.0;
  53229. this._normals32[idx + 1] = 0.0;
  53230. this._normals32[idx + 2] = 0.0;
  53231. if (this._computeParticleColor && this._particle.color) {
  53232. this._colors32[colidx] = this._particle.color.r;
  53233. this._colors32[colidx + 1] = this._particle.color.g;
  53234. this._colors32[colidx + 2] = this._particle.color.b;
  53235. this._colors32[colidx + 3] = this._particle.color.a;
  53236. }
  53237. if (this._computeParticleTexture) {
  53238. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  53239. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  53240. }
  53241. }
  53242. }
  53243. // if the particle intersections must be computed : update the bbInfo
  53244. if (this._particlesIntersect) {
  53245. var bInfo = this._particle._boundingInfo;
  53246. var bBox = bInfo.boundingBox;
  53247. var bSphere = bInfo.boundingSphere;
  53248. if (!this._bSphereOnly) {
  53249. // place, scale and rotate the particle bbox within the SPS local system, then update it
  53250. for (var b = 0; b < bBox.vectors.length; b++) {
  53251. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  53252. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  53253. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  53254. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  53255. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  53256. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  53257. 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;
  53258. 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;
  53259. 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;
  53260. }
  53261. bBox._update(this.mesh._worldMatrix);
  53262. }
  53263. // place and scale the particle bouding sphere in the SPS local system, then update it
  53264. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  53265. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  53266. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  53267. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  53268. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  53269. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  53270. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  53271. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  53272. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  53273. 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));
  53274. bSphere._update(this.mesh._worldMatrix);
  53275. }
  53276. // increment indexes for the next particle
  53277. index = idx + 3;
  53278. colorIndex = colidx + 4;
  53279. uvIndex = uvidx + 2;
  53280. }
  53281. // if the VBO must be updated
  53282. if (update) {
  53283. if (this._computeParticleColor) {
  53284. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  53285. }
  53286. if (this._computeParticleTexture) {
  53287. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  53288. }
  53289. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  53290. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  53291. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  53292. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  53293. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  53294. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  53295. for (var i = 0; i < this._normals32.length; i++) {
  53296. this._fixedNormal32[i] = this._normals32[i];
  53297. }
  53298. }
  53299. if (!this.mesh.areNormalsFrozen) {
  53300. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  53301. }
  53302. }
  53303. if (this._depthSort && this._depthSortParticles) {
  53304. this.depthSortedParticles.sort(this._depthSortFunction);
  53305. var dspl = this.depthSortedParticles.length;
  53306. var sorted = 0;
  53307. var lind = 0;
  53308. var sind = 0;
  53309. var sid = 0;
  53310. for (sorted = 0; sorted < dspl; sorted++) {
  53311. lind = this.depthSortedParticles[sorted].indicesLength;
  53312. sind = this.depthSortedParticles[sorted].ind;
  53313. for (var i = 0; i < lind; i++) {
  53314. this._indices32[sid] = this._indices[sind + i];
  53315. sid++;
  53316. }
  53317. }
  53318. this.mesh.updateIndices(this._indices32);
  53319. }
  53320. }
  53321. if (this._computeBoundingBox) {
  53322. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  53323. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  53324. }
  53325. this.afterUpdateParticles(start, end, update);
  53326. return this;
  53327. };
  53328. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  53329. this._halfroll = this._roll * 0.5;
  53330. this._halfpitch = this._pitch * 0.5;
  53331. this._halfyaw = this._yaw * 0.5;
  53332. this._sinRoll = Math.sin(this._halfroll);
  53333. this._cosRoll = Math.cos(this._halfroll);
  53334. this._sinPitch = Math.sin(this._halfpitch);
  53335. this._cosPitch = Math.cos(this._halfpitch);
  53336. this._sinYaw = Math.sin(this._halfyaw);
  53337. this._cosYaw = Math.cos(this._halfyaw);
  53338. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  53339. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  53340. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  53341. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  53342. };
  53343. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  53344. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  53345. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  53346. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  53347. this._rotMatrix.m[3] = 0;
  53348. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  53349. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  53350. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  53351. this._rotMatrix.m[7] = 0;
  53352. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  53353. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  53354. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  53355. this._rotMatrix.m[11] = 0;
  53356. this._rotMatrix.m[12] = 0;
  53357. this._rotMatrix.m[13] = 0;
  53358. this._rotMatrix.m[14] = 0;
  53359. this._rotMatrix.m[15] = 1.0;
  53360. };
  53361. /**
  53362. * Disposes the SPS.
  53363. */
  53364. SolidParticleSystem.prototype.dispose = function () {
  53365. this.mesh.dispose();
  53366. this.vars = null;
  53367. // drop references to internal big arrays for the GC
  53368. this._positions = null;
  53369. this._indices = null;
  53370. this._normals = null;
  53371. this._uvs = null;
  53372. this._colors = null;
  53373. this._indices32 = null;
  53374. this._positions32 = null;
  53375. this._normals32 = null;
  53376. this._fixedNormal32 = null;
  53377. this._uvs32 = null;
  53378. this._colors32 = null;
  53379. this.pickedParticles = null;
  53380. };
  53381. /**
  53382. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  53383. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53384. * @returns the SPS.
  53385. */
  53386. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  53387. if (!this._isVisibilityBoxLocked) {
  53388. this.mesh.refreshBoundingInfo();
  53389. }
  53390. return this;
  53391. };
  53392. /**
  53393. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  53394. * @param size the size (float) of the visibility box
  53395. * note : this doesn't lock the SPS mesh bounding box.
  53396. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53397. */
  53398. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  53399. var vis = size / 2;
  53400. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  53401. };
  53402. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  53403. /**
  53404. * Gets whether the SPS as always visible or not
  53405. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53406. */
  53407. get: function () {
  53408. return this._alwaysVisible;
  53409. },
  53410. /**
  53411. * Sets the SPS as always visible or not
  53412. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53413. */
  53414. set: function (val) {
  53415. this._alwaysVisible = val;
  53416. this.mesh.alwaysSelectAsActiveMesh = val;
  53417. },
  53418. enumerable: true,
  53419. configurable: true
  53420. });
  53421. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  53422. /**
  53423. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53424. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53425. */
  53426. get: function () {
  53427. return this._isVisibilityBoxLocked;
  53428. },
  53429. /**
  53430. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  53431. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  53432. */
  53433. set: function (val) {
  53434. this._isVisibilityBoxLocked = val;
  53435. var boundingInfo = this.mesh.getBoundingInfo();
  53436. boundingInfo.isLocked = val;
  53437. },
  53438. enumerable: true,
  53439. configurable: true
  53440. });
  53441. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  53442. /**
  53443. * Gets if `setParticles()` computes the particle rotations or not.
  53444. * Default value : true. The SPS is faster when it's set to false.
  53445. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53446. */
  53447. get: function () {
  53448. return this._computeParticleRotation;
  53449. },
  53450. /**
  53451. * Tells to `setParticles()` to compute the particle rotations or not.
  53452. * Default value : true. The SPS is faster when it's set to false.
  53453. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  53454. */
  53455. set: function (val) {
  53456. this._computeParticleRotation = val;
  53457. },
  53458. enumerable: true,
  53459. configurable: true
  53460. });
  53461. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  53462. /**
  53463. * Gets if `setParticles()` computes the particle colors or not.
  53464. * Default value : true. The SPS is faster when it's set to false.
  53465. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53466. */
  53467. get: function () {
  53468. return this._computeParticleColor;
  53469. },
  53470. /**
  53471. * Tells to `setParticles()` to compute the particle colors or not.
  53472. * Default value : true. The SPS is faster when it's set to false.
  53473. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  53474. */
  53475. set: function (val) {
  53476. this._computeParticleColor = val;
  53477. },
  53478. enumerable: true,
  53479. configurable: true
  53480. });
  53481. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  53482. /**
  53483. * Gets if `setParticles()` computes the particle textures or not.
  53484. * Default value : true. The SPS is faster when it's set to false.
  53485. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  53486. */
  53487. get: function () {
  53488. return this._computeParticleTexture;
  53489. },
  53490. set: function (val) {
  53491. this._computeParticleTexture = val;
  53492. },
  53493. enumerable: true,
  53494. configurable: true
  53495. });
  53496. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  53497. /**
  53498. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  53499. * Default value : false. The SPS is faster when it's set to false.
  53500. * Note : the particle custom vertex positions aren't stored values.
  53501. */
  53502. get: function () {
  53503. return this._computeParticleVertex;
  53504. },
  53505. /**
  53506. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  53507. * Default value : false. The SPS is faster when it's set to false.
  53508. * Note : the particle custom vertex positions aren't stored values.
  53509. */
  53510. set: function (val) {
  53511. this._computeParticleVertex = val;
  53512. },
  53513. enumerable: true,
  53514. configurable: true
  53515. });
  53516. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  53517. /**
  53518. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  53519. */
  53520. get: function () {
  53521. return this._computeBoundingBox;
  53522. },
  53523. /**
  53524. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  53525. */
  53526. set: function (val) {
  53527. this._computeBoundingBox = val;
  53528. },
  53529. enumerable: true,
  53530. configurable: true
  53531. });
  53532. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  53533. /**
  53534. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  53535. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53536. * Default : `true`
  53537. */
  53538. get: function () {
  53539. return this._depthSortParticles;
  53540. },
  53541. /**
  53542. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  53543. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  53544. * Default : `true`
  53545. */
  53546. set: function (val) {
  53547. this._depthSortParticles = val;
  53548. },
  53549. enumerable: true,
  53550. configurable: true
  53551. });
  53552. // =======================================================================
  53553. // Particle behavior logic
  53554. // these following methods may be overwritten by the user to fit his needs
  53555. /**
  53556. * This function does nothing. It may be overwritten to set all the particle first values.
  53557. * The SPS doesn't call this function, you may have to call it by your own.
  53558. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53559. */
  53560. SolidParticleSystem.prototype.initParticles = function () {
  53561. };
  53562. /**
  53563. * This function does nothing. It may be overwritten to recycle a particle.
  53564. * The SPS doesn't call this function, you may have to call it by your own.
  53565. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53566. * @param particle The particle to recycle
  53567. * @returns the recycled particle
  53568. */
  53569. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  53570. return particle;
  53571. };
  53572. /**
  53573. * Updates a particle : this function should be overwritten by the user.
  53574. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  53575. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  53576. * @example : just set a particle position or velocity and recycle conditions
  53577. * @param particle The particle to update
  53578. * @returns the updated particle
  53579. */
  53580. SolidParticleSystem.prototype.updateParticle = function (particle) {
  53581. return particle;
  53582. };
  53583. /**
  53584. * Updates a vertex of a particle : it can be overwritten by the user.
  53585. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  53586. * @param particle the current particle
  53587. * @param vertex the current index of the current particle
  53588. * @param pt the index of the current vertex in the particle shape
  53589. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  53590. * @example : just set a vertex particle position
  53591. * @returns the updated vertex
  53592. */
  53593. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  53594. return vertex;
  53595. };
  53596. /**
  53597. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  53598. * This does nothing and may be overwritten by the user.
  53599. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53600. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53601. * @param update the boolean update value actually passed to setParticles()
  53602. */
  53603. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  53604. };
  53605. /**
  53606. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  53607. * This will be passed three parameters.
  53608. * This does nothing and may be overwritten by the user.
  53609. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53610. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  53611. * @param update the boolean update value actually passed to setParticles()
  53612. */
  53613. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  53614. };
  53615. return SolidParticleSystem;
  53616. }());
  53617. BABYLON.SolidParticleSystem = SolidParticleSystem;
  53618. })(BABYLON || (BABYLON = {}));
  53619. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  53620. var BABYLON;
  53621. (function (BABYLON) {
  53622. var ShaderMaterial = /** @class */ (function (_super) {
  53623. __extends(ShaderMaterial, _super);
  53624. function ShaderMaterial(name, scene, shaderPath, options) {
  53625. var _this = _super.call(this, name, scene) || this;
  53626. _this._textures = {};
  53627. _this._textureArrays = {};
  53628. _this._floats = {};
  53629. _this._ints = {};
  53630. _this._floatsArrays = {};
  53631. _this._colors3 = {};
  53632. _this._colors3Arrays = {};
  53633. _this._colors4 = {};
  53634. _this._vectors2 = {};
  53635. _this._vectors3 = {};
  53636. _this._vectors4 = {};
  53637. _this._matrices = {};
  53638. _this._matrices3x3 = {};
  53639. _this._matrices2x2 = {};
  53640. _this._vectors2Arrays = {};
  53641. _this._vectors3Arrays = {};
  53642. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  53643. _this._shaderPath = shaderPath;
  53644. options.needAlphaBlending = options.needAlphaBlending || false;
  53645. options.needAlphaTesting = options.needAlphaTesting || false;
  53646. options.attributes = options.attributes || ["position", "normal", "uv"];
  53647. options.uniforms = options.uniforms || ["worldViewProjection"];
  53648. options.uniformBuffers = options.uniformBuffers || [];
  53649. options.samplers = options.samplers || [];
  53650. options.defines = options.defines || [];
  53651. _this._options = options;
  53652. return _this;
  53653. }
  53654. ShaderMaterial.prototype.getClassName = function () {
  53655. return "ShaderMaterial";
  53656. };
  53657. ShaderMaterial.prototype.needAlphaBlending = function () {
  53658. return this._options.needAlphaBlending;
  53659. };
  53660. ShaderMaterial.prototype.needAlphaTesting = function () {
  53661. return this._options.needAlphaTesting;
  53662. };
  53663. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  53664. if (this._options.uniforms.indexOf(uniformName) === -1) {
  53665. this._options.uniforms.push(uniformName);
  53666. }
  53667. };
  53668. ShaderMaterial.prototype.setTexture = function (name, texture) {
  53669. if (this._options.samplers.indexOf(name) === -1) {
  53670. this._options.samplers.push(name);
  53671. }
  53672. this._textures[name] = texture;
  53673. return this;
  53674. };
  53675. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  53676. if (this._options.samplers.indexOf(name) === -1) {
  53677. this._options.samplers.push(name);
  53678. }
  53679. this._checkUniform(name);
  53680. this._textureArrays[name] = textures;
  53681. return this;
  53682. };
  53683. ShaderMaterial.prototype.setFloat = function (name, value) {
  53684. this._checkUniform(name);
  53685. this._floats[name] = value;
  53686. return this;
  53687. };
  53688. ShaderMaterial.prototype.setInt = function (name, value) {
  53689. this._checkUniform(name);
  53690. this._ints[name] = value;
  53691. return this;
  53692. };
  53693. ShaderMaterial.prototype.setFloats = function (name, value) {
  53694. this._checkUniform(name);
  53695. this._floatsArrays[name] = value;
  53696. return this;
  53697. };
  53698. ShaderMaterial.prototype.setColor3 = function (name, value) {
  53699. this._checkUniform(name);
  53700. this._colors3[name] = value;
  53701. return this;
  53702. };
  53703. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  53704. this._checkUniform(name);
  53705. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  53706. color.toArray(arr, arr.length);
  53707. return arr;
  53708. }, []);
  53709. return this;
  53710. };
  53711. ShaderMaterial.prototype.setColor4 = function (name, value) {
  53712. this._checkUniform(name);
  53713. this._colors4[name] = value;
  53714. return this;
  53715. };
  53716. ShaderMaterial.prototype.setVector2 = function (name, value) {
  53717. this._checkUniform(name);
  53718. this._vectors2[name] = value;
  53719. return this;
  53720. };
  53721. ShaderMaterial.prototype.setVector3 = function (name, value) {
  53722. this._checkUniform(name);
  53723. this._vectors3[name] = value;
  53724. return this;
  53725. };
  53726. ShaderMaterial.prototype.setVector4 = function (name, value) {
  53727. this._checkUniform(name);
  53728. this._vectors4[name] = value;
  53729. return this;
  53730. };
  53731. ShaderMaterial.prototype.setMatrix = function (name, value) {
  53732. this._checkUniform(name);
  53733. this._matrices[name] = value;
  53734. return this;
  53735. };
  53736. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  53737. this._checkUniform(name);
  53738. this._matrices3x3[name] = value;
  53739. return this;
  53740. };
  53741. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  53742. this._checkUniform(name);
  53743. this._matrices2x2[name] = value;
  53744. return this;
  53745. };
  53746. ShaderMaterial.prototype.setArray2 = function (name, value) {
  53747. this._checkUniform(name);
  53748. this._vectors2Arrays[name] = value;
  53749. return this;
  53750. };
  53751. ShaderMaterial.prototype.setArray3 = function (name, value) {
  53752. this._checkUniform(name);
  53753. this._vectors3Arrays[name] = value;
  53754. return this;
  53755. };
  53756. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53757. if (!mesh) {
  53758. return true;
  53759. }
  53760. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  53761. return false;
  53762. }
  53763. return false;
  53764. };
  53765. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  53766. var scene = this.getScene();
  53767. var engine = scene.getEngine();
  53768. if (!this.checkReadyOnEveryCall) {
  53769. if (this._renderId === scene.getRenderId()) {
  53770. if (this._checkCache(scene, mesh, useInstances)) {
  53771. return true;
  53772. }
  53773. }
  53774. }
  53775. // Instances
  53776. var defines = [];
  53777. var attribs = [];
  53778. var fallbacks = new BABYLON.EffectFallbacks();
  53779. if (useInstances) {
  53780. defines.push("#define INSTANCES");
  53781. }
  53782. for (var index = 0; index < this._options.defines.length; index++) {
  53783. defines.push(this._options.defines[index]);
  53784. }
  53785. for (var index = 0; index < this._options.attributes.length; index++) {
  53786. attribs.push(this._options.attributes[index]);
  53787. }
  53788. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53789. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53790. defines.push("#define VERTEXCOLOR");
  53791. }
  53792. // Bones
  53793. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  53794. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  53795. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  53796. if (mesh.numBoneInfluencers > 4) {
  53797. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  53798. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  53799. }
  53800. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  53801. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  53802. fallbacks.addCPUSkinningFallback(0, mesh);
  53803. if (this._options.uniforms.indexOf("mBones") === -1) {
  53804. this._options.uniforms.push("mBones");
  53805. }
  53806. }
  53807. else {
  53808. defines.push("#define NUM_BONE_INFLUENCERS 0");
  53809. }
  53810. // Textures
  53811. for (var name in this._textures) {
  53812. if (!this._textures[name].isReady()) {
  53813. return false;
  53814. }
  53815. }
  53816. // Alpha test
  53817. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  53818. defines.push("#define ALPHATEST");
  53819. }
  53820. var previousEffect = this._effect;
  53821. var join = defines.join("\n");
  53822. this._effect = engine.createEffect(this._shaderPath, {
  53823. attributes: attribs,
  53824. uniformsNames: this._options.uniforms,
  53825. uniformBuffersNames: this._options.uniformBuffers,
  53826. samplers: this._options.samplers,
  53827. defines: join,
  53828. fallbacks: fallbacks,
  53829. onCompiled: this.onCompiled,
  53830. onError: this.onError
  53831. }, engine);
  53832. if (!this._effect.isReady()) {
  53833. return false;
  53834. }
  53835. if (previousEffect !== this._effect) {
  53836. scene.resetCachedMaterial();
  53837. }
  53838. this._renderId = scene.getRenderId();
  53839. return true;
  53840. };
  53841. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53842. var scene = this.getScene();
  53843. if (!this._effect) {
  53844. return;
  53845. }
  53846. if (this._options.uniforms.indexOf("world") !== -1) {
  53847. this._effect.setMatrix("world", world);
  53848. }
  53849. if (this._options.uniforms.indexOf("worldView") !== -1) {
  53850. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  53851. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  53852. }
  53853. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  53854. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  53855. }
  53856. };
  53857. ShaderMaterial.prototype.bind = function (world, mesh) {
  53858. // Std values
  53859. this.bindOnlyWorldMatrix(world);
  53860. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  53861. if (this._options.uniforms.indexOf("view") !== -1) {
  53862. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  53863. }
  53864. if (this._options.uniforms.indexOf("projection") !== -1) {
  53865. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  53866. }
  53867. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  53868. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  53869. }
  53870. // Bones
  53871. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53872. var name;
  53873. // Texture
  53874. for (name in this._textures) {
  53875. this._effect.setTexture(name, this._textures[name]);
  53876. }
  53877. // Texture arrays
  53878. for (name in this._textureArrays) {
  53879. this._effect.setTextureArray(name, this._textureArrays[name]);
  53880. }
  53881. // Int
  53882. for (name in this._ints) {
  53883. this._effect.setInt(name, this._ints[name]);
  53884. }
  53885. // Float
  53886. for (name in this._floats) {
  53887. this._effect.setFloat(name, this._floats[name]);
  53888. }
  53889. // Floats
  53890. for (name in this._floatsArrays) {
  53891. this._effect.setArray(name, this._floatsArrays[name]);
  53892. }
  53893. // Color3
  53894. for (name in this._colors3) {
  53895. this._effect.setColor3(name, this._colors3[name]);
  53896. }
  53897. for (name in this._colors3Arrays) {
  53898. this._effect.setArray3(name, this._colors3Arrays[name]);
  53899. }
  53900. // Color4
  53901. for (name in this._colors4) {
  53902. var color = this._colors4[name];
  53903. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  53904. }
  53905. // Vector2
  53906. for (name in this._vectors2) {
  53907. this._effect.setVector2(name, this._vectors2[name]);
  53908. }
  53909. // Vector3
  53910. for (name in this._vectors3) {
  53911. this._effect.setVector3(name, this._vectors3[name]);
  53912. }
  53913. // Vector4
  53914. for (name in this._vectors4) {
  53915. this._effect.setVector4(name, this._vectors4[name]);
  53916. }
  53917. // Matrix
  53918. for (name in this._matrices) {
  53919. this._effect.setMatrix(name, this._matrices[name]);
  53920. }
  53921. // Matrix 3x3
  53922. for (name in this._matrices3x3) {
  53923. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  53924. }
  53925. // Matrix 2x2
  53926. for (name in this._matrices2x2) {
  53927. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  53928. }
  53929. // Vector2Array
  53930. for (name in this._vectors2Arrays) {
  53931. this._effect.setArray2(name, this._vectors2Arrays[name]);
  53932. }
  53933. // Vector3Array
  53934. for (name in this._vectors3Arrays) {
  53935. this._effect.setArray3(name, this._vectors3Arrays[name]);
  53936. }
  53937. }
  53938. this._afterBind(mesh);
  53939. };
  53940. ShaderMaterial.prototype.getActiveTextures = function () {
  53941. var activeTextures = _super.prototype.getActiveTextures.call(this);
  53942. for (var name in this._textures) {
  53943. activeTextures.push(this._textures[name]);
  53944. }
  53945. for (var name in this._textureArrays) {
  53946. var array = this._textureArrays[name];
  53947. for (var index = 0; index < array.length; index++) {
  53948. activeTextures.push(array[index]);
  53949. }
  53950. }
  53951. return activeTextures;
  53952. };
  53953. ShaderMaterial.prototype.hasTexture = function (texture) {
  53954. if (_super.prototype.hasTexture.call(this, texture)) {
  53955. return true;
  53956. }
  53957. for (var name in this._textures) {
  53958. if (this._textures[name] === texture) {
  53959. return true;
  53960. }
  53961. }
  53962. for (var name in this._textureArrays) {
  53963. var array = this._textureArrays[name];
  53964. for (var index = 0; index < array.length; index++) {
  53965. if (array[index] === texture) {
  53966. return true;
  53967. }
  53968. }
  53969. }
  53970. return false;
  53971. };
  53972. ShaderMaterial.prototype.clone = function (name) {
  53973. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  53974. return newShaderMaterial;
  53975. };
  53976. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  53977. if (forceDisposeTextures) {
  53978. var name;
  53979. for (name in this._textures) {
  53980. this._textures[name].dispose();
  53981. }
  53982. for (name in this._textureArrays) {
  53983. var array = this._textureArrays[name];
  53984. for (var index = 0; index < array.length; index++) {
  53985. array[index].dispose();
  53986. }
  53987. }
  53988. }
  53989. this._textures = {};
  53990. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  53991. };
  53992. ShaderMaterial.prototype.serialize = function () {
  53993. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53994. serializationObject.customType = "BABYLON.ShaderMaterial";
  53995. serializationObject.options = this._options;
  53996. serializationObject.shaderPath = this._shaderPath;
  53997. var name;
  53998. // Texture
  53999. serializationObject.textures = {};
  54000. for (name in this._textures) {
  54001. serializationObject.textures[name] = this._textures[name].serialize();
  54002. }
  54003. // Texture arrays
  54004. serializationObject.textureArrays = {};
  54005. for (name in this._textureArrays) {
  54006. serializationObject.textureArrays[name] = [];
  54007. var array = this._textureArrays[name];
  54008. for (var index = 0; index < array.length; index++) {
  54009. serializationObject.textureArrays[name].push(array[index].serialize());
  54010. }
  54011. }
  54012. // Float
  54013. serializationObject.floats = {};
  54014. for (name in this._floats) {
  54015. serializationObject.floats[name] = this._floats[name];
  54016. }
  54017. // Float s
  54018. serializationObject.FloatArrays = {};
  54019. for (name in this._floatsArrays) {
  54020. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  54021. }
  54022. // Color3
  54023. serializationObject.colors3 = {};
  54024. for (name in this._colors3) {
  54025. serializationObject.colors3[name] = this._colors3[name].asArray();
  54026. }
  54027. // Color3 array
  54028. serializationObject.colors3Arrays = {};
  54029. for (name in this._colors3Arrays) {
  54030. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  54031. }
  54032. // Color4
  54033. serializationObject.colors4 = {};
  54034. for (name in this._colors4) {
  54035. serializationObject.colors4[name] = this._colors4[name].asArray();
  54036. }
  54037. // Vector2
  54038. serializationObject.vectors2 = {};
  54039. for (name in this._vectors2) {
  54040. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  54041. }
  54042. // Vector3
  54043. serializationObject.vectors3 = {};
  54044. for (name in this._vectors3) {
  54045. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  54046. }
  54047. // Vector4
  54048. serializationObject.vectors4 = {};
  54049. for (name in this._vectors4) {
  54050. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  54051. }
  54052. // Matrix
  54053. serializationObject.matrices = {};
  54054. for (name in this._matrices) {
  54055. serializationObject.matrices[name] = this._matrices[name].asArray();
  54056. }
  54057. // Matrix 3x3
  54058. serializationObject.matrices3x3 = {};
  54059. for (name in this._matrices3x3) {
  54060. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  54061. }
  54062. // Matrix 2x2
  54063. serializationObject.matrices2x2 = {};
  54064. for (name in this._matrices2x2) {
  54065. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  54066. }
  54067. // Vector2Array
  54068. serializationObject.vectors2Arrays = {};
  54069. for (name in this._vectors2Arrays) {
  54070. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  54071. }
  54072. // Vector3Array
  54073. serializationObject.vectors3Arrays = {};
  54074. for (name in this._vectors3Arrays) {
  54075. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  54076. }
  54077. return serializationObject;
  54078. };
  54079. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  54080. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  54081. var name;
  54082. // Texture
  54083. for (name in source.textures) {
  54084. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  54085. }
  54086. // Texture arrays
  54087. for (name in source.textureArrays) {
  54088. var array = source.textureArrays[name];
  54089. var textureArray = new Array();
  54090. for (var index = 0; index < array.length; index++) {
  54091. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  54092. }
  54093. material.setTextureArray(name, textureArray);
  54094. }
  54095. // Float
  54096. for (name in source.floats) {
  54097. material.setFloat(name, source.floats[name]);
  54098. }
  54099. // Float s
  54100. for (name in source.floatsArrays) {
  54101. material.setFloats(name, source.floatsArrays[name]);
  54102. }
  54103. // Color3
  54104. for (name in source.colors3) {
  54105. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  54106. }
  54107. // Color3 arrays
  54108. for (name in source.colors3Arrays) {
  54109. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  54110. if (i % 3 === 0) {
  54111. arr.push([num]);
  54112. }
  54113. else {
  54114. arr[arr.length - 1].push(num);
  54115. }
  54116. return arr;
  54117. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  54118. material.setColor3Array(name, colors);
  54119. }
  54120. // Color4
  54121. for (name in source.colors4) {
  54122. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  54123. }
  54124. // Vector2
  54125. for (name in source.vectors2) {
  54126. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  54127. }
  54128. // Vector3
  54129. for (name in source.vectors3) {
  54130. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  54131. }
  54132. // Vector4
  54133. for (name in source.vectors4) {
  54134. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  54135. }
  54136. // Matrix
  54137. for (name in source.matrices) {
  54138. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  54139. }
  54140. // Matrix 3x3
  54141. for (name in source.matrices3x3) {
  54142. material.setMatrix3x3(name, source.matrices3x3[name]);
  54143. }
  54144. // Matrix 2x2
  54145. for (name in source.matrices2x2) {
  54146. material.setMatrix2x2(name, source.matrices2x2[name]);
  54147. }
  54148. // Vector2Array
  54149. for (name in source.vectors2Arrays) {
  54150. material.setArray2(name, source.vectors2Arrays[name]);
  54151. }
  54152. // Vector3Array
  54153. for (name in source.vectors3Arrays) {
  54154. material.setArray3(name, source.vectors3Arrays[name]);
  54155. }
  54156. return material;
  54157. };
  54158. return ShaderMaterial;
  54159. }(BABYLON.Material));
  54160. BABYLON.ShaderMaterial = ShaderMaterial;
  54161. })(BABYLON || (BABYLON = {}));
  54162. //# sourceMappingURL=babylon.shaderMaterial.js.map
  54163. var BABYLON;
  54164. (function (BABYLON) {
  54165. var GroundMesh = /** @class */ (function (_super) {
  54166. __extends(GroundMesh, _super);
  54167. function GroundMesh(name, scene) {
  54168. var _this = _super.call(this, name, scene) || this;
  54169. _this.generateOctree = false;
  54170. return _this;
  54171. }
  54172. GroundMesh.prototype.getClassName = function () {
  54173. return "GroundMesh";
  54174. };
  54175. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  54176. get: function () {
  54177. return Math.min(this._subdivisionsX, this._subdivisionsY);
  54178. },
  54179. enumerable: true,
  54180. configurable: true
  54181. });
  54182. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  54183. get: function () {
  54184. return this._subdivisionsX;
  54185. },
  54186. enumerable: true,
  54187. configurable: true
  54188. });
  54189. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  54190. get: function () {
  54191. return this._subdivisionsY;
  54192. },
  54193. enumerable: true,
  54194. configurable: true
  54195. });
  54196. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  54197. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  54198. this._subdivisionsX = chunksCount;
  54199. this._subdivisionsY = chunksCount;
  54200. this.subdivide(chunksCount);
  54201. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  54202. };
  54203. /**
  54204. * Returns a height (y) value in the Worl system :
  54205. * the ground altitude at the coordinates (x, z) expressed in the World system.
  54206. * Returns the ground y position if (x, z) are outside the ground surface.
  54207. */
  54208. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  54209. var world = this.getWorldMatrix();
  54210. var invMat = BABYLON.Tmp.Matrix[5];
  54211. world.invertToRef(invMat);
  54212. var tmpVect = BABYLON.Tmp.Vector3[8];
  54213. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  54214. x = tmpVect.x;
  54215. z = tmpVect.z;
  54216. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54217. return this.position.y;
  54218. }
  54219. if (!this._heightQuads || this._heightQuads.length == 0) {
  54220. this._initHeightQuads();
  54221. this._computeHeightQuads();
  54222. }
  54223. var facet = this._getFacetAt(x, z);
  54224. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  54225. // return y in the World system
  54226. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  54227. return tmpVect.y;
  54228. };
  54229. /**
  54230. * Returns a normalized vector (Vector3) orthogonal to the ground
  54231. * at the ground coordinates (x, z) expressed in the World system.
  54232. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  54233. */
  54234. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  54235. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  54236. this.getNormalAtCoordinatesToRef(x, z, normal);
  54237. return normal;
  54238. };
  54239. /**
  54240. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  54241. * at the ground coordinates (x, z) expressed in the World system.
  54242. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  54243. * Returns the GroundMesh.
  54244. */
  54245. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  54246. var world = this.getWorldMatrix();
  54247. var tmpMat = BABYLON.Tmp.Matrix[5];
  54248. world.invertToRef(tmpMat);
  54249. var tmpVect = BABYLON.Tmp.Vector3[8];
  54250. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  54251. x = tmpVect.x;
  54252. z = tmpVect.z;
  54253. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  54254. return this;
  54255. }
  54256. if (!this._heightQuads || this._heightQuads.length == 0) {
  54257. this._initHeightQuads();
  54258. this._computeHeightQuads();
  54259. }
  54260. var facet = this._getFacetAt(x, z);
  54261. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  54262. return this;
  54263. };
  54264. /**
  54265. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  54266. * if the ground has been updated.
  54267. * This can be used in the render loop.
  54268. * Returns the GroundMesh.
  54269. */
  54270. GroundMesh.prototype.updateCoordinateHeights = function () {
  54271. if (!this._heightQuads || this._heightQuads.length == 0) {
  54272. this._initHeightQuads();
  54273. }
  54274. this._computeHeightQuads();
  54275. return this;
  54276. };
  54277. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  54278. GroundMesh.prototype._getFacetAt = function (x, z) {
  54279. // retrieve col and row from x, z coordinates in the ground local system
  54280. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  54281. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  54282. var quad = this._heightQuads[row * this._subdivisionsX + col];
  54283. var facet;
  54284. if (z < quad.slope.x * x + quad.slope.y) {
  54285. facet = quad.facet1;
  54286. }
  54287. else {
  54288. facet = quad.facet2;
  54289. }
  54290. return facet;
  54291. };
  54292. // Creates and populates the heightMap array with "facet" elements :
  54293. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  54294. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54295. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54296. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54297. // Returns the GroundMesh.
  54298. GroundMesh.prototype._initHeightQuads = function () {
  54299. var subdivisionsX = this._subdivisionsX;
  54300. var subdivisionsY = this._subdivisionsY;
  54301. this._heightQuads = new Array();
  54302. for (var row = 0; row < subdivisionsY; row++) {
  54303. for (var col = 0; col < subdivisionsX; col++) {
  54304. 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) };
  54305. this._heightQuads[row * subdivisionsX + col] = quad;
  54306. }
  54307. }
  54308. return this;
  54309. };
  54310. // Compute each quad element values and update the the heightMap array :
  54311. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  54312. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  54313. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  54314. // Returns the GroundMesh.
  54315. GroundMesh.prototype._computeHeightQuads = function () {
  54316. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54317. if (!positions) {
  54318. return this;
  54319. }
  54320. var v1 = BABYLON.Tmp.Vector3[3];
  54321. var v2 = BABYLON.Tmp.Vector3[2];
  54322. var v3 = BABYLON.Tmp.Vector3[1];
  54323. var v4 = BABYLON.Tmp.Vector3[0];
  54324. var v1v2 = BABYLON.Tmp.Vector3[4];
  54325. var v1v3 = BABYLON.Tmp.Vector3[5];
  54326. var v1v4 = BABYLON.Tmp.Vector3[6];
  54327. var norm1 = BABYLON.Tmp.Vector3[7];
  54328. var norm2 = BABYLON.Tmp.Vector3[8];
  54329. var i = 0;
  54330. var j = 0;
  54331. var k = 0;
  54332. var cd = 0; // 2D slope coefficient : z = cd * x + h
  54333. var h = 0;
  54334. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  54335. var d2 = 0;
  54336. var subdivisionsX = this._subdivisionsX;
  54337. var subdivisionsY = this._subdivisionsY;
  54338. for (var row = 0; row < subdivisionsY; row++) {
  54339. for (var col = 0; col < subdivisionsX; col++) {
  54340. i = col * 3;
  54341. j = row * (subdivisionsX + 1) * 3;
  54342. k = (row + 1) * (subdivisionsX + 1) * 3;
  54343. v1.x = positions[j + i];
  54344. v1.y = positions[j + i + 1];
  54345. v1.z = positions[j + i + 2];
  54346. v2.x = positions[j + i + 3];
  54347. v2.y = positions[j + i + 4];
  54348. v2.z = positions[j + i + 5];
  54349. v3.x = positions[k + i];
  54350. v3.y = positions[k + i + 1];
  54351. v3.z = positions[k + i + 2];
  54352. v4.x = positions[k + i + 3];
  54353. v4.y = positions[k + i + 4];
  54354. v4.z = positions[k + i + 5];
  54355. // 2D slope V1V4
  54356. cd = (v4.z - v1.z) / (v4.x - v1.x);
  54357. h = v1.z - cd * v1.x; // v1 belongs to the slope
  54358. // facet equations :
  54359. // we compute each facet normal vector
  54360. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  54361. // we compute the value d by applying the equation to v1 which belongs to the plane
  54362. // then we store the facet equation in a Vector4
  54363. v2.subtractToRef(v1, v1v2);
  54364. v3.subtractToRef(v1, v1v3);
  54365. v4.subtractToRef(v1, v1v4);
  54366. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  54367. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  54368. norm1.normalize();
  54369. norm2.normalize();
  54370. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  54371. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  54372. var quad = this._heightQuads[row * subdivisionsX + col];
  54373. quad.slope.copyFromFloats(cd, h);
  54374. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  54375. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  54376. }
  54377. }
  54378. return this;
  54379. };
  54380. GroundMesh.prototype.serialize = function (serializationObject) {
  54381. _super.prototype.serialize.call(this, serializationObject);
  54382. serializationObject.subdivisionsX = this._subdivisionsX;
  54383. serializationObject.subdivisionsY = this._subdivisionsY;
  54384. serializationObject.minX = this._minX;
  54385. serializationObject.maxX = this._maxX;
  54386. serializationObject.minZ = this._minZ;
  54387. serializationObject.maxZ = this._maxZ;
  54388. serializationObject.width = this._width;
  54389. serializationObject.height = this._height;
  54390. };
  54391. GroundMesh.Parse = function (parsedMesh, scene) {
  54392. var result = new GroundMesh(parsedMesh.name, scene);
  54393. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  54394. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  54395. result._minX = parsedMesh.minX;
  54396. result._maxX = parsedMesh.maxX;
  54397. result._minZ = parsedMesh.minZ;
  54398. result._maxZ = parsedMesh.maxZ;
  54399. result._width = parsedMesh.width;
  54400. result._height = parsedMesh.height;
  54401. return result;
  54402. };
  54403. return GroundMesh;
  54404. }(BABYLON.Mesh));
  54405. BABYLON.GroundMesh = GroundMesh;
  54406. })(BABYLON || (BABYLON = {}));
  54407. //# sourceMappingURL=babylon.groundMesh.js.map
  54408. var BABYLON;
  54409. (function (BABYLON) {
  54410. /**
  54411. * Creates an instance based on a source mesh.
  54412. */
  54413. var InstancedMesh = /** @class */ (function (_super) {
  54414. __extends(InstancedMesh, _super);
  54415. function InstancedMesh(name, source) {
  54416. var _this = _super.call(this, name, source.getScene()) || this;
  54417. source.instances.push(_this);
  54418. _this._sourceMesh = source;
  54419. _this.position.copyFrom(source.position);
  54420. _this.rotation.copyFrom(source.rotation);
  54421. _this.scaling.copyFrom(source.scaling);
  54422. if (source.rotationQuaternion) {
  54423. _this.rotationQuaternion = source.rotationQuaternion.clone();
  54424. }
  54425. _this.infiniteDistance = source.infiniteDistance;
  54426. _this.setPivotMatrix(source.getPivotMatrix());
  54427. _this.refreshBoundingInfo();
  54428. _this._syncSubMeshes();
  54429. return _this;
  54430. }
  54431. /**
  54432. * Returns the string "InstancedMesh".
  54433. */
  54434. InstancedMesh.prototype.getClassName = function () {
  54435. return "InstancedMesh";
  54436. };
  54437. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  54438. // Methods
  54439. get: function () {
  54440. return this._sourceMesh.receiveShadows;
  54441. },
  54442. enumerable: true,
  54443. configurable: true
  54444. });
  54445. Object.defineProperty(InstancedMesh.prototype, "material", {
  54446. get: function () {
  54447. return this._sourceMesh.material;
  54448. },
  54449. enumerable: true,
  54450. configurable: true
  54451. });
  54452. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  54453. get: function () {
  54454. return this._sourceMesh.visibility;
  54455. },
  54456. enumerable: true,
  54457. configurable: true
  54458. });
  54459. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  54460. get: function () {
  54461. return this._sourceMesh.skeleton;
  54462. },
  54463. enumerable: true,
  54464. configurable: true
  54465. });
  54466. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  54467. get: function () {
  54468. return this._sourceMesh.renderingGroupId;
  54469. },
  54470. enumerable: true,
  54471. configurable: true
  54472. });
  54473. /**
  54474. * Returns the total number of vertices (integer).
  54475. */
  54476. InstancedMesh.prototype.getTotalVertices = function () {
  54477. return this._sourceMesh.getTotalVertices();
  54478. };
  54479. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  54480. get: function () {
  54481. return this._sourceMesh;
  54482. },
  54483. enumerable: true,
  54484. configurable: true
  54485. });
  54486. /**
  54487. * Is this node ready to be used/rendered
  54488. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  54489. * @return {boolean} is it ready
  54490. */
  54491. InstancedMesh.prototype.isReady = function (completeCheck) {
  54492. if (completeCheck === void 0) { completeCheck = false; }
  54493. return this._sourceMesh.isReady(completeCheck, true);
  54494. };
  54495. /**
  54496. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  54497. */
  54498. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  54499. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  54500. };
  54501. /**
  54502. * Sets the vertex data of the mesh geometry for the requested `kind`.
  54503. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  54504. * The `data` are either a numeric array either a Float32Array.
  54505. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  54506. * 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).
  54507. * Note that a new underlying VertexBuffer object is created each call.
  54508. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  54509. *
  54510. * Possible `kind` values :
  54511. * - BABYLON.VertexBuffer.PositionKind
  54512. * - BABYLON.VertexBuffer.UVKind
  54513. * - BABYLON.VertexBuffer.UV2Kind
  54514. * - BABYLON.VertexBuffer.UV3Kind
  54515. * - BABYLON.VertexBuffer.UV4Kind
  54516. * - BABYLON.VertexBuffer.UV5Kind
  54517. * - BABYLON.VertexBuffer.UV6Kind
  54518. * - BABYLON.VertexBuffer.ColorKind
  54519. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54520. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54521. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54522. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54523. *
  54524. * Returns the Mesh.
  54525. */
  54526. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  54527. if (this.sourceMesh) {
  54528. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  54529. }
  54530. return this.sourceMesh;
  54531. };
  54532. /**
  54533. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  54534. * If the mesh has no geometry, it is simply returned as it is.
  54535. * The `data` are either a numeric array either a Float32Array.
  54536. * No new underlying VertexBuffer object is created.
  54537. * 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.
  54538. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  54539. *
  54540. * Possible `kind` values :
  54541. * - BABYLON.VertexBuffer.PositionKind
  54542. * - BABYLON.VertexBuffer.UVKind
  54543. * - BABYLON.VertexBuffer.UV2Kind
  54544. * - BABYLON.VertexBuffer.UV3Kind
  54545. * - BABYLON.VertexBuffer.UV4Kind
  54546. * - BABYLON.VertexBuffer.UV5Kind
  54547. * - BABYLON.VertexBuffer.UV6Kind
  54548. * - BABYLON.VertexBuffer.ColorKind
  54549. * - BABYLON.VertexBuffer.MatricesIndicesKind
  54550. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  54551. * - BABYLON.VertexBuffer.MatricesWeightsKind
  54552. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  54553. *
  54554. * Returns the Mesh.
  54555. */
  54556. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  54557. if (this.sourceMesh) {
  54558. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  54559. }
  54560. return this.sourceMesh;
  54561. };
  54562. /**
  54563. * Sets the mesh indices.
  54564. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  54565. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  54566. * This method creates a new index buffer each call.
  54567. * Returns the Mesh.
  54568. */
  54569. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  54570. if (totalVertices === void 0) { totalVertices = null; }
  54571. if (this.sourceMesh) {
  54572. this.sourceMesh.setIndices(indices, totalVertices);
  54573. }
  54574. return this.sourceMesh;
  54575. };
  54576. /**
  54577. * Boolean : True if the mesh owns the requested kind of data.
  54578. */
  54579. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  54580. return this._sourceMesh.isVerticesDataPresent(kind);
  54581. };
  54582. /**
  54583. * Returns an array of indices (IndicesArray).
  54584. */
  54585. InstancedMesh.prototype.getIndices = function () {
  54586. return this._sourceMesh.getIndices();
  54587. };
  54588. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  54589. get: function () {
  54590. return this._sourceMesh._positions;
  54591. },
  54592. enumerable: true,
  54593. configurable: true
  54594. });
  54595. /**
  54596. * Sets a new updated BoundingInfo to the mesh.
  54597. * Returns the mesh.
  54598. */
  54599. InstancedMesh.prototype.refreshBoundingInfo = function () {
  54600. var meshBB = this._sourceMesh.getBoundingInfo();
  54601. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  54602. this._updateBoundingInfo();
  54603. return this;
  54604. };
  54605. InstancedMesh.prototype._preActivate = function () {
  54606. if (this._currentLOD) {
  54607. this._currentLOD._preActivate();
  54608. }
  54609. return this;
  54610. };
  54611. InstancedMesh.prototype._activate = function (renderId) {
  54612. if (this._currentLOD) {
  54613. this._currentLOD._registerInstanceForRenderId(this, renderId);
  54614. }
  54615. return this;
  54616. };
  54617. /**
  54618. * Returns the current associated LOD AbstractMesh.
  54619. */
  54620. InstancedMesh.prototype.getLOD = function (camera) {
  54621. if (!camera) {
  54622. return this;
  54623. }
  54624. var boundingInfo = this.getBoundingInfo();
  54625. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  54626. if (this._currentLOD === this.sourceMesh) {
  54627. return this;
  54628. }
  54629. return this._currentLOD;
  54630. };
  54631. InstancedMesh.prototype._syncSubMeshes = function () {
  54632. this.releaseSubMeshes();
  54633. if (this._sourceMesh.subMeshes) {
  54634. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  54635. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  54636. }
  54637. }
  54638. return this;
  54639. };
  54640. InstancedMesh.prototype._generatePointsArray = function () {
  54641. return this._sourceMesh._generatePointsArray();
  54642. };
  54643. /**
  54644. * Creates a new InstancedMesh from the current mesh.
  54645. * - name (string) : the cloned mesh name
  54646. * - newParent (optional Node) : the optional Node to parent the clone to.
  54647. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  54648. *
  54649. * Returns the clone.
  54650. */
  54651. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54652. var result = this._sourceMesh.createInstance(name);
  54653. // Deep copy
  54654. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  54655. // Bounding info
  54656. this.refreshBoundingInfo();
  54657. // Parent
  54658. if (newParent) {
  54659. result.parent = newParent;
  54660. }
  54661. if (!doNotCloneChildren) {
  54662. // Children
  54663. for (var index = 0; index < this.getScene().meshes.length; index++) {
  54664. var mesh = this.getScene().meshes[index];
  54665. if (mesh.parent === this) {
  54666. mesh.clone(mesh.name, result);
  54667. }
  54668. }
  54669. }
  54670. result.computeWorldMatrix(true);
  54671. return result;
  54672. };
  54673. /**
  54674. * Disposes the InstancedMesh.
  54675. * Returns nothing.
  54676. */
  54677. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  54678. // Remove from mesh
  54679. var index = this._sourceMesh.instances.indexOf(this);
  54680. this._sourceMesh.instances.splice(index, 1);
  54681. _super.prototype.dispose.call(this, doNotRecurse);
  54682. };
  54683. return InstancedMesh;
  54684. }(BABYLON.AbstractMesh));
  54685. BABYLON.InstancedMesh = InstancedMesh;
  54686. })(BABYLON || (BABYLON = {}));
  54687. //# sourceMappingURL=babylon.instancedMesh.js.map
  54688. var BABYLON;
  54689. (function (BABYLON) {
  54690. var LinesMesh = /** @class */ (function (_super) {
  54691. __extends(LinesMesh, _super);
  54692. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  54693. if (scene === void 0) { scene = null; }
  54694. if (parent === void 0) { parent = null; }
  54695. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  54696. _this.useVertexColor = useVertexColor;
  54697. _this.useVertexAlpha = useVertexAlpha;
  54698. _this.color = new BABYLON.Color3(1, 1, 1);
  54699. _this.alpha = 1;
  54700. if (source) {
  54701. _this.color = source.color.clone();
  54702. _this.alpha = source.alpha;
  54703. _this.useVertexColor = source.useVertexColor;
  54704. _this.useVertexAlpha = source.useVertexAlpha;
  54705. }
  54706. _this._intersectionThreshold = 0.1;
  54707. var defines = [];
  54708. var options = {
  54709. attributes: [BABYLON.VertexBuffer.PositionKind],
  54710. uniforms: ["world", "viewProjection"],
  54711. needAlphaBlending: true,
  54712. defines: defines
  54713. };
  54714. if (useVertexAlpha === false) {
  54715. options.needAlphaBlending = false;
  54716. }
  54717. if (!useVertexColor) {
  54718. options.uniforms.push("color");
  54719. }
  54720. else {
  54721. options.defines.push("#define VERTEXCOLOR");
  54722. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  54723. }
  54724. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  54725. return _this;
  54726. }
  54727. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  54728. /**
  54729. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54730. * This margin is expressed in world space coordinates, so its value may vary.
  54731. * Default value is 0.1
  54732. * @returns the intersection Threshold value.
  54733. */
  54734. get: function () {
  54735. return this._intersectionThreshold;
  54736. },
  54737. /**
  54738. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  54739. * This margin is expressed in world space coordinates, so its value may vary.
  54740. * @param value the new threshold to apply
  54741. */
  54742. set: function (value) {
  54743. if (this._intersectionThreshold === value) {
  54744. return;
  54745. }
  54746. this._intersectionThreshold = value;
  54747. if (this.geometry) {
  54748. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  54749. }
  54750. },
  54751. enumerable: true,
  54752. configurable: true
  54753. });
  54754. /**
  54755. * Returns the string "LineMesh"
  54756. */
  54757. LinesMesh.prototype.getClassName = function () {
  54758. return "LinesMesh";
  54759. };
  54760. Object.defineProperty(LinesMesh.prototype, "material", {
  54761. get: function () {
  54762. return this._colorShader;
  54763. },
  54764. set: function (value) {
  54765. // Do nothing
  54766. },
  54767. enumerable: true,
  54768. configurable: true
  54769. });
  54770. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  54771. get: function () {
  54772. return false;
  54773. },
  54774. enumerable: true,
  54775. configurable: true
  54776. });
  54777. LinesMesh.prototype.createInstance = function (name) {
  54778. throw new Error("LinesMeshes do not support createInstance.");
  54779. };
  54780. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  54781. if (!this._geometry) {
  54782. return this;
  54783. }
  54784. // VBOs
  54785. this._geometry._bind(this._colorShader.getEffect());
  54786. // Color
  54787. if (!this.useVertexColor) {
  54788. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  54789. }
  54790. return this;
  54791. };
  54792. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  54793. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  54794. return this;
  54795. }
  54796. var engine = this.getScene().getEngine();
  54797. // Draw order
  54798. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  54799. return this;
  54800. };
  54801. LinesMesh.prototype.dispose = function (doNotRecurse) {
  54802. this._colorShader.dispose();
  54803. _super.prototype.dispose.call(this, doNotRecurse);
  54804. };
  54805. /**
  54806. * Returns a new LineMesh object cloned from the current one.
  54807. */
  54808. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  54809. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  54810. };
  54811. return LinesMesh;
  54812. }(BABYLON.Mesh));
  54813. BABYLON.LinesMesh = LinesMesh;
  54814. })(BABYLON || (BABYLON = {}));
  54815. //# sourceMappingURL=babylon.linesMesh.js.map
  54816. var BABYLON;
  54817. (function (BABYLON) {
  54818. var MeshBuilder = /** @class */ (function () {
  54819. function MeshBuilder() {
  54820. }
  54821. MeshBuilder.updateSideOrientation = function (orientation) {
  54822. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  54823. return BABYLON.Mesh.DOUBLESIDE;
  54824. }
  54825. if (orientation === undefined || orientation === null) {
  54826. return BABYLON.Mesh.FRONTSIDE;
  54827. }
  54828. return orientation;
  54829. };
  54830. /**
  54831. * Creates a box mesh.
  54832. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  54833. * The parameter `size` sets the size (float) of each box side (default 1).
  54834. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  54835. * 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).
  54836. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  54837. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54838. * 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).
  54839. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54840. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54841. */
  54842. MeshBuilder.CreateBox = function (name, options, scene) {
  54843. if (scene === void 0) { scene = null; }
  54844. var box = new BABYLON.Mesh(name, scene);
  54845. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54846. box._originalBuilderSideOrientation = options.sideOrientation;
  54847. var vertexData = BABYLON.VertexData.CreateBox(options);
  54848. vertexData.applyToMesh(box, options.updatable);
  54849. return box;
  54850. };
  54851. /**
  54852. * Creates a sphere mesh.
  54853. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  54854. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  54855. * 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`).
  54856. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  54857. * 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
  54858. * 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).
  54859. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54860. * 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).
  54861. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54862. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54863. */
  54864. MeshBuilder.CreateSphere = function (name, options, scene) {
  54865. var sphere = new BABYLON.Mesh(name, scene);
  54866. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54867. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54868. var vertexData = BABYLON.VertexData.CreateSphere(options);
  54869. vertexData.applyToMesh(sphere, options.updatable);
  54870. return sphere;
  54871. };
  54872. /**
  54873. * Creates a plane polygonal mesh. By default, this is a disc.
  54874. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  54875. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  54876. * 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.
  54877. * 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
  54878. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54879. * 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).
  54880. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54881. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54882. */
  54883. MeshBuilder.CreateDisc = function (name, options, scene) {
  54884. if (scene === void 0) { scene = null; }
  54885. var disc = new BABYLON.Mesh(name, scene);
  54886. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54887. disc._originalBuilderSideOrientation = options.sideOrientation;
  54888. var vertexData = BABYLON.VertexData.CreateDisc(options);
  54889. vertexData.applyToMesh(disc, options.updatable);
  54890. return disc;
  54891. };
  54892. /**
  54893. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  54894. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  54895. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  54896. * 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`).
  54897. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  54898. * 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.
  54899. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54900. * 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).
  54901. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54902. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54903. */
  54904. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  54905. var sphere = new BABYLON.Mesh(name, scene);
  54906. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54907. sphere._originalBuilderSideOrientation = options.sideOrientation;
  54908. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  54909. vertexData.applyToMesh(sphere, options.updatable);
  54910. return sphere;
  54911. };
  54912. ;
  54913. /**
  54914. * Creates a ribbon mesh.
  54915. * 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.
  54916. *
  54917. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  54918. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  54919. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  54920. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  54921. * 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.
  54922. * 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.
  54923. * 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
  54924. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  54925. * 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).
  54926. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  54927. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  54928. * 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.
  54929. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  54930. * 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
  54931. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  54932. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  54933. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  54934. */
  54935. MeshBuilder.CreateRibbon = function (name, options, scene) {
  54936. if (scene === void 0) { scene = null; }
  54937. var pathArray = options.pathArray;
  54938. var closeArray = options.closeArray;
  54939. var closePath = options.closePath;
  54940. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  54941. var instance = options.instance;
  54942. var updatable = options.updatable;
  54943. if (instance) {
  54944. // positionFunction : ribbon case
  54945. // only pathArray and sideOrientation parameters are taken into account for positions update
  54946. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  54947. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  54948. var positionFunction = function (positions) {
  54949. var minlg = pathArray[0].length;
  54950. var i = 0;
  54951. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  54952. for (var si = 1; si <= ns; si++) {
  54953. for (var p = 0; p < pathArray.length; p++) {
  54954. var path = pathArray[p];
  54955. var l = path.length;
  54956. minlg = (minlg < l) ? minlg : l;
  54957. var j = 0;
  54958. while (j < minlg) {
  54959. positions[i] = path[j].x;
  54960. positions[i + 1] = path[j].y;
  54961. positions[i + 2] = path[j].z;
  54962. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  54963. BABYLON.Tmp.Vector3[0].x = path[j].x;
  54964. }
  54965. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  54966. BABYLON.Tmp.Vector3[1].x = path[j].x;
  54967. }
  54968. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  54969. BABYLON.Tmp.Vector3[0].y = path[j].y;
  54970. }
  54971. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  54972. BABYLON.Tmp.Vector3[1].y = path[j].y;
  54973. }
  54974. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  54975. BABYLON.Tmp.Vector3[0].z = path[j].z;
  54976. }
  54977. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  54978. BABYLON.Tmp.Vector3[1].z = path[j].z;
  54979. }
  54980. j++;
  54981. i += 3;
  54982. }
  54983. if (instance._closePath) {
  54984. positions[i] = path[0].x;
  54985. positions[i + 1] = path[0].y;
  54986. positions[i + 2] = path[0].z;
  54987. i += 3;
  54988. }
  54989. }
  54990. }
  54991. };
  54992. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54993. positionFunction(positions);
  54994. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  54995. instance._boundingInfo.update(instance._worldMatrix);
  54996. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  54997. if (options.colors) {
  54998. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54999. for (var c = 0; c < options.colors.length; c++) {
  55000. colors[c * 4] = options.colors[c].r;
  55001. colors[c * 4 + 1] = options.colors[c].g;
  55002. colors[c * 4 + 2] = options.colors[c].b;
  55003. colors[c * 4 + 3] = options.colors[c].a;
  55004. }
  55005. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  55006. }
  55007. if (options.uvs) {
  55008. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  55009. for (var i = 0; i < options.uvs.length; i++) {
  55010. uvs[i * 2] = options.uvs[i].x;
  55011. uvs[i * 2 + 1] = options.uvs[i].y;
  55012. }
  55013. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  55014. }
  55015. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  55016. var indices = instance.getIndices();
  55017. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55018. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  55019. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  55020. if (instance._closePath) {
  55021. var indexFirst = 0;
  55022. var indexLast = 0;
  55023. for (var p = 0; p < pathArray.length; p++) {
  55024. indexFirst = instance._idx[p] * 3;
  55025. if (p + 1 < pathArray.length) {
  55026. indexLast = (instance._idx[p + 1] - 1) * 3;
  55027. }
  55028. else {
  55029. indexLast = normals.length - 3;
  55030. }
  55031. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  55032. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  55033. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  55034. normals[indexLast] = normals[indexFirst];
  55035. normals[indexLast + 1] = normals[indexFirst + 1];
  55036. normals[indexLast + 2] = normals[indexFirst + 2];
  55037. }
  55038. }
  55039. if (!(instance.areNormalsFrozen)) {
  55040. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  55041. }
  55042. }
  55043. return instance;
  55044. }
  55045. else {
  55046. var ribbon = new BABYLON.Mesh(name, scene);
  55047. ribbon._originalBuilderSideOrientation = sideOrientation;
  55048. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  55049. if (closePath) {
  55050. ribbon._idx = vertexData._idx;
  55051. }
  55052. ribbon._closePath = closePath;
  55053. ribbon._closeArray = closeArray;
  55054. vertexData.applyToMesh(ribbon, updatable);
  55055. return ribbon;
  55056. }
  55057. };
  55058. /**
  55059. * Creates a cylinder or a cone mesh.
  55060. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  55061. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  55062. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  55063. * 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.
  55064. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  55065. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  55066. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  55067. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  55068. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  55069. * 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).
  55070. * 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
  55071. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  55072. * 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
  55073. * 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.
  55074. * If `enclose` is false, a ring surface is one element.
  55075. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  55076. * 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
  55077. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55078. * 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).
  55079. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55080. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55081. */
  55082. MeshBuilder.CreateCylinder = function (name, options, scene) {
  55083. var cylinder = new BABYLON.Mesh(name, scene);
  55084. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55085. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  55086. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  55087. vertexData.applyToMesh(cylinder, options.updatable);
  55088. return cylinder;
  55089. };
  55090. /**
  55091. * Creates a torus mesh.
  55092. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  55093. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  55094. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  55095. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  55096. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55097. * 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).
  55098. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55099. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55100. */
  55101. MeshBuilder.CreateTorus = function (name, options, scene) {
  55102. var torus = new BABYLON.Mesh(name, scene);
  55103. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55104. torus._originalBuilderSideOrientation = options.sideOrientation;
  55105. var vertexData = BABYLON.VertexData.CreateTorus(options);
  55106. vertexData.applyToMesh(torus, options.updatable);
  55107. return torus;
  55108. };
  55109. /**
  55110. * Creates a torus knot mesh.
  55111. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  55112. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  55113. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  55114. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  55115. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  55116. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55117. * 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).
  55118. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55119. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55120. */
  55121. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  55122. var torusKnot = new BABYLON.Mesh(name, scene);
  55123. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55124. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  55125. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  55126. vertexData.applyToMesh(torusKnot, options.updatable);
  55127. return torusKnot;
  55128. };
  55129. /**
  55130. * Creates a line system mesh.
  55131. * A line system is a pool of many lines gathered in a single mesh.
  55132. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  55133. * 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.
  55134. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  55135. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  55136. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  55137. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  55138. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  55139. * 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
  55140. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  55141. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55142. */
  55143. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  55144. var instance = options.instance;
  55145. var lines = options.lines;
  55146. var colors = options.colors;
  55147. if (instance) {
  55148. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55149. var vertexColor;
  55150. var lineColors;
  55151. if (colors) {
  55152. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  55153. }
  55154. var i = 0;
  55155. var c = 0;
  55156. for (var l = 0; l < lines.length; l++) {
  55157. var points = lines[l];
  55158. for (var p = 0; p < points.length; p++) {
  55159. positions[i] = points[p].x;
  55160. positions[i + 1] = points[p].y;
  55161. positions[i + 2] = points[p].z;
  55162. if (colors && vertexColor) {
  55163. lineColors = colors[l];
  55164. vertexColor[c] = lineColors[p].r;
  55165. vertexColor[c + 1] = lineColors[p].g;
  55166. vertexColor[c + 2] = lineColors[p].b;
  55167. vertexColor[c + 3] = lineColors[p].a;
  55168. c += 4;
  55169. }
  55170. i += 3;
  55171. }
  55172. }
  55173. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  55174. if (colors && vertexColor) {
  55175. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  55176. }
  55177. return instance;
  55178. }
  55179. // line system creation
  55180. var useVertexColor = (colors) ? true : false;
  55181. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  55182. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  55183. vertexData.applyToMesh(lineSystem, options.updatable);
  55184. return lineSystem;
  55185. };
  55186. /**
  55187. * Creates a line mesh.
  55188. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  55189. * 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.
  55190. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55191. * The parameter `points` is an array successive Vector3.
  55192. * 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
  55193. * The optional parameter `colors` is an array of successive Color4, one per line point.
  55194. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  55195. * When updating an instance, remember that only point positions can change, not the number of points.
  55196. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55197. */
  55198. MeshBuilder.CreateLines = function (name, options, scene) {
  55199. if (scene === void 0) { scene = null; }
  55200. var colors = (options.colors) ? [options.colors] : null;
  55201. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  55202. return lines;
  55203. };
  55204. /**
  55205. * Creates a dashed line mesh.
  55206. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  55207. * 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.
  55208. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  55209. * The parameter `points` is an array successive Vector3.
  55210. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  55211. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  55212. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  55213. * 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
  55214. * When updating an instance, remember that only point positions can change, not the number of points.
  55215. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55216. */
  55217. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  55218. if (scene === void 0) { scene = null; }
  55219. var points = options.points;
  55220. var instance = options.instance;
  55221. var gapSize = options.gapSize || 1;
  55222. var dashSize = options.dashSize || 3;
  55223. if (instance) {
  55224. var positionFunction = function (positions) {
  55225. var curvect = BABYLON.Vector3.Zero();
  55226. var nbSeg = positions.length / 6;
  55227. var lg = 0;
  55228. var nb = 0;
  55229. var shft = 0;
  55230. var dashshft = 0;
  55231. var curshft = 0;
  55232. var p = 0;
  55233. var i = 0;
  55234. var j = 0;
  55235. for (i = 0; i < points.length - 1; i++) {
  55236. points[i + 1].subtractToRef(points[i], curvect);
  55237. lg += curvect.length();
  55238. }
  55239. shft = lg / nbSeg;
  55240. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  55241. for (i = 0; i < points.length - 1; i++) {
  55242. points[i + 1].subtractToRef(points[i], curvect);
  55243. nb = Math.floor(curvect.length() / shft);
  55244. curvect.normalize();
  55245. j = 0;
  55246. while (j < nb && p < positions.length) {
  55247. curshft = shft * j;
  55248. positions[p] = points[i].x + curshft * curvect.x;
  55249. positions[p + 1] = points[i].y + curshft * curvect.y;
  55250. positions[p + 2] = points[i].z + curshft * curvect.z;
  55251. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  55252. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  55253. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  55254. p += 6;
  55255. j++;
  55256. }
  55257. }
  55258. while (p < positions.length) {
  55259. positions[p] = points[i].x;
  55260. positions[p + 1] = points[i].y;
  55261. positions[p + 2] = points[i].z;
  55262. p += 3;
  55263. }
  55264. };
  55265. instance.updateMeshPositions(positionFunction, false);
  55266. return instance;
  55267. }
  55268. // dashed lines creation
  55269. var dashedLines = new BABYLON.LinesMesh(name, scene);
  55270. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  55271. vertexData.applyToMesh(dashedLines, options.updatable);
  55272. dashedLines.dashSize = dashSize;
  55273. dashedLines.gapSize = gapSize;
  55274. return dashedLines;
  55275. };
  55276. /**
  55277. * Creates an extruded shape mesh.
  55278. * 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.
  55279. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  55280. *
  55281. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55282. * 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
  55283. * extruded along the Z axis.
  55284. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55285. * 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.
  55286. * The parameter `scale` (float, default 1) is the value to scale the shape.
  55287. * 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
  55288. * 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
  55289. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55290. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55291. * 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).
  55292. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55293. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55294. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55295. */
  55296. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  55297. if (scene === void 0) { scene = null; }
  55298. var path = options.path;
  55299. var shape = options.shape;
  55300. var scale = options.scale || 1;
  55301. var rotation = options.rotation || 0;
  55302. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55303. var updatable = options.updatable;
  55304. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55305. var instance = options.instance || null;
  55306. var invertUV = options.invertUV || false;
  55307. 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);
  55308. };
  55309. /**
  55310. * Creates an custom extruded shape mesh.
  55311. * 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.
  55312. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  55313. *
  55314. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  55315. * 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
  55316. * extruded along the Z axis.
  55317. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  55318. * 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
  55319. * and the distance of this point from the begining of the path :
  55320. * ```javascript
  55321. * var rotationFunction = function(i, distance) {
  55322. * // do things
  55323. * return rotationValue; }
  55324. * ```
  55325. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  55326. * 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
  55327. * and the distance of this point from the begining of the path :
  55328. * ```javascript
  55329. * var scaleFunction = function(i, distance) {
  55330. * // do things
  55331. * return scaleValue;}
  55332. * ```
  55333. * It must returns a float value that will be the scale value applied to the shape on each path point.
  55334. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  55335. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  55336. * 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
  55337. * 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
  55338. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  55339. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55340. * 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).
  55341. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55342. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55343. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55344. */
  55345. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  55346. var path = options.path;
  55347. var shape = options.shape;
  55348. var scaleFunction = options.scaleFunction || (function () { return 1; });
  55349. var rotationFunction = options.rotationFunction || (function () { return 0; });
  55350. var ribbonCloseArray = options.ribbonCloseArray || false;
  55351. var ribbonClosePath = options.ribbonClosePath || false;
  55352. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  55353. var updatable = options.updatable;
  55354. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55355. var instance = options.instance;
  55356. var invertUV = options.invertUV || false;
  55357. 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);
  55358. };
  55359. /**
  55360. * Creates lathe mesh.
  55361. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  55362. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  55363. *
  55364. * 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
  55365. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  55366. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  55367. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  55368. * 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.
  55369. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  55370. * 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
  55371. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55372. * 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).
  55373. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55374. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55375. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55376. */
  55377. MeshBuilder.CreateLathe = function (name, options, scene) {
  55378. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  55379. var closed = (options.closed === undefined) ? true : options.closed;
  55380. var shape = options.shape;
  55381. var radius = options.radius || 1;
  55382. var tessellation = options.tessellation || 64;
  55383. var updatable = options.updatable;
  55384. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55385. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55386. var pi2 = Math.PI * 2;
  55387. var paths = new Array();
  55388. var invertUV = options.invertUV || false;
  55389. var i = 0;
  55390. var p = 0;
  55391. var step = pi2 / tessellation * arc;
  55392. var rotated;
  55393. var path = new Array();
  55394. ;
  55395. for (i = 0; i <= tessellation; i++) {
  55396. var path = [];
  55397. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  55398. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  55399. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  55400. }
  55401. for (p = 0; p < shape.length; p++) {
  55402. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  55403. path.push(rotated);
  55404. }
  55405. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  55406. 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));
  55407. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  55408. }
  55409. paths.push(path);
  55410. }
  55411. // lathe ribbon
  55412. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55413. return lathe;
  55414. };
  55415. /**
  55416. * Creates a plane mesh.
  55417. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55418. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  55419. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  55420. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  55421. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55422. * 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).
  55423. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55424. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55425. */
  55426. MeshBuilder.CreatePlane = function (name, options, scene) {
  55427. var plane = new BABYLON.Mesh(name, scene);
  55428. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55429. plane._originalBuilderSideOrientation = options.sideOrientation;
  55430. var vertexData = BABYLON.VertexData.CreatePlane(options);
  55431. vertexData.applyToMesh(plane, options.updatable);
  55432. if (options.sourcePlane) {
  55433. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  55434. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  55435. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  55436. plane.rotate(vectorProduct, product);
  55437. }
  55438. return plane;
  55439. };
  55440. /**
  55441. * Creates a ground mesh.
  55442. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  55443. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  55444. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  55445. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55446. */
  55447. MeshBuilder.CreateGround = function (name, options, scene) {
  55448. var ground = new BABYLON.GroundMesh(name, scene);
  55449. ground._setReady(false);
  55450. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  55451. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  55452. ground._width = options.width || 1;
  55453. ground._height = options.height || 1;
  55454. ground._maxX = ground._width / 2;
  55455. ground._maxZ = ground._height / 2;
  55456. ground._minX = -ground._maxX;
  55457. ground._minZ = -ground._maxZ;
  55458. var vertexData = BABYLON.VertexData.CreateGround(options);
  55459. vertexData.applyToMesh(ground, options.updatable);
  55460. ground._setReady(true);
  55461. return ground;
  55462. };
  55463. /**
  55464. * Creates a tiled ground mesh.
  55465. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  55466. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  55467. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  55468. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  55469. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  55470. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  55471. * numbers of subdivisions on the ground width and height of each tile.
  55472. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55473. */
  55474. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  55475. var tiledGround = new BABYLON.Mesh(name, scene);
  55476. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  55477. vertexData.applyToMesh(tiledGround, options.updatable);
  55478. return tiledGround;
  55479. };
  55480. /**
  55481. * Creates a ground mesh from a height map.
  55482. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  55483. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  55484. * The parameter `url` sets the URL of the height map image resource.
  55485. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  55486. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  55487. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  55488. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  55489. * 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.
  55490. * 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).
  55491. * This function is passed the newly built mesh :
  55492. * ```javascript
  55493. * function(mesh) { // do things
  55494. * return; }
  55495. * ```
  55496. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55497. */
  55498. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  55499. var width = options.width || 10.0;
  55500. var height = options.height || 10.0;
  55501. var subdivisions = options.subdivisions || 1 | 0;
  55502. var minHeight = options.minHeight || 0.0;
  55503. var maxHeight = options.maxHeight || 1.0;
  55504. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  55505. var updatable = options.updatable;
  55506. var onReady = options.onReady;
  55507. var ground = new BABYLON.GroundMesh(name, scene);
  55508. ground._subdivisionsX = subdivisions;
  55509. ground._subdivisionsY = subdivisions;
  55510. ground._width = width;
  55511. ground._height = height;
  55512. ground._maxX = ground._width / 2.0;
  55513. ground._maxZ = ground._height / 2.0;
  55514. ground._minX = -ground._maxX;
  55515. ground._minZ = -ground._maxZ;
  55516. ground._setReady(false);
  55517. var onload = function (img) {
  55518. // Getting height map data
  55519. var canvas = document.createElement("canvas");
  55520. var context = canvas.getContext("2d");
  55521. if (!context) {
  55522. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  55523. }
  55524. if (scene.isDisposed) {
  55525. return;
  55526. }
  55527. var bufferWidth = img.width;
  55528. var bufferHeight = img.height;
  55529. canvas.width = bufferWidth;
  55530. canvas.height = bufferHeight;
  55531. context.drawImage(img, 0, 0);
  55532. // Create VertexData from map data
  55533. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  55534. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  55535. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  55536. width: width, height: height,
  55537. subdivisions: subdivisions,
  55538. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  55539. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  55540. });
  55541. vertexData.applyToMesh(ground, updatable);
  55542. ground._setReady(true);
  55543. //execute ready callback, if set
  55544. if (onReady) {
  55545. onReady(ground);
  55546. }
  55547. };
  55548. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  55549. return ground;
  55550. };
  55551. /**
  55552. * Creates a polygon mesh.
  55553. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  55554. * 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.
  55555. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55556. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55557. * 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).
  55558. * Remember you can only change the shape positions, not their number when updating a polygon.
  55559. */
  55560. MeshBuilder.CreatePolygon = function (name, options, scene) {
  55561. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55562. var shape = options.shape;
  55563. var holes = options.holes || [];
  55564. var depth = options.depth || 0;
  55565. var contours = [];
  55566. var hole = [];
  55567. for (var i = 0; i < shape.length; i++) {
  55568. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  55569. }
  55570. var epsilon = 0.00000001;
  55571. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  55572. contours.pop();
  55573. }
  55574. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  55575. for (var hNb = 0; hNb < holes.length; hNb++) {
  55576. hole = [];
  55577. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  55578. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  55579. }
  55580. polygonTriangulation.addHole(hole);
  55581. }
  55582. var polygon = polygonTriangulation.build(options.updatable, depth);
  55583. polygon._originalBuilderSideOrientation = options.sideOrientation;
  55584. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  55585. vertexData.applyToMesh(polygon, options.updatable);
  55586. return polygon;
  55587. };
  55588. ;
  55589. /**
  55590. * Creates an extruded polygon mesh, with depth in the Y direction.
  55591. * 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).
  55592. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  55593. */
  55594. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  55595. return MeshBuilder.CreatePolygon(name, options, scene);
  55596. };
  55597. ;
  55598. /**
  55599. * Creates a tube mesh.
  55600. * 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.
  55601. *
  55602. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  55603. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  55604. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  55605. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  55606. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  55607. * 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.
  55608. * It must return a radius value (positive float) :
  55609. * ```javascript
  55610. * var radiusFunction = function(i, distance) {
  55611. * // do things
  55612. * return radius; }
  55613. * ```
  55614. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  55615. * 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
  55616. * 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
  55617. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55618. * 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).
  55619. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55620. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  55621. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55622. */
  55623. MeshBuilder.CreateTube = function (name, options, scene) {
  55624. var path = options.path;
  55625. var instance = options.instance;
  55626. var radius = 1.0;
  55627. if (instance) {
  55628. radius = instance.radius;
  55629. }
  55630. if (options.radius !== undefined) {
  55631. radius = options.radius;
  55632. }
  55633. ;
  55634. var tessellation = options.tessellation || 64 | 0;
  55635. var radiusFunction = options.radiusFunction || null;
  55636. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  55637. var invertUV = options.invertUV || false;
  55638. var updatable = options.updatable;
  55639. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55640. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  55641. // tube geometry
  55642. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  55643. var tangents = path3D.getTangents();
  55644. var normals = path3D.getNormals();
  55645. var distances = path3D.getDistances();
  55646. var pi2 = Math.PI * 2;
  55647. var step = pi2 / tessellation * arc;
  55648. var returnRadius = function () { return radius; };
  55649. var radiusFunctionFinal = radiusFunction || returnRadius;
  55650. var circlePath;
  55651. var rad;
  55652. var normal;
  55653. var rotated;
  55654. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55655. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55656. for (var i = 0; i < path.length; i++) {
  55657. rad = radiusFunctionFinal(i, distances[i]); // current radius
  55658. circlePath = Array(); // current circle array
  55659. normal = normals[i]; // current normal
  55660. for (var t = 0; t < tessellation; t++) {
  55661. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  55662. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  55663. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  55664. rotated.scaleInPlace(rad).addInPlace(path[i]);
  55665. circlePath[t] = rotated;
  55666. }
  55667. circlePaths[index] = circlePath;
  55668. index++;
  55669. }
  55670. // cap
  55671. var capPath = function (nbPoints, pathIndex) {
  55672. var pointCap = Array();
  55673. for (var i = 0; i < nbPoints; i++) {
  55674. pointCap.push(path[pathIndex]);
  55675. }
  55676. return pointCap;
  55677. };
  55678. switch (cap) {
  55679. case BABYLON.Mesh.NO_CAP:
  55680. break;
  55681. case BABYLON.Mesh.CAP_START:
  55682. circlePaths[0] = capPath(tessellation, 0);
  55683. circlePaths[1] = circlePaths[2].slice(0);
  55684. break;
  55685. case BABYLON.Mesh.CAP_END:
  55686. circlePaths[index] = circlePaths[index - 1].slice(0);
  55687. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55688. break;
  55689. case BABYLON.Mesh.CAP_ALL:
  55690. circlePaths[0] = capPath(tessellation, 0);
  55691. circlePaths[1] = circlePaths[2].slice(0);
  55692. circlePaths[index] = circlePaths[index - 1].slice(0);
  55693. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  55694. break;
  55695. default:
  55696. break;
  55697. }
  55698. return circlePaths;
  55699. };
  55700. var path3D;
  55701. var pathArray;
  55702. if (instance) {
  55703. var arc = options.arc || instance.arc;
  55704. path3D = (instance.path3D).update(path);
  55705. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  55706. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  55707. instance.path3D = path3D;
  55708. instance.pathArray = pathArray;
  55709. instance.arc = arc;
  55710. instance.radius = radius;
  55711. return instance;
  55712. }
  55713. // tube creation
  55714. path3D = new BABYLON.Path3D(path);
  55715. var newPathArray = new Array();
  55716. cap = (cap < 0 || cap > 3) ? 0 : cap;
  55717. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  55718. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  55719. tube.pathArray = pathArray;
  55720. tube.path3D = path3D;
  55721. tube.tessellation = tessellation;
  55722. tube.cap = cap;
  55723. tube.arc = options.arc;
  55724. tube.radius = radius;
  55725. return tube;
  55726. };
  55727. /**
  55728. * Creates a polyhedron mesh.
  55729. *
  55730. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  55731. * 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
  55732. * to choose the wanted type.
  55733. * The parameter `size` (positive float, default 1) sets the polygon size.
  55734. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  55735. * 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`.
  55736. * 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
  55737. * 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)`).
  55738. * 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
  55739. * 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.
  55740. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  55741. * 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).
  55742. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  55743. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  55744. */
  55745. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  55746. var polyhedron = new BABYLON.Mesh(name, scene);
  55747. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  55748. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  55749. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  55750. vertexData.applyToMesh(polyhedron, options.updatable);
  55751. return polyhedron;
  55752. };
  55753. /**
  55754. * Creates a decal mesh.
  55755. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  55756. * 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.
  55757. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  55758. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  55759. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  55760. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  55761. */
  55762. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  55763. var indices = sourceMesh.getIndices();
  55764. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55765. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  55766. var position = options.position || BABYLON.Vector3.Zero();
  55767. var normal = options.normal || BABYLON.Vector3.Up();
  55768. var size = options.size || BABYLON.Vector3.One();
  55769. var angle = options.angle || 0;
  55770. // Getting correct rotation
  55771. if (!normal) {
  55772. var target = new BABYLON.Vector3(0, 0, 1);
  55773. var camera = sourceMesh.getScene().activeCamera;
  55774. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  55775. normal = camera.globalPosition.subtract(cameraWorldTarget);
  55776. }
  55777. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  55778. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  55779. var pitch = Math.atan2(normal.y, len);
  55780. // Matrix
  55781. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  55782. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  55783. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  55784. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  55785. var vertexData = new BABYLON.VertexData();
  55786. vertexData.indices = [];
  55787. vertexData.positions = [];
  55788. vertexData.normals = [];
  55789. vertexData.uvs = [];
  55790. var currentVertexDataIndex = 0;
  55791. var extractDecalVector3 = function (indexId) {
  55792. var result = new BABYLON.PositionNormalVertex();
  55793. if (!indices || !positions || !normals) {
  55794. return result;
  55795. }
  55796. var vertexId = indices[indexId];
  55797. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  55798. // Send vector to decal local world
  55799. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  55800. // Get normal
  55801. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  55802. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  55803. return result;
  55804. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  55805. var clip = function (vertices, axis) {
  55806. if (vertices.length === 0) {
  55807. return vertices;
  55808. }
  55809. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  55810. var clipVertices = function (v0, v1) {
  55811. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  55812. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  55813. };
  55814. var result = new Array();
  55815. for (var index = 0; index < vertices.length; index += 3) {
  55816. var v1Out;
  55817. var v2Out;
  55818. var v3Out;
  55819. var total = 0;
  55820. var nV1 = null;
  55821. var nV2 = null;
  55822. var nV3 = null;
  55823. var nV4 = null;
  55824. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  55825. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  55826. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  55827. v1Out = d1 > 0;
  55828. v2Out = d2 > 0;
  55829. v3Out = d3 > 0;
  55830. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  55831. switch (total) {
  55832. case 0:
  55833. result.push(vertices[index]);
  55834. result.push(vertices[index + 1]);
  55835. result.push(vertices[index + 2]);
  55836. break;
  55837. case 1:
  55838. if (v1Out) {
  55839. nV1 = vertices[index + 1];
  55840. nV2 = vertices[index + 2];
  55841. nV3 = clipVertices(vertices[index], nV1);
  55842. nV4 = clipVertices(vertices[index], nV2);
  55843. }
  55844. if (v2Out) {
  55845. nV1 = vertices[index];
  55846. nV2 = vertices[index + 2];
  55847. nV3 = clipVertices(vertices[index + 1], nV1);
  55848. nV4 = clipVertices(vertices[index + 1], nV2);
  55849. result.push(nV3);
  55850. result.push(nV2.clone());
  55851. result.push(nV1.clone());
  55852. result.push(nV2.clone());
  55853. result.push(nV3.clone());
  55854. result.push(nV4);
  55855. break;
  55856. }
  55857. if (v3Out) {
  55858. nV1 = vertices[index];
  55859. nV2 = vertices[index + 1];
  55860. nV3 = clipVertices(vertices[index + 2], nV1);
  55861. nV4 = clipVertices(vertices[index + 2], nV2);
  55862. }
  55863. if (nV1 && nV2 && nV3 && nV4) {
  55864. result.push(nV1.clone());
  55865. result.push(nV2.clone());
  55866. result.push(nV3);
  55867. result.push(nV4);
  55868. result.push(nV3.clone());
  55869. result.push(nV2.clone());
  55870. }
  55871. break;
  55872. case 2:
  55873. if (!v1Out) {
  55874. nV1 = vertices[index].clone();
  55875. nV2 = clipVertices(nV1, vertices[index + 1]);
  55876. nV3 = clipVertices(nV1, vertices[index + 2]);
  55877. result.push(nV1);
  55878. result.push(nV2);
  55879. result.push(nV3);
  55880. }
  55881. if (!v2Out) {
  55882. nV1 = vertices[index + 1].clone();
  55883. nV2 = clipVertices(nV1, vertices[index + 2]);
  55884. nV3 = clipVertices(nV1, vertices[index]);
  55885. result.push(nV1);
  55886. result.push(nV2);
  55887. result.push(nV3);
  55888. }
  55889. if (!v3Out) {
  55890. nV1 = vertices[index + 2].clone();
  55891. nV2 = clipVertices(nV1, vertices[index]);
  55892. nV3 = clipVertices(nV1, vertices[index + 1]);
  55893. result.push(nV1);
  55894. result.push(nV2);
  55895. result.push(nV3);
  55896. }
  55897. break;
  55898. case 3:
  55899. break;
  55900. }
  55901. }
  55902. return result;
  55903. };
  55904. for (var index = 0; index < indices.length; index += 3) {
  55905. var faceVertices = new Array();
  55906. faceVertices.push(extractDecalVector3(index));
  55907. faceVertices.push(extractDecalVector3(index + 1));
  55908. faceVertices.push(extractDecalVector3(index + 2));
  55909. // Clip
  55910. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  55911. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  55912. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  55913. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  55914. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  55915. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  55916. if (faceVertices.length === 0) {
  55917. continue;
  55918. }
  55919. // Add UVs and get back to world
  55920. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  55921. var vertex = faceVertices[vIndex];
  55922. //TODO check for Int32Array | Uint32Array | Uint16Array
  55923. vertexData.indices.push(currentVertexDataIndex);
  55924. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  55925. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  55926. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  55927. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  55928. currentVertexDataIndex++;
  55929. }
  55930. }
  55931. // Return mesh
  55932. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  55933. vertexData.applyToMesh(decal);
  55934. decal.position = position.clone();
  55935. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  55936. return decal;
  55937. };
  55938. // Privates
  55939. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  55940. // extrusion geometry
  55941. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  55942. var tangents = path3D.getTangents();
  55943. var normals = path3D.getNormals();
  55944. var binormals = path3D.getBinormals();
  55945. var distances = path3D.getDistances();
  55946. var angle = 0;
  55947. var returnScale = function () { return scale !== null ? scale : 1; };
  55948. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  55949. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  55950. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  55951. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  55952. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  55953. for (var i = 0; i < curve.length; i++) {
  55954. var shapePath = new Array();
  55955. var angleStep = rotate(i, distances[i]);
  55956. var scaleRatio = scl(i, distances[i]);
  55957. for (var p = 0; p < shape.length; p++) {
  55958. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  55959. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  55960. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  55961. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  55962. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  55963. shapePath[p] = rotated;
  55964. }
  55965. shapePaths[index] = shapePath;
  55966. angle += angleStep;
  55967. index++;
  55968. }
  55969. // cap
  55970. var capPath = function (shapePath) {
  55971. var pointCap = Array();
  55972. var barycenter = BABYLON.Vector3.Zero();
  55973. var i;
  55974. for (i = 0; i < shapePath.length; i++) {
  55975. barycenter.addInPlace(shapePath[i]);
  55976. }
  55977. barycenter.scaleInPlace(1.0 / shapePath.length);
  55978. for (i = 0; i < shapePath.length; i++) {
  55979. pointCap.push(barycenter);
  55980. }
  55981. return pointCap;
  55982. };
  55983. switch (cap) {
  55984. case BABYLON.Mesh.NO_CAP:
  55985. break;
  55986. case BABYLON.Mesh.CAP_START:
  55987. shapePaths[0] = capPath(shapePaths[2]);
  55988. shapePaths[1] = shapePaths[2];
  55989. break;
  55990. case BABYLON.Mesh.CAP_END:
  55991. shapePaths[index] = shapePaths[index - 1];
  55992. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55993. break;
  55994. case BABYLON.Mesh.CAP_ALL:
  55995. shapePaths[0] = capPath(shapePaths[2]);
  55996. shapePaths[1] = shapePaths[2];
  55997. shapePaths[index] = shapePaths[index - 1];
  55998. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  55999. break;
  56000. default:
  56001. break;
  56002. }
  56003. return shapePaths;
  56004. };
  56005. var path3D;
  56006. var pathArray;
  56007. if (instance) {
  56008. path3D = (instance.path3D).update(curve);
  56009. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  56010. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  56011. return instance;
  56012. }
  56013. // extruded shape creation
  56014. path3D = new BABYLON.Path3D(curve);
  56015. var newShapePaths = new Array();
  56016. cap = (cap < 0 || cap > 3) ? 0 : cap;
  56017. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  56018. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  56019. extrudedGeneric.pathArray = pathArray;
  56020. extrudedGeneric.path3D = path3D;
  56021. extrudedGeneric.cap = cap;
  56022. return extrudedGeneric;
  56023. };
  56024. return MeshBuilder;
  56025. }());
  56026. BABYLON.MeshBuilder = MeshBuilder;
  56027. })(BABYLON || (BABYLON = {}));
  56028. //# sourceMappingURL=babylon.meshBuilder.js.map
  56029. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  56030. var BABYLON;
  56031. (function (BABYLON) {
  56032. /**
  56033. * Draco compression (https://google.github.io/draco/)
  56034. */
  56035. var DracoCompression = /** @class */ (function () {
  56036. function DracoCompression() {
  56037. }
  56038. Object.defineProperty(DracoCompression, "IsSupported", {
  56039. /**
  56040. * Returns whether Draco compression is supported.
  56041. */
  56042. get: function () {
  56043. return BABYLON.Tools.IsWindowObjectExist() && !!window.DracoDecoderModule;
  56044. },
  56045. enumerable: true,
  56046. configurable: true
  56047. });
  56048. /**
  56049. * Decodes Draco compressed data to vertex data.
  56050. * @param data The array buffer view for the Draco compression data
  56051. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  56052. * @returns The decoded vertex data
  56053. */
  56054. DracoCompression.Decode = function (data, attributes) {
  56055. var dracoModule = new DracoDecoderModule();
  56056. var buffer = new dracoModule.DecoderBuffer();
  56057. buffer.Init(data, data.byteLength);
  56058. var decoder = new dracoModule.Decoder();
  56059. var geometry;
  56060. var status;
  56061. var vertexData = new BABYLON.VertexData();
  56062. try {
  56063. var type = decoder.GetEncodedGeometryType(buffer);
  56064. switch (type) {
  56065. case dracoModule.TRIANGULAR_MESH:
  56066. geometry = new dracoModule.Mesh();
  56067. status = decoder.DecodeBufferToMesh(buffer, geometry);
  56068. break;
  56069. case dracoModule.POINT_CLOUD:
  56070. geometry = new dracoModule.PointCloud();
  56071. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  56072. break;
  56073. default:
  56074. throw new Error("Invalid geometry type " + type);
  56075. }
  56076. if (!status.ok() || !geometry.ptr) {
  56077. throw new Error(status.error_msg());
  56078. }
  56079. var numPoints = geometry.num_points();
  56080. if (type === dracoModule.TRIANGULAR_MESH) {
  56081. var numFaces = geometry.num_faces();
  56082. var faceIndices = new dracoModule.DracoInt32Array();
  56083. try {
  56084. vertexData.indices = new Uint32Array(numFaces * 3);
  56085. for (var i = 0; i < numFaces; i++) {
  56086. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  56087. var offset = i * 3;
  56088. vertexData.indices[offset + 0] = faceIndices.GetValue(0);
  56089. vertexData.indices[offset + 1] = faceIndices.GetValue(1);
  56090. vertexData.indices[offset + 2] = faceIndices.GetValue(2);
  56091. }
  56092. }
  56093. finally {
  56094. dracoModule.destroy(faceIndices);
  56095. }
  56096. }
  56097. for (var kind in attributes) {
  56098. var uniqueId = attributes[kind];
  56099. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  56100. var dracoData = new dracoModule.DracoFloat32Array();
  56101. try {
  56102. if (attribute.num_components() !== BABYLON.VertexBuffer.DeduceStride(kind)) {
  56103. throw new Error("Unsupported number of components for " + kind);
  56104. }
  56105. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  56106. var babylonData = new Float32Array(numPoints * attribute.num_components());
  56107. for (var i = 0; i < babylonData.length; i++) {
  56108. babylonData[i] = dracoData.GetValue(i);
  56109. }
  56110. vertexData.set(babylonData, kind);
  56111. }
  56112. finally {
  56113. dracoModule.destroy(dracoData);
  56114. }
  56115. }
  56116. }
  56117. finally {
  56118. if (geometry) {
  56119. dracoModule.destroy(geometry);
  56120. }
  56121. dracoModule.destroy(decoder);
  56122. dracoModule.destroy(buffer);
  56123. }
  56124. return vertexData;
  56125. };
  56126. return DracoCompression;
  56127. }());
  56128. BABYLON.DracoCompression = DracoCompression;
  56129. })(BABYLON || (BABYLON = {}));
  56130. //# sourceMappingURL=babylon.dracoCompression.js.map
  56131. var BABYLON;
  56132. (function (BABYLON) {
  56133. var AudioEngine = /** @class */ (function () {
  56134. function AudioEngine() {
  56135. this._audioContext = null;
  56136. this._audioContextInitialized = false;
  56137. this.canUseWebAudio = false;
  56138. this.WarnedWebAudioUnsupported = false;
  56139. this.unlocked = false;
  56140. this.isMP3supported = false;
  56141. this.isOGGsupported = false;
  56142. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  56143. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  56144. this.canUseWebAudio = true;
  56145. }
  56146. var audioElem = document.createElement('audio');
  56147. try {
  56148. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  56149. this.isMP3supported = true;
  56150. }
  56151. }
  56152. catch (e) {
  56153. // protect error during capability check.
  56154. }
  56155. try {
  56156. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  56157. this.isOGGsupported = true;
  56158. }
  56159. }
  56160. catch (e) {
  56161. // protect error during capability check.
  56162. }
  56163. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  56164. this._unlockiOSaudio();
  56165. }
  56166. else {
  56167. this.unlocked = true;
  56168. }
  56169. }
  56170. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  56171. get: function () {
  56172. if (!this._audioContextInitialized) {
  56173. this._initializeAudioContext();
  56174. }
  56175. return this._audioContext;
  56176. },
  56177. enumerable: true,
  56178. configurable: true
  56179. });
  56180. AudioEngine.prototype._unlockiOSaudio = function () {
  56181. var _this = this;
  56182. var unlockaudio = function () {
  56183. if (!_this.audioContext) {
  56184. return;
  56185. }
  56186. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  56187. var source = _this.audioContext.createBufferSource();
  56188. source.buffer = buffer;
  56189. source.connect(_this.audioContext.destination);
  56190. source.start(0);
  56191. setTimeout(function () {
  56192. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  56193. _this.unlocked = true;
  56194. window.removeEventListener('touchend', unlockaudio, false);
  56195. if (_this.onAudioUnlocked) {
  56196. _this.onAudioUnlocked();
  56197. }
  56198. }
  56199. }, 0);
  56200. };
  56201. window.addEventListener('touchend', unlockaudio, false);
  56202. };
  56203. AudioEngine.prototype._initializeAudioContext = function () {
  56204. try {
  56205. if (this.canUseWebAudio) {
  56206. this._audioContext = new AudioContext();
  56207. // create a global volume gain node
  56208. this.masterGain = this._audioContext.createGain();
  56209. this.masterGain.gain.value = 1;
  56210. this.masterGain.connect(this._audioContext.destination);
  56211. this._audioContextInitialized = true;
  56212. }
  56213. }
  56214. catch (e) {
  56215. this.canUseWebAudio = false;
  56216. BABYLON.Tools.Error("Web Audio: " + e.message);
  56217. }
  56218. };
  56219. AudioEngine.prototype.dispose = function () {
  56220. if (this.canUseWebAudio && this._audioContextInitialized) {
  56221. if (this._connectedAnalyser && this._audioContext) {
  56222. this._connectedAnalyser.stopDebugCanvas();
  56223. this._connectedAnalyser.dispose();
  56224. this.masterGain.disconnect();
  56225. this.masterGain.connect(this._audioContext.destination);
  56226. this._connectedAnalyser = null;
  56227. }
  56228. this.masterGain.gain.value = 1;
  56229. }
  56230. this.WarnedWebAudioUnsupported = false;
  56231. };
  56232. AudioEngine.prototype.getGlobalVolume = function () {
  56233. if (this.canUseWebAudio && this._audioContextInitialized) {
  56234. return this.masterGain.gain.value;
  56235. }
  56236. else {
  56237. return -1;
  56238. }
  56239. };
  56240. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  56241. if (this.canUseWebAudio && this._audioContextInitialized) {
  56242. this.masterGain.gain.value = newVolume;
  56243. }
  56244. };
  56245. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  56246. if (this._connectedAnalyser) {
  56247. this._connectedAnalyser.stopDebugCanvas();
  56248. }
  56249. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  56250. this._connectedAnalyser = analyser;
  56251. this.masterGain.disconnect();
  56252. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  56253. }
  56254. };
  56255. return AudioEngine;
  56256. }());
  56257. BABYLON.AudioEngine = AudioEngine;
  56258. })(BABYLON || (BABYLON = {}));
  56259. //# sourceMappingURL=babylon.audioEngine.js.map
  56260. var BABYLON;
  56261. (function (BABYLON) {
  56262. var Sound = /** @class */ (function () {
  56263. /**
  56264. * Create a sound and attach it to a scene
  56265. * @param name Name of your sound
  56266. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  56267. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  56268. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  56269. */
  56270. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  56271. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  56272. var _this = this;
  56273. this.autoplay = false;
  56274. this.loop = false;
  56275. this.useCustomAttenuation = false;
  56276. this.spatialSound = false;
  56277. this.refDistance = 1;
  56278. this.rolloffFactor = 1;
  56279. this.maxDistance = 100;
  56280. this.distanceModel = "linear";
  56281. this._panningModel = "equalpower";
  56282. this._playbackRate = 1;
  56283. this._streaming = false;
  56284. this._startTime = 0;
  56285. this._startOffset = 0;
  56286. this._position = BABYLON.Vector3.Zero();
  56287. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  56288. this._volume = 1;
  56289. this._isReadyToPlay = false;
  56290. this.isPlaying = false;
  56291. this.isPaused = false;
  56292. this._isDirectional = false;
  56293. // Used if you'd like to create a directional sound.
  56294. // If not set, the sound will be omnidirectional
  56295. this._coneInnerAngle = 360;
  56296. this._coneOuterAngle = 360;
  56297. this._coneOuterGain = 0;
  56298. this._isOutputConnected = false;
  56299. this._urlType = "Unknown";
  56300. this.name = name;
  56301. this._scene = scene;
  56302. this._readyToPlayCallback = readyToPlayCallback;
  56303. // Default custom attenuation function is a linear attenuation
  56304. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  56305. if (currentDistance < maxDistance) {
  56306. return currentVolume * (1 - currentDistance / maxDistance);
  56307. }
  56308. else {
  56309. return 0;
  56310. }
  56311. };
  56312. if (options) {
  56313. this.autoplay = options.autoplay || false;
  56314. this.loop = options.loop || false;
  56315. // if volume === 0, we need another way to check this option
  56316. if (options.volume !== undefined) {
  56317. this._volume = options.volume;
  56318. }
  56319. this.spatialSound = options.spatialSound || false;
  56320. this.maxDistance = options.maxDistance || 100;
  56321. this.useCustomAttenuation = options.useCustomAttenuation || false;
  56322. this.rolloffFactor = options.rolloffFactor || 1;
  56323. this.refDistance = options.refDistance || 1;
  56324. this.distanceModel = options.distanceModel || "linear";
  56325. this._playbackRate = options.playbackRate || 1;
  56326. this._streaming = options.streaming || false;
  56327. }
  56328. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56329. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  56330. this._soundGain.gain.value = this._volume;
  56331. this._inputAudioNode = this._soundGain;
  56332. this._ouputAudioNode = this._soundGain;
  56333. if (this.spatialSound) {
  56334. this._createSpatialParameters();
  56335. }
  56336. this._scene.mainSoundTrack.AddSound(this);
  56337. var validParameter = true;
  56338. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  56339. if (urlOrArrayBuffer) {
  56340. if (typeof (urlOrArrayBuffer) === "string")
  56341. this._urlType = "String";
  56342. if (Array.isArray(urlOrArrayBuffer))
  56343. this._urlType = "Array";
  56344. if (urlOrArrayBuffer instanceof ArrayBuffer)
  56345. this._urlType = "ArrayBuffer";
  56346. var urls = [];
  56347. var codecSupportedFound = false;
  56348. switch (this._urlType) {
  56349. case "ArrayBuffer":
  56350. if (urlOrArrayBuffer.byteLength > 0) {
  56351. codecSupportedFound = true;
  56352. this._soundLoaded(urlOrArrayBuffer);
  56353. }
  56354. break;
  56355. case "String":
  56356. urls.push(urlOrArrayBuffer);
  56357. case "Array":
  56358. if (urls.length === 0)
  56359. urls = urlOrArrayBuffer;
  56360. // If we found a supported format, we load it immediately and stop the loop
  56361. for (var i = 0; i < urls.length; i++) {
  56362. var url = urls[i];
  56363. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  56364. codecSupportedFound = true;
  56365. }
  56366. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  56367. codecSupportedFound = true;
  56368. }
  56369. if (url.indexOf(".wav", url.length - 4) !== -1) {
  56370. codecSupportedFound = true;
  56371. }
  56372. if (url.indexOf("blob:") !== -1) {
  56373. codecSupportedFound = true;
  56374. }
  56375. if (codecSupportedFound) {
  56376. // Loading sound using XHR2
  56377. if (!this._streaming) {
  56378. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  56379. }
  56380. else {
  56381. this._htmlAudioElement = new Audio(url);
  56382. this._htmlAudioElement.controls = false;
  56383. this._htmlAudioElement.loop = this.loop;
  56384. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  56385. this._htmlAudioElement.preload = "auto";
  56386. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  56387. _this._isReadyToPlay = true;
  56388. if (_this.autoplay) {
  56389. _this.play();
  56390. }
  56391. if (_this._readyToPlayCallback) {
  56392. _this._readyToPlayCallback();
  56393. }
  56394. });
  56395. document.body.appendChild(this._htmlAudioElement);
  56396. }
  56397. break;
  56398. }
  56399. }
  56400. break;
  56401. default:
  56402. validParameter = false;
  56403. break;
  56404. }
  56405. if (!validParameter) {
  56406. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  56407. }
  56408. else {
  56409. if (!codecSupportedFound) {
  56410. this._isReadyToPlay = true;
  56411. // Simulating a ready to play event to avoid breaking code path
  56412. if (this._readyToPlayCallback) {
  56413. window.setTimeout(function () {
  56414. if (_this._readyToPlayCallback) {
  56415. _this._readyToPlayCallback();
  56416. }
  56417. }, 1000);
  56418. }
  56419. }
  56420. }
  56421. }
  56422. }
  56423. else {
  56424. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  56425. this._scene.mainSoundTrack.AddSound(this);
  56426. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  56427. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  56428. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  56429. }
  56430. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  56431. if (this._readyToPlayCallback) {
  56432. window.setTimeout(function () {
  56433. if (_this._readyToPlayCallback) {
  56434. _this._readyToPlayCallback();
  56435. }
  56436. }, 1000);
  56437. }
  56438. }
  56439. }
  56440. Sound.prototype.dispose = function () {
  56441. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  56442. if (this.isPlaying) {
  56443. this.stop();
  56444. }
  56445. this._isReadyToPlay = false;
  56446. if (this.soundTrackId === -1) {
  56447. this._scene.mainSoundTrack.RemoveSound(this);
  56448. }
  56449. else {
  56450. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  56451. }
  56452. if (this._soundGain) {
  56453. this._soundGain.disconnect();
  56454. this._soundGain = null;
  56455. }
  56456. if (this._soundPanner) {
  56457. this._soundPanner.disconnect();
  56458. this._soundPanner = null;
  56459. }
  56460. if (this._soundSource) {
  56461. this._soundSource.disconnect();
  56462. this._soundSource = null;
  56463. }
  56464. this._audioBuffer = null;
  56465. if (this._htmlAudioElement) {
  56466. this._htmlAudioElement.pause();
  56467. this._htmlAudioElement.src = "";
  56468. document.body.removeChild(this._htmlAudioElement);
  56469. }
  56470. if (this._connectedMesh && this._registerFunc) {
  56471. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56472. this._connectedMesh = null;
  56473. }
  56474. }
  56475. };
  56476. Sound.prototype.isReady = function () {
  56477. return this._isReadyToPlay;
  56478. };
  56479. Sound.prototype._soundLoaded = function (audioData) {
  56480. var _this = this;
  56481. if (!BABYLON.Engine.audioEngine.audioContext) {
  56482. return;
  56483. }
  56484. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  56485. _this._audioBuffer = buffer;
  56486. _this._isReadyToPlay = true;
  56487. if (_this.autoplay) {
  56488. _this.play();
  56489. }
  56490. if (_this._readyToPlayCallback) {
  56491. _this._readyToPlayCallback();
  56492. }
  56493. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  56494. };
  56495. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  56496. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56497. this._audioBuffer = audioBuffer;
  56498. this._isReadyToPlay = true;
  56499. }
  56500. };
  56501. Sound.prototype.updateOptions = function (options) {
  56502. if (options) {
  56503. this.loop = options.loop || this.loop;
  56504. this.maxDistance = options.maxDistance || this.maxDistance;
  56505. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  56506. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  56507. this.refDistance = options.refDistance || this.refDistance;
  56508. this.distanceModel = options.distanceModel || this.distanceModel;
  56509. this._playbackRate = options.playbackRate || this._playbackRate;
  56510. this._updateSpatialParameters();
  56511. if (this.isPlaying) {
  56512. if (this._streaming) {
  56513. this._htmlAudioElement.playbackRate = this._playbackRate;
  56514. }
  56515. else {
  56516. if (this._soundSource) {
  56517. this._soundSource.playbackRate.value = this._playbackRate;
  56518. }
  56519. }
  56520. }
  56521. }
  56522. };
  56523. Sound.prototype._createSpatialParameters = function () {
  56524. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56525. if (this._scene.headphone) {
  56526. this._panningModel = "HRTF";
  56527. }
  56528. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  56529. this._updateSpatialParameters();
  56530. this._soundPanner.connect(this._ouputAudioNode);
  56531. this._inputAudioNode = this._soundPanner;
  56532. }
  56533. };
  56534. Sound.prototype._updateSpatialParameters = function () {
  56535. if (this.spatialSound && this._soundPanner) {
  56536. if (this.useCustomAttenuation) {
  56537. // Tricks to disable in a way embedded Web Audio attenuation
  56538. this._soundPanner.distanceModel = "linear";
  56539. this._soundPanner.maxDistance = Number.MAX_VALUE;
  56540. this._soundPanner.refDistance = 1;
  56541. this._soundPanner.rolloffFactor = 1;
  56542. this._soundPanner.panningModel = this._panningModel;
  56543. }
  56544. else {
  56545. this._soundPanner.distanceModel = this.distanceModel;
  56546. this._soundPanner.maxDistance = this.maxDistance;
  56547. this._soundPanner.refDistance = this.refDistance;
  56548. this._soundPanner.rolloffFactor = this.rolloffFactor;
  56549. this._soundPanner.panningModel = this._panningModel;
  56550. }
  56551. }
  56552. };
  56553. Sound.prototype.switchPanningModelToHRTF = function () {
  56554. this._panningModel = "HRTF";
  56555. this._switchPanningModel();
  56556. };
  56557. Sound.prototype.switchPanningModelToEqualPower = function () {
  56558. this._panningModel = "equalpower";
  56559. this._switchPanningModel();
  56560. };
  56561. Sound.prototype._switchPanningModel = function () {
  56562. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56563. this._soundPanner.panningModel = this._panningModel;
  56564. }
  56565. };
  56566. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  56567. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56568. if (this._isOutputConnected) {
  56569. this._ouputAudioNode.disconnect();
  56570. }
  56571. this._ouputAudioNode.connect(soundTrackAudioNode);
  56572. this._isOutputConnected = true;
  56573. }
  56574. };
  56575. /**
  56576. * Transform this sound into a directional source
  56577. * @param coneInnerAngle Size of the inner cone in degree
  56578. * @param coneOuterAngle Size of the outer cone in degree
  56579. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  56580. */
  56581. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  56582. if (coneOuterAngle < coneInnerAngle) {
  56583. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  56584. return;
  56585. }
  56586. this._coneInnerAngle = coneInnerAngle;
  56587. this._coneOuterAngle = coneOuterAngle;
  56588. this._coneOuterGain = coneOuterGain;
  56589. this._isDirectional = true;
  56590. if (this.isPlaying && this.loop) {
  56591. this.stop();
  56592. this.play();
  56593. }
  56594. };
  56595. Sound.prototype.setPosition = function (newPosition) {
  56596. this._position = newPosition;
  56597. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  56598. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56599. }
  56600. };
  56601. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  56602. this._localDirection = newLocalDirection;
  56603. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  56604. this._updateDirection();
  56605. }
  56606. };
  56607. Sound.prototype._updateDirection = function () {
  56608. if (!this._connectedMesh || !this._soundPanner) {
  56609. return;
  56610. }
  56611. var mat = this._connectedMesh.getWorldMatrix();
  56612. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  56613. direction.normalize();
  56614. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  56615. };
  56616. Sound.prototype.updateDistanceFromListener = function () {
  56617. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  56618. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  56619. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  56620. }
  56621. };
  56622. Sound.prototype.setAttenuationFunction = function (callback) {
  56623. this._customAttenuationFunction = callback;
  56624. };
  56625. /**
  56626. * Play the sound
  56627. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  56628. * @param offset (optional) Start the sound setting it at a specific time
  56629. */
  56630. Sound.prototype.play = function (time, offset) {
  56631. var _this = this;
  56632. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  56633. try {
  56634. if (this._startOffset < 0) {
  56635. time = -this._startOffset;
  56636. this._startOffset = 0;
  56637. }
  56638. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56639. if (!this._soundSource || !this._streamingSource) {
  56640. if (this.spatialSound && this._soundPanner) {
  56641. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  56642. if (this._isDirectional) {
  56643. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  56644. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  56645. this._soundPanner.coneOuterGain = this._coneOuterGain;
  56646. if (this._connectedMesh) {
  56647. this._updateDirection();
  56648. }
  56649. else {
  56650. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  56651. }
  56652. }
  56653. }
  56654. }
  56655. if (this._streaming) {
  56656. if (!this._streamingSource) {
  56657. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  56658. this._htmlAudioElement.onended = function () { _this._onended(); };
  56659. this._htmlAudioElement.playbackRate = this._playbackRate;
  56660. }
  56661. this._streamingSource.disconnect();
  56662. this._streamingSource.connect(this._inputAudioNode);
  56663. this._htmlAudioElement.play();
  56664. }
  56665. else {
  56666. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  56667. this._soundSource.buffer = this._audioBuffer;
  56668. this._soundSource.connect(this._inputAudioNode);
  56669. this._soundSource.loop = this.loop;
  56670. this._soundSource.playbackRate.value = this._playbackRate;
  56671. this._soundSource.onended = function () { _this._onended(); };
  56672. if (this._soundSource.buffer) {
  56673. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  56674. }
  56675. }
  56676. this._startTime = startTime;
  56677. this.isPlaying = true;
  56678. this.isPaused = false;
  56679. }
  56680. catch (ex) {
  56681. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  56682. }
  56683. }
  56684. };
  56685. Sound.prototype._onended = function () {
  56686. this.isPlaying = false;
  56687. if (this.onended) {
  56688. this.onended();
  56689. }
  56690. };
  56691. /**
  56692. * Stop the sound
  56693. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  56694. */
  56695. Sound.prototype.stop = function (time) {
  56696. if (this.isPlaying) {
  56697. if (this._streaming) {
  56698. this._htmlAudioElement.pause();
  56699. // Test needed for Firefox or it will generate an Invalid State Error
  56700. if (this._htmlAudioElement.currentTime > 0) {
  56701. this._htmlAudioElement.currentTime = 0;
  56702. }
  56703. }
  56704. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  56705. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  56706. this._soundSource.stop(stopTime);
  56707. this._soundSource.onended = function () { };
  56708. if (!this.isPaused) {
  56709. this._startOffset = 0;
  56710. }
  56711. }
  56712. this.isPlaying = false;
  56713. }
  56714. };
  56715. Sound.prototype.pause = function () {
  56716. if (this.isPlaying) {
  56717. this.isPaused = true;
  56718. if (this._streaming) {
  56719. this._htmlAudioElement.pause();
  56720. }
  56721. else if (BABYLON.Engine.audioEngine.audioContext) {
  56722. this.stop(0);
  56723. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  56724. }
  56725. }
  56726. };
  56727. Sound.prototype.setVolume = function (newVolume, time) {
  56728. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  56729. if (time && BABYLON.Engine.audioEngine.audioContext) {
  56730. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  56731. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  56732. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  56733. }
  56734. else {
  56735. this._soundGain.gain.value = newVolume;
  56736. }
  56737. }
  56738. this._volume = newVolume;
  56739. };
  56740. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  56741. this._playbackRate = newPlaybackRate;
  56742. if (this.isPlaying) {
  56743. if (this._streaming) {
  56744. this._htmlAudioElement.playbackRate = this._playbackRate;
  56745. }
  56746. else if (this._soundSource) {
  56747. this._soundSource.playbackRate.value = this._playbackRate;
  56748. }
  56749. }
  56750. };
  56751. Sound.prototype.getVolume = function () {
  56752. return this._volume;
  56753. };
  56754. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  56755. var _this = this;
  56756. if (this._connectedMesh && this._registerFunc) {
  56757. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56758. this._registerFunc = null;
  56759. }
  56760. this._connectedMesh = meshToConnectTo;
  56761. if (!this.spatialSound) {
  56762. this.spatialSound = true;
  56763. this._createSpatialParameters();
  56764. if (this.isPlaying && this.loop) {
  56765. this.stop();
  56766. this.play();
  56767. }
  56768. }
  56769. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  56770. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  56771. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  56772. };
  56773. Sound.prototype.detachFromMesh = function () {
  56774. if (this._connectedMesh && this._registerFunc) {
  56775. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  56776. this._registerFunc = null;
  56777. this._connectedMesh = null;
  56778. }
  56779. };
  56780. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  56781. if (!node.getBoundingInfo) {
  56782. return;
  56783. }
  56784. var mesh = node;
  56785. var boundingInfo = mesh.getBoundingInfo();
  56786. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  56787. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  56788. this._updateDirection();
  56789. }
  56790. };
  56791. Sound.prototype.clone = function () {
  56792. var _this = this;
  56793. if (!this._streaming) {
  56794. var setBufferAndRun = function () {
  56795. if (_this._isReadyToPlay) {
  56796. clonedSound._audioBuffer = _this.getAudioBuffer();
  56797. clonedSound._isReadyToPlay = true;
  56798. if (clonedSound.autoplay) {
  56799. clonedSound.play();
  56800. }
  56801. }
  56802. else {
  56803. window.setTimeout(setBufferAndRun, 300);
  56804. }
  56805. };
  56806. var currentOptions = {
  56807. autoplay: this.autoplay, loop: this.loop,
  56808. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  56809. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  56810. refDistance: this.refDistance, distanceModel: this.distanceModel
  56811. };
  56812. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  56813. if (this.useCustomAttenuation) {
  56814. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  56815. }
  56816. clonedSound.setPosition(this._position);
  56817. clonedSound.setPlaybackRate(this._playbackRate);
  56818. setBufferAndRun();
  56819. return clonedSound;
  56820. }
  56821. else {
  56822. return null;
  56823. }
  56824. };
  56825. Sound.prototype.getAudioBuffer = function () {
  56826. return this._audioBuffer;
  56827. };
  56828. Sound.prototype.serialize = function () {
  56829. var serializationObject = {
  56830. name: this.name,
  56831. url: this.name,
  56832. autoplay: this.autoplay,
  56833. loop: this.loop,
  56834. volume: this._volume,
  56835. spatialSound: this.spatialSound,
  56836. maxDistance: this.maxDistance,
  56837. rolloffFactor: this.rolloffFactor,
  56838. refDistance: this.refDistance,
  56839. distanceModel: this.distanceModel,
  56840. playbackRate: this._playbackRate,
  56841. panningModel: this._panningModel,
  56842. soundTrackId: this.soundTrackId
  56843. };
  56844. if (this.spatialSound) {
  56845. if (this._connectedMesh)
  56846. serializationObject.connectedMeshId = this._connectedMesh.id;
  56847. serializationObject.position = this._position.asArray();
  56848. serializationObject.refDistance = this.refDistance;
  56849. serializationObject.distanceModel = this.distanceModel;
  56850. serializationObject.isDirectional = this._isDirectional;
  56851. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  56852. serializationObject.coneInnerAngle = this._coneInnerAngle;
  56853. serializationObject.coneOuterAngle = this._coneOuterAngle;
  56854. serializationObject.coneOuterGain = this._coneOuterGain;
  56855. }
  56856. return serializationObject;
  56857. };
  56858. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  56859. var soundName = parsedSound.name;
  56860. var soundUrl;
  56861. if (parsedSound.url) {
  56862. soundUrl = rootUrl + parsedSound.url;
  56863. }
  56864. else {
  56865. soundUrl = rootUrl + soundName;
  56866. }
  56867. var options = {
  56868. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  56869. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  56870. rolloffFactor: parsedSound.rolloffFactor,
  56871. refDistance: parsedSound.refDistance,
  56872. distanceModel: parsedSound.distanceModel,
  56873. playbackRate: parsedSound.playbackRate
  56874. };
  56875. var newSound;
  56876. if (!sourceSound) {
  56877. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  56878. scene._addPendingData(newSound);
  56879. }
  56880. else {
  56881. var setBufferAndRun = function () {
  56882. if (sourceSound._isReadyToPlay) {
  56883. newSound._audioBuffer = sourceSound.getAudioBuffer();
  56884. newSound._isReadyToPlay = true;
  56885. if (newSound.autoplay) {
  56886. newSound.play();
  56887. }
  56888. }
  56889. else {
  56890. window.setTimeout(setBufferAndRun, 300);
  56891. }
  56892. };
  56893. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  56894. setBufferAndRun();
  56895. }
  56896. if (parsedSound.position) {
  56897. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  56898. newSound.setPosition(soundPosition);
  56899. }
  56900. if (parsedSound.isDirectional) {
  56901. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  56902. if (parsedSound.localDirectionToMesh) {
  56903. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  56904. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  56905. }
  56906. }
  56907. if (parsedSound.connectedMeshId) {
  56908. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  56909. if (connectedMesh) {
  56910. newSound.attachToMesh(connectedMesh);
  56911. }
  56912. }
  56913. return newSound;
  56914. };
  56915. return Sound;
  56916. }());
  56917. BABYLON.Sound = Sound;
  56918. })(BABYLON || (BABYLON = {}));
  56919. //# sourceMappingURL=babylon.sound.js.map
  56920. var BABYLON;
  56921. (function (BABYLON) {
  56922. var SoundTrack = /** @class */ (function () {
  56923. function SoundTrack(scene, options) {
  56924. this.id = -1;
  56925. this._isMainTrack = false;
  56926. this._isInitialized = false;
  56927. this._scene = scene;
  56928. this.soundCollection = new Array();
  56929. this._options = options;
  56930. if (!this._isMainTrack) {
  56931. this._scene.soundTracks.push(this);
  56932. this.id = this._scene.soundTracks.length - 1;
  56933. }
  56934. }
  56935. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  56936. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  56937. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  56938. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  56939. if (this._options) {
  56940. if (this._options.volume) {
  56941. this._outputAudioNode.gain.value = this._options.volume;
  56942. }
  56943. if (this._options.mainTrack) {
  56944. this._isMainTrack = this._options.mainTrack;
  56945. }
  56946. }
  56947. this._isInitialized = true;
  56948. }
  56949. };
  56950. SoundTrack.prototype.dispose = function () {
  56951. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  56952. if (this._connectedAnalyser) {
  56953. this._connectedAnalyser.stopDebugCanvas();
  56954. }
  56955. while (this.soundCollection.length) {
  56956. this.soundCollection[0].dispose();
  56957. }
  56958. if (this._outputAudioNode) {
  56959. this._outputAudioNode.disconnect();
  56960. }
  56961. this._outputAudioNode = null;
  56962. }
  56963. };
  56964. SoundTrack.prototype.AddSound = function (sound) {
  56965. if (!this._isInitialized) {
  56966. this._initializeSoundTrackAudioGraph();
  56967. }
  56968. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56969. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  56970. }
  56971. if (sound.soundTrackId) {
  56972. if (sound.soundTrackId === -1) {
  56973. this._scene.mainSoundTrack.RemoveSound(sound);
  56974. }
  56975. else {
  56976. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  56977. }
  56978. }
  56979. this.soundCollection.push(sound);
  56980. sound.soundTrackId = this.id;
  56981. };
  56982. SoundTrack.prototype.RemoveSound = function (sound) {
  56983. var index = this.soundCollection.indexOf(sound);
  56984. if (index !== -1) {
  56985. this.soundCollection.splice(index, 1);
  56986. }
  56987. };
  56988. SoundTrack.prototype.setVolume = function (newVolume) {
  56989. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  56990. this._outputAudioNode.gain.value = newVolume;
  56991. }
  56992. };
  56993. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  56994. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  56995. for (var i = 0; i < this.soundCollection.length; i++) {
  56996. this.soundCollection[i].switchPanningModelToHRTF();
  56997. }
  56998. }
  56999. };
  57000. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  57001. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57002. for (var i = 0; i < this.soundCollection.length; i++) {
  57003. this.soundCollection[i].switchPanningModelToEqualPower();
  57004. }
  57005. }
  57006. };
  57007. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  57008. if (this._connectedAnalyser) {
  57009. this._connectedAnalyser.stopDebugCanvas();
  57010. }
  57011. this._connectedAnalyser = analyser;
  57012. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  57013. this._outputAudioNode.disconnect();
  57014. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  57015. }
  57016. };
  57017. return SoundTrack;
  57018. }());
  57019. BABYLON.SoundTrack = SoundTrack;
  57020. })(BABYLON || (BABYLON = {}));
  57021. //# sourceMappingURL=babylon.soundtrack.js.map
  57022. var BABYLON;
  57023. (function (BABYLON) {
  57024. var Analyser = /** @class */ (function () {
  57025. function Analyser(scene) {
  57026. this.SMOOTHING = 0.75;
  57027. this.FFT_SIZE = 512;
  57028. this.BARGRAPHAMPLITUDE = 256;
  57029. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  57030. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  57031. this._scene = scene;
  57032. this._audioEngine = BABYLON.Engine.audioEngine;
  57033. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  57034. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  57035. this._webAudioAnalyser.minDecibels = -140;
  57036. this._webAudioAnalyser.maxDecibels = 0;
  57037. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57038. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  57039. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  57040. }
  57041. }
  57042. Analyser.prototype.getFrequencyBinCount = function () {
  57043. if (this._audioEngine.canUseWebAudio) {
  57044. return this._webAudioAnalyser.frequencyBinCount;
  57045. }
  57046. else {
  57047. return 0;
  57048. }
  57049. };
  57050. Analyser.prototype.getByteFrequencyData = function () {
  57051. if (this._audioEngine.canUseWebAudio) {
  57052. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57053. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57054. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  57055. }
  57056. return this._byteFreqs;
  57057. };
  57058. Analyser.prototype.getByteTimeDomainData = function () {
  57059. if (this._audioEngine.canUseWebAudio) {
  57060. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57061. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57062. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  57063. }
  57064. return this._byteTime;
  57065. };
  57066. Analyser.prototype.getFloatFrequencyData = function () {
  57067. if (this._audioEngine.canUseWebAudio) {
  57068. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  57069. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  57070. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  57071. }
  57072. return this._floatFreqs;
  57073. };
  57074. Analyser.prototype.drawDebugCanvas = function () {
  57075. var _this = this;
  57076. if (this._audioEngine.canUseWebAudio) {
  57077. if (!this._debugCanvas) {
  57078. this._debugCanvas = document.createElement("canvas");
  57079. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  57080. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  57081. this._debugCanvas.style.position = "absolute";
  57082. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  57083. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  57084. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  57085. document.body.appendChild(this._debugCanvas);
  57086. this._registerFunc = function () {
  57087. _this.drawDebugCanvas();
  57088. };
  57089. this._scene.registerBeforeRender(this._registerFunc);
  57090. }
  57091. if (this._registerFunc && this._debugCanvasContext) {
  57092. var workingArray = this.getByteFrequencyData();
  57093. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  57094. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  57095. // Draw the frequency domain chart.
  57096. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  57097. var value = workingArray[i];
  57098. var percent = value / this.BARGRAPHAMPLITUDE;
  57099. var height = this.DEBUGCANVASSIZE.height * percent;
  57100. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  57101. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  57102. var hue = i / this.getFrequencyBinCount() * 360;
  57103. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  57104. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  57105. }
  57106. }
  57107. }
  57108. };
  57109. Analyser.prototype.stopDebugCanvas = function () {
  57110. if (this._debugCanvas) {
  57111. if (this._registerFunc) {
  57112. this._scene.unregisterBeforeRender(this._registerFunc);
  57113. this._registerFunc = null;
  57114. }
  57115. document.body.removeChild(this._debugCanvas);
  57116. this._debugCanvas = null;
  57117. this._debugCanvasContext = null;
  57118. }
  57119. };
  57120. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  57121. if (this._audioEngine.canUseWebAudio) {
  57122. inputAudioNode.connect(this._webAudioAnalyser);
  57123. this._webAudioAnalyser.connect(outputAudioNode);
  57124. }
  57125. };
  57126. Analyser.prototype.dispose = function () {
  57127. if (this._audioEngine.canUseWebAudio) {
  57128. this._webAudioAnalyser.disconnect();
  57129. }
  57130. };
  57131. return Analyser;
  57132. }());
  57133. BABYLON.Analyser = Analyser;
  57134. })(BABYLON || (BABYLON = {}));
  57135. //# sourceMappingURL=babylon.analyser.js.map
  57136. var BABYLON;
  57137. (function (BABYLON) {
  57138. var CubeTexture = /** @class */ (function (_super) {
  57139. __extends(CubeTexture, _super);
  57140. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  57141. if (extensions === void 0) { extensions = null; }
  57142. if (noMipmap === void 0) { noMipmap = false; }
  57143. if (files === void 0) { files = null; }
  57144. if (onLoad === void 0) { onLoad = null; }
  57145. if (onError === void 0) { onError = null; }
  57146. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  57147. if (prefiltered === void 0) { prefiltered = false; }
  57148. if (forcedExtension === void 0) { forcedExtension = null; }
  57149. var _this = _super.call(this, scene) || this;
  57150. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57151. /**
  57152. * Gets or sets the center of the bounding box associated with the cube texture
  57153. * It must define where the camera used to render the texture was set
  57154. */
  57155. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57156. _this.name = rootUrl;
  57157. _this.url = rootUrl;
  57158. _this._noMipmap = noMipmap;
  57159. _this.hasAlpha = false;
  57160. _this._format = format;
  57161. _this._prefiltered = prefiltered;
  57162. _this.isCube = true;
  57163. _this._textureMatrix = BABYLON.Matrix.Identity();
  57164. if (prefiltered) {
  57165. _this.gammaSpace = false;
  57166. }
  57167. if (!rootUrl && !files) {
  57168. return _this;
  57169. }
  57170. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  57171. var lastDot = rootUrl.lastIndexOf(".");
  57172. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  57173. var isDDS = (extension === ".dds");
  57174. if (!files) {
  57175. if (!isDDS && !extensions) {
  57176. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  57177. }
  57178. files = [];
  57179. if (extensions) {
  57180. for (var index = 0; index < extensions.length; index++) {
  57181. files.push(rootUrl + extensions[index]);
  57182. }
  57183. }
  57184. }
  57185. _this._files = files;
  57186. if (!_this._texture) {
  57187. if (!scene.useDelayedTextureLoading) {
  57188. if (prefiltered) {
  57189. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  57190. }
  57191. else {
  57192. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  57193. }
  57194. }
  57195. else {
  57196. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57197. }
  57198. }
  57199. else if (onLoad) {
  57200. if (_this._texture.isReady) {
  57201. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  57202. }
  57203. else {
  57204. _this._texture.onLoadedObservable.add(onLoad);
  57205. }
  57206. }
  57207. return _this;
  57208. }
  57209. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  57210. get: function () {
  57211. return this._boundingBoxSize;
  57212. },
  57213. /**
  57214. * Gets or sets the size of the bounding box associated with the cube texture
  57215. * When defined, the cubemap will switch to local mode
  57216. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57217. * @example https://www.babylonjs-playground.com/#RNASML
  57218. */
  57219. set: function (value) {
  57220. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57221. return;
  57222. }
  57223. this._boundingBoxSize = value;
  57224. var scene = this.getScene();
  57225. if (scene) {
  57226. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57227. }
  57228. },
  57229. enumerable: true,
  57230. configurable: true
  57231. });
  57232. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  57233. var rootUrlKey = "";
  57234. files.forEach(function (url) { return rootUrlKey += url; });
  57235. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  57236. };
  57237. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  57238. if (forcedExtension === void 0) { forcedExtension = null; }
  57239. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  57240. };
  57241. // Methods
  57242. CubeTexture.prototype.delayLoad = function () {
  57243. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  57244. return;
  57245. }
  57246. var scene = this.getScene();
  57247. if (!scene) {
  57248. return;
  57249. }
  57250. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  57251. this._texture = this._getFromCache(this.url, this._noMipmap);
  57252. if (!this._texture) {
  57253. if (this._prefiltered) {
  57254. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  57255. }
  57256. else {
  57257. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  57258. }
  57259. }
  57260. };
  57261. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  57262. return this._textureMatrix;
  57263. };
  57264. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  57265. this._textureMatrix = value;
  57266. };
  57267. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  57268. var texture = BABYLON.SerializationHelper.Parse(function () {
  57269. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  57270. }, parsedTexture, scene);
  57271. // Animations
  57272. if (parsedTexture.animations) {
  57273. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  57274. var parsedAnimation = parsedTexture.animations[animationIndex];
  57275. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57276. }
  57277. }
  57278. return texture;
  57279. };
  57280. CubeTexture.prototype.clone = function () {
  57281. var _this = this;
  57282. return BABYLON.SerializationHelper.Clone(function () {
  57283. var scene = _this.getScene();
  57284. if (!scene) {
  57285. return _this;
  57286. }
  57287. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  57288. }, this);
  57289. };
  57290. return CubeTexture;
  57291. }(BABYLON.BaseTexture));
  57292. BABYLON.CubeTexture = CubeTexture;
  57293. })(BABYLON || (BABYLON = {}));
  57294. //# sourceMappingURL=babylon.cubeTexture.js.map
  57295. var BABYLON;
  57296. (function (BABYLON) {
  57297. var RenderTargetTexture = /** @class */ (function (_super) {
  57298. __extends(RenderTargetTexture, _super);
  57299. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  57300. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  57301. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  57302. if (isCube === void 0) { isCube = false; }
  57303. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  57304. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  57305. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  57306. if (isMulti === void 0) { isMulti = false; }
  57307. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  57308. _this.isCube = isCube;
  57309. /**
  57310. * Use this list to define the list of mesh you want to render.
  57311. */
  57312. _this.renderList = new Array();
  57313. _this.renderParticles = true;
  57314. _this.renderSprites = false;
  57315. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  57316. _this.ignoreCameraViewport = false;
  57317. // Events
  57318. /**
  57319. * An event triggered when the texture is unbind.
  57320. * @type {BABYLON.Observable}
  57321. */
  57322. _this.onBeforeBindObservable = new BABYLON.Observable();
  57323. /**
  57324. * An event triggered when the texture is unbind.
  57325. * @type {BABYLON.Observable}
  57326. */
  57327. _this.onAfterUnbindObservable = new BABYLON.Observable();
  57328. /**
  57329. * An event triggered before rendering the texture
  57330. * @type {BABYLON.Observable}
  57331. */
  57332. _this.onBeforeRenderObservable = new BABYLON.Observable();
  57333. /**
  57334. * An event triggered after rendering the texture
  57335. * @type {BABYLON.Observable}
  57336. */
  57337. _this.onAfterRenderObservable = new BABYLON.Observable();
  57338. /**
  57339. * An event triggered after the texture clear
  57340. * @type {BABYLON.Observable}
  57341. */
  57342. _this.onClearObservable = new BABYLON.Observable();
  57343. _this._currentRefreshId = -1;
  57344. _this._refreshRate = 1;
  57345. _this._samples = 1;
  57346. /**
  57347. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  57348. * It must define where the camera used to render the texture is set
  57349. */
  57350. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  57351. scene = _this.getScene();
  57352. if (!scene) {
  57353. return _this;
  57354. }
  57355. _this._engine = scene.getEngine();
  57356. _this.name = name;
  57357. _this.isRenderTarget = true;
  57358. _this._initialSizeParameter = size;
  57359. _this._processSizeParameter(size);
  57360. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  57361. });
  57362. _this._generateMipMaps = generateMipMaps ? true : false;
  57363. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  57364. // Rendering groups
  57365. _this._renderingManager = new BABYLON.RenderingManager(scene);
  57366. if (isMulti) {
  57367. return _this;
  57368. }
  57369. _this._renderTargetOptions = {
  57370. generateMipMaps: generateMipMaps,
  57371. type: type,
  57372. samplingMode: samplingMode,
  57373. generateDepthBuffer: generateDepthBuffer,
  57374. generateStencilBuffer: generateStencilBuffer
  57375. };
  57376. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  57377. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57378. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  57379. }
  57380. if (isCube) {
  57381. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  57382. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  57383. _this._textureMatrix = BABYLON.Matrix.Identity();
  57384. }
  57385. else {
  57386. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  57387. }
  57388. return _this;
  57389. }
  57390. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  57391. get: function () {
  57392. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  57393. },
  57394. enumerable: true,
  57395. configurable: true
  57396. });
  57397. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  57398. get: function () {
  57399. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  57400. },
  57401. enumerable: true,
  57402. configurable: true
  57403. });
  57404. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  57405. get: function () {
  57406. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  57407. },
  57408. enumerable: true,
  57409. configurable: true
  57410. });
  57411. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  57412. set: function (callback) {
  57413. if (this._onAfterUnbindObserver) {
  57414. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  57415. }
  57416. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  57417. },
  57418. enumerable: true,
  57419. configurable: true
  57420. });
  57421. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  57422. set: function (callback) {
  57423. if (this._onBeforeRenderObserver) {
  57424. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  57425. }
  57426. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  57427. },
  57428. enumerable: true,
  57429. configurable: true
  57430. });
  57431. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  57432. set: function (callback) {
  57433. if (this._onAfterRenderObserver) {
  57434. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  57435. }
  57436. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  57437. },
  57438. enumerable: true,
  57439. configurable: true
  57440. });
  57441. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  57442. set: function (callback) {
  57443. if (this._onClearObserver) {
  57444. this.onClearObservable.remove(this._onClearObserver);
  57445. }
  57446. this._onClearObserver = this.onClearObservable.add(callback);
  57447. },
  57448. enumerable: true,
  57449. configurable: true
  57450. });
  57451. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  57452. get: function () {
  57453. return this._renderTargetOptions;
  57454. },
  57455. enumerable: true,
  57456. configurable: true
  57457. });
  57458. RenderTargetTexture.prototype._onRatioRescale = function () {
  57459. if (this._sizeRatio) {
  57460. this.resize(this._initialSizeParameter);
  57461. }
  57462. };
  57463. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  57464. get: function () {
  57465. return this._boundingBoxSize;
  57466. },
  57467. /**
  57468. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  57469. * When defined, the cubemap will switch to local mode
  57470. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  57471. * @example https://www.babylonjs-playground.com/#RNASML
  57472. */
  57473. set: function (value) {
  57474. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  57475. return;
  57476. }
  57477. this._boundingBoxSize = value;
  57478. var scene = this.getScene();
  57479. if (scene) {
  57480. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  57481. }
  57482. },
  57483. enumerable: true,
  57484. configurable: true
  57485. });
  57486. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  57487. if (size.ratio) {
  57488. this._sizeRatio = size.ratio;
  57489. this._size = {
  57490. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  57491. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  57492. };
  57493. }
  57494. else {
  57495. this._size = size;
  57496. }
  57497. };
  57498. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  57499. get: function () {
  57500. return this._samples;
  57501. },
  57502. set: function (value) {
  57503. if (this._samples === value) {
  57504. return;
  57505. }
  57506. var scene = this.getScene();
  57507. if (!scene) {
  57508. return;
  57509. }
  57510. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  57511. },
  57512. enumerable: true,
  57513. configurable: true
  57514. });
  57515. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  57516. this._currentRefreshId = -1;
  57517. };
  57518. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  57519. get: function () {
  57520. return this._refreshRate;
  57521. },
  57522. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  57523. set: function (value) {
  57524. this._refreshRate = value;
  57525. this.resetRefreshCounter();
  57526. },
  57527. enumerable: true,
  57528. configurable: true
  57529. });
  57530. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  57531. if (!this._postProcessManager) {
  57532. var scene = this.getScene();
  57533. if (!scene) {
  57534. return;
  57535. }
  57536. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  57537. this._postProcesses = new Array();
  57538. }
  57539. this._postProcesses.push(postProcess);
  57540. this._postProcesses[0].autoClear = false;
  57541. };
  57542. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  57543. if (!this._postProcesses) {
  57544. return;
  57545. }
  57546. if (dispose) {
  57547. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  57548. var postProcess = _a[_i];
  57549. postProcess.dispose();
  57550. }
  57551. }
  57552. this._postProcesses = [];
  57553. };
  57554. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  57555. if (!this._postProcesses) {
  57556. return;
  57557. }
  57558. var index = this._postProcesses.indexOf(postProcess);
  57559. if (index === -1) {
  57560. return;
  57561. }
  57562. this._postProcesses.splice(index, 1);
  57563. if (this._postProcesses.length > 0) {
  57564. this._postProcesses[0].autoClear = false;
  57565. }
  57566. };
  57567. RenderTargetTexture.prototype._shouldRender = function () {
  57568. if (this._currentRefreshId === -1) {
  57569. this._currentRefreshId = 1;
  57570. return true;
  57571. }
  57572. if (this.refreshRate === this._currentRefreshId) {
  57573. this._currentRefreshId = 1;
  57574. return true;
  57575. }
  57576. this._currentRefreshId++;
  57577. return false;
  57578. };
  57579. RenderTargetTexture.prototype.getRenderSize = function () {
  57580. if (this._size.width) {
  57581. return this._size.width;
  57582. }
  57583. return this._size;
  57584. };
  57585. RenderTargetTexture.prototype.getRenderWidth = function () {
  57586. if (this._size.width) {
  57587. return this._size.width;
  57588. }
  57589. return this._size;
  57590. };
  57591. RenderTargetTexture.prototype.getRenderHeight = function () {
  57592. if (this._size.width) {
  57593. return this._size.height;
  57594. }
  57595. return this._size;
  57596. };
  57597. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  57598. get: function () {
  57599. return true;
  57600. },
  57601. enumerable: true,
  57602. configurable: true
  57603. });
  57604. RenderTargetTexture.prototype.scale = function (ratio) {
  57605. var newSize = this.getRenderSize() * ratio;
  57606. this.resize(newSize);
  57607. };
  57608. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  57609. if (this.isCube) {
  57610. return this._textureMatrix;
  57611. }
  57612. return _super.prototype.getReflectionTextureMatrix.call(this);
  57613. };
  57614. RenderTargetTexture.prototype.resize = function (size) {
  57615. this.releaseInternalTexture();
  57616. var scene = this.getScene();
  57617. if (!scene) {
  57618. return;
  57619. }
  57620. this._processSizeParameter(size);
  57621. if (this.isCube) {
  57622. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  57623. }
  57624. else {
  57625. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  57626. }
  57627. };
  57628. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  57629. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  57630. if (dumpForDebug === void 0) { dumpForDebug = false; }
  57631. var scene = this.getScene();
  57632. if (!scene) {
  57633. return;
  57634. }
  57635. var engine = scene.getEngine();
  57636. if (this.useCameraPostProcesses !== undefined) {
  57637. useCameraPostProcess = this.useCameraPostProcesses;
  57638. }
  57639. if (this._waitingRenderList) {
  57640. this.renderList = [];
  57641. for (var index = 0; index < this._waitingRenderList.length; index++) {
  57642. var id = this._waitingRenderList[index];
  57643. var mesh_1 = scene.getMeshByID(id);
  57644. if (mesh_1) {
  57645. this.renderList.push(mesh_1);
  57646. }
  57647. }
  57648. delete this._waitingRenderList;
  57649. }
  57650. // Is predicate defined?
  57651. if (this.renderListPredicate) {
  57652. if (this.renderList) {
  57653. this.renderList.splice(0); // Clear previous renderList
  57654. }
  57655. else {
  57656. this.renderList = [];
  57657. }
  57658. var scene = this.getScene();
  57659. if (!scene) {
  57660. return;
  57661. }
  57662. var sceneMeshes = scene.meshes;
  57663. for (var index = 0; index < sceneMeshes.length; index++) {
  57664. var mesh = sceneMeshes[index];
  57665. if (this.renderListPredicate(mesh)) {
  57666. this.renderList.push(mesh);
  57667. }
  57668. }
  57669. }
  57670. this.onBeforeBindObservable.notifyObservers(this);
  57671. // Set custom projection.
  57672. // Needs to be before binding to prevent changing the aspect ratio.
  57673. var camera;
  57674. if (this.activeCamera) {
  57675. camera = this.activeCamera;
  57676. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57677. if (this.activeCamera !== scene.activeCamera) {
  57678. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  57679. }
  57680. }
  57681. else {
  57682. camera = scene.activeCamera;
  57683. if (camera) {
  57684. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  57685. }
  57686. }
  57687. // Prepare renderingManager
  57688. this._renderingManager.reset();
  57689. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  57690. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  57691. var sceneRenderId = scene.getRenderId();
  57692. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  57693. var mesh = currentRenderList[meshIndex];
  57694. if (mesh) {
  57695. if (!mesh.isReady()) {
  57696. // Reset _currentRefreshId
  57697. this.resetRefreshCounter();
  57698. continue;
  57699. }
  57700. mesh._preActivateForIntermediateRendering(sceneRenderId);
  57701. var isMasked = void 0;
  57702. if (!this.renderList && camera) {
  57703. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  57704. }
  57705. else {
  57706. isMasked = false;
  57707. }
  57708. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  57709. mesh._activate(sceneRenderId);
  57710. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  57711. var subMesh = mesh.subMeshes[subIndex];
  57712. scene._activeIndices.addCount(subMesh.indexCount, false);
  57713. this._renderingManager.dispatch(subMesh, mesh);
  57714. }
  57715. }
  57716. }
  57717. }
  57718. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  57719. var particleSystem = scene.particleSystems[particleIndex];
  57720. var emitter = particleSystem.emitter;
  57721. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  57722. continue;
  57723. }
  57724. if (currentRenderList.indexOf(emitter) >= 0) {
  57725. this._renderingManager.dispatchParticles(particleSystem);
  57726. }
  57727. }
  57728. if (this.isCube) {
  57729. for (var face = 0; face < 6; face++) {
  57730. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57731. scene.incrementRenderId();
  57732. scene.resetCachedMaterial();
  57733. }
  57734. }
  57735. else {
  57736. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  57737. }
  57738. this.onAfterUnbindObservable.notifyObservers(this);
  57739. if (scene.activeCamera) {
  57740. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  57741. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  57742. }
  57743. engine.setViewport(scene.activeCamera.viewport);
  57744. }
  57745. scene.resetCachedMaterial();
  57746. };
  57747. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  57748. var minimum = 128;
  57749. var x = renderDimension * scale;
  57750. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  57751. // Ensure we don't exceed the render dimension (while staying POT)
  57752. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  57753. };
  57754. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  57755. var _this = this;
  57756. if (!this._texture) {
  57757. return;
  57758. }
  57759. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  57760. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  57761. });
  57762. };
  57763. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  57764. var scene = this.getScene();
  57765. if (!scene) {
  57766. return;
  57767. }
  57768. var engine = scene.getEngine();
  57769. if (!this._texture) {
  57770. return;
  57771. }
  57772. // Bind
  57773. if (this._postProcessManager) {
  57774. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  57775. }
  57776. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  57777. if (this._texture) {
  57778. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  57779. }
  57780. }
  57781. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  57782. // Clear
  57783. if (this.onClearObservable.hasObservers()) {
  57784. this.onClearObservable.notifyObservers(engine);
  57785. }
  57786. else {
  57787. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  57788. }
  57789. if (!this._doNotChangeAspectRatio) {
  57790. scene.updateTransformMatrix(true);
  57791. }
  57792. // Render
  57793. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  57794. if (this._postProcessManager) {
  57795. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  57796. }
  57797. else if (useCameraPostProcess) {
  57798. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  57799. }
  57800. if (!this._doNotChangeAspectRatio) {
  57801. scene.updateTransformMatrix(true);
  57802. }
  57803. // Dump ?
  57804. if (dumpForDebug) {
  57805. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  57806. }
  57807. // Unbind
  57808. if (!this.isCube || faceIndex === 5) {
  57809. if (this.isCube) {
  57810. if (faceIndex === 5) {
  57811. engine.generateMipMapsForCubemap(this._texture);
  57812. }
  57813. }
  57814. this.unbindFrameBuffer(engine, faceIndex);
  57815. }
  57816. else {
  57817. this.onAfterRenderObservable.notifyObservers(faceIndex);
  57818. }
  57819. };
  57820. /**
  57821. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  57822. * This allowed control for front to back rendering or reversly depending of the special needs.
  57823. *
  57824. * @param renderingGroupId The rendering group id corresponding to its index
  57825. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  57826. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  57827. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  57828. */
  57829. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  57830. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  57831. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  57832. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  57833. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  57834. };
  57835. /**
  57836. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  57837. *
  57838. * @param renderingGroupId The rendering group id corresponding to its index
  57839. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  57840. */
  57841. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  57842. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  57843. };
  57844. RenderTargetTexture.prototype.clone = function () {
  57845. var textureSize = this.getSize();
  57846. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  57847. // Base texture
  57848. newTexture.hasAlpha = this.hasAlpha;
  57849. newTexture.level = this.level;
  57850. // RenderTarget Texture
  57851. newTexture.coordinatesMode = this.coordinatesMode;
  57852. if (this.renderList) {
  57853. newTexture.renderList = this.renderList.slice(0);
  57854. }
  57855. return newTexture;
  57856. };
  57857. RenderTargetTexture.prototype.serialize = function () {
  57858. if (!this.name) {
  57859. return null;
  57860. }
  57861. var serializationObject = _super.prototype.serialize.call(this);
  57862. serializationObject.renderTargetSize = this.getRenderSize();
  57863. serializationObject.renderList = [];
  57864. if (this.renderList) {
  57865. for (var index = 0; index < this.renderList.length; index++) {
  57866. serializationObject.renderList.push(this.renderList[index].id);
  57867. }
  57868. }
  57869. return serializationObject;
  57870. };
  57871. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  57872. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  57873. var objBuffer = this.getInternalTexture();
  57874. var scene = this.getScene();
  57875. if (objBuffer && scene) {
  57876. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  57877. }
  57878. };
  57879. RenderTargetTexture.prototype.dispose = function () {
  57880. if (this._postProcessManager) {
  57881. this._postProcessManager.dispose();
  57882. this._postProcessManager = null;
  57883. }
  57884. this.clearPostProcesses(true);
  57885. if (this._resizeObserver) {
  57886. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  57887. this._resizeObserver = null;
  57888. }
  57889. this.renderList = null;
  57890. // Remove from custom render targets
  57891. var scene = this.getScene();
  57892. if (!scene) {
  57893. return;
  57894. }
  57895. var index = scene.customRenderTargets.indexOf(this);
  57896. if (index >= 0) {
  57897. scene.customRenderTargets.splice(index, 1);
  57898. }
  57899. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  57900. var camera = _a[_i];
  57901. index = camera.customRenderTargets.indexOf(this);
  57902. if (index >= 0) {
  57903. camera.customRenderTargets.splice(index, 1);
  57904. }
  57905. }
  57906. _super.prototype.dispose.call(this);
  57907. };
  57908. RenderTargetTexture.prototype._rebuild = function () {
  57909. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  57910. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  57911. }
  57912. if (this._postProcessManager) {
  57913. this._postProcessManager._rebuild();
  57914. }
  57915. };
  57916. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  57917. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  57918. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  57919. return RenderTargetTexture;
  57920. }(BABYLON.Texture));
  57921. BABYLON.RenderTargetTexture = RenderTargetTexture;
  57922. })(BABYLON || (BABYLON = {}));
  57923. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  57924. var BABYLON;
  57925. (function (BABYLON) {
  57926. ;
  57927. var MultiRenderTarget = /** @class */ (function (_super) {
  57928. __extends(MultiRenderTarget, _super);
  57929. function MultiRenderTarget(name, size, count, scene, options) {
  57930. var _this = this;
  57931. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  57932. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  57933. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  57934. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  57935. _this._engine = scene.getEngine();
  57936. if (!_this.isSupported) {
  57937. _this.dispose();
  57938. return;
  57939. }
  57940. var types = [];
  57941. var samplingModes = [];
  57942. for (var i = 0; i < count; i++) {
  57943. if (options && options.types && options.types[i] !== undefined) {
  57944. types.push(options.types[i]);
  57945. }
  57946. else {
  57947. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  57948. }
  57949. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  57950. samplingModes.push(options.samplingModes[i]);
  57951. }
  57952. else {
  57953. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  57954. }
  57955. }
  57956. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  57957. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  57958. _this._size = size;
  57959. _this._multiRenderTargetOptions = {
  57960. samplingModes: samplingModes,
  57961. generateMipMaps: generateMipMaps,
  57962. generateDepthBuffer: generateDepthBuffer,
  57963. generateStencilBuffer: generateStencilBuffer,
  57964. generateDepthTexture: generateDepthTexture,
  57965. types: types,
  57966. textureCount: count
  57967. };
  57968. _this._createInternalTextures();
  57969. _this._createTextures();
  57970. return _this;
  57971. }
  57972. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  57973. get: function () {
  57974. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  57975. },
  57976. enumerable: true,
  57977. configurable: true
  57978. });
  57979. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  57980. get: function () {
  57981. return this._textures;
  57982. },
  57983. enumerable: true,
  57984. configurable: true
  57985. });
  57986. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  57987. get: function () {
  57988. return this._textures[this._textures.length - 1];
  57989. },
  57990. enumerable: true,
  57991. configurable: true
  57992. });
  57993. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  57994. set: function (wrap) {
  57995. if (this._textures) {
  57996. for (var i = 0; i < this._textures.length; i++) {
  57997. this._textures[i].wrapU = wrap;
  57998. }
  57999. }
  58000. },
  58001. enumerable: true,
  58002. configurable: true
  58003. });
  58004. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  58005. set: function (wrap) {
  58006. if (this._textures) {
  58007. for (var i = 0; i < this._textures.length; i++) {
  58008. this._textures[i].wrapV = wrap;
  58009. }
  58010. }
  58011. },
  58012. enumerable: true,
  58013. configurable: true
  58014. });
  58015. MultiRenderTarget.prototype._rebuild = function () {
  58016. this.releaseInternalTextures();
  58017. this._createInternalTextures();
  58018. for (var i = 0; i < this._internalTextures.length; i++) {
  58019. var texture = this._textures[i];
  58020. texture._texture = this._internalTextures[i];
  58021. }
  58022. // Keeps references to frame buffer and stencil/depth buffer
  58023. this._texture = this._internalTextures[0];
  58024. };
  58025. MultiRenderTarget.prototype._createInternalTextures = function () {
  58026. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  58027. };
  58028. MultiRenderTarget.prototype._createTextures = function () {
  58029. this._textures = [];
  58030. for (var i = 0; i < this._internalTextures.length; i++) {
  58031. var texture = new BABYLON.Texture(null, this.getScene());
  58032. texture._texture = this._internalTextures[i];
  58033. this._textures.push(texture);
  58034. }
  58035. // Keeps references to frame buffer and stencil/depth buffer
  58036. this._texture = this._internalTextures[0];
  58037. };
  58038. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  58039. get: function () {
  58040. return this._samples;
  58041. },
  58042. set: function (value) {
  58043. if (this._samples === value) {
  58044. return;
  58045. }
  58046. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  58047. },
  58048. enumerable: true,
  58049. configurable: true
  58050. });
  58051. MultiRenderTarget.prototype.resize = function (size) {
  58052. this.releaseInternalTextures();
  58053. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  58054. this._createInternalTextures();
  58055. };
  58056. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  58057. var _this = this;
  58058. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  58059. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  58060. });
  58061. };
  58062. MultiRenderTarget.prototype.dispose = function () {
  58063. this.releaseInternalTextures();
  58064. _super.prototype.dispose.call(this);
  58065. };
  58066. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  58067. if (!this._internalTextures) {
  58068. return;
  58069. }
  58070. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  58071. if (this._internalTextures[i] !== undefined) {
  58072. this._internalTextures[i].dispose();
  58073. this._internalTextures.splice(i, 1);
  58074. }
  58075. }
  58076. };
  58077. return MultiRenderTarget;
  58078. }(BABYLON.RenderTargetTexture));
  58079. BABYLON.MultiRenderTarget = MultiRenderTarget;
  58080. })(BABYLON || (BABYLON = {}));
  58081. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  58082. var BABYLON;
  58083. (function (BABYLON) {
  58084. var MirrorTexture = /** @class */ (function (_super) {
  58085. __extends(MirrorTexture, _super);
  58086. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  58087. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58088. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  58089. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58090. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  58091. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  58092. _this._transformMatrix = BABYLON.Matrix.Zero();
  58093. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  58094. _this._adaptiveBlurKernel = 0;
  58095. _this._blurKernelX = 0;
  58096. _this._blurKernelY = 0;
  58097. _this._blurRatio = 1.0;
  58098. _this.ignoreCameraViewport = true;
  58099. _this.onBeforeRenderObservable.add(function () {
  58100. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  58101. _this._savedViewMatrix = scene.getViewMatrix();
  58102. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  58103. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  58104. scene.clipPlane = _this.mirrorPlane;
  58105. scene.getEngine().cullBackFaces = false;
  58106. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  58107. });
  58108. _this.onAfterRenderObservable.add(function () {
  58109. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  58110. scene.getEngine().cullBackFaces = true;
  58111. scene._mirroredCameraPosition = null;
  58112. delete scene.clipPlane;
  58113. });
  58114. return _this;
  58115. }
  58116. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  58117. get: function () {
  58118. return this._blurRatio;
  58119. },
  58120. set: function (value) {
  58121. if (this._blurRatio === value) {
  58122. return;
  58123. }
  58124. this._blurRatio = value;
  58125. this._preparePostProcesses();
  58126. },
  58127. enumerable: true,
  58128. configurable: true
  58129. });
  58130. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  58131. set: function (value) {
  58132. this._adaptiveBlurKernel = value;
  58133. this._autoComputeBlurKernel();
  58134. },
  58135. enumerable: true,
  58136. configurable: true
  58137. });
  58138. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  58139. set: function (value) {
  58140. this.blurKernelX = value;
  58141. this.blurKernelY = value;
  58142. },
  58143. enumerable: true,
  58144. configurable: true
  58145. });
  58146. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  58147. get: function () {
  58148. return this._blurKernelX;
  58149. },
  58150. set: function (value) {
  58151. if (this._blurKernelX === value) {
  58152. return;
  58153. }
  58154. this._blurKernelX = value;
  58155. this._preparePostProcesses();
  58156. },
  58157. enumerable: true,
  58158. configurable: true
  58159. });
  58160. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  58161. get: function () {
  58162. return this._blurKernelY;
  58163. },
  58164. set: function (value) {
  58165. if (this._blurKernelY === value) {
  58166. return;
  58167. }
  58168. this._blurKernelY = value;
  58169. this._preparePostProcesses();
  58170. },
  58171. enumerable: true,
  58172. configurable: true
  58173. });
  58174. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  58175. var engine = this.getScene().getEngine();
  58176. var dw = this.getRenderWidth() / engine.getRenderWidth();
  58177. var dh = this.getRenderHeight() / engine.getRenderHeight();
  58178. this.blurKernelX = this._adaptiveBlurKernel * dw;
  58179. this.blurKernelY = this._adaptiveBlurKernel * dh;
  58180. };
  58181. MirrorTexture.prototype._onRatioRescale = function () {
  58182. if (this._sizeRatio) {
  58183. this.resize(this._initialSizeParameter);
  58184. if (!this._adaptiveBlurKernel) {
  58185. this._preparePostProcesses();
  58186. }
  58187. }
  58188. if (this._adaptiveBlurKernel) {
  58189. this._autoComputeBlurKernel();
  58190. }
  58191. };
  58192. MirrorTexture.prototype._preparePostProcesses = function () {
  58193. this.clearPostProcesses(true);
  58194. if (this._blurKernelX && this._blurKernelY) {
  58195. var engine = this.getScene().getEngine();
  58196. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  58197. 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);
  58198. this._blurX.autoClear = false;
  58199. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  58200. this._blurX.inputTexture = this._texture;
  58201. }
  58202. else {
  58203. this._blurX.alwaysForcePOT = true;
  58204. }
  58205. 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);
  58206. this._blurY.autoClear = false;
  58207. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  58208. this.addPostProcess(this._blurX);
  58209. this.addPostProcess(this._blurY);
  58210. }
  58211. else {
  58212. if (this._blurY) {
  58213. this.removePostProcess(this._blurY);
  58214. this._blurY.dispose();
  58215. this._blurY = null;
  58216. }
  58217. if (this._blurX) {
  58218. this.removePostProcess(this._blurX);
  58219. this._blurX.dispose();
  58220. this._blurX = null;
  58221. }
  58222. }
  58223. };
  58224. MirrorTexture.prototype.clone = function () {
  58225. var scene = this.getScene();
  58226. if (!scene) {
  58227. return this;
  58228. }
  58229. var textureSize = this.getSize();
  58230. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  58231. // Base texture
  58232. newTexture.hasAlpha = this.hasAlpha;
  58233. newTexture.level = this.level;
  58234. // Mirror Texture
  58235. newTexture.mirrorPlane = this.mirrorPlane.clone();
  58236. if (this.renderList) {
  58237. newTexture.renderList = this.renderList.slice(0);
  58238. }
  58239. return newTexture;
  58240. };
  58241. MirrorTexture.prototype.serialize = function () {
  58242. if (!this.name) {
  58243. return null;
  58244. }
  58245. var serializationObject = _super.prototype.serialize.call(this);
  58246. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  58247. return serializationObject;
  58248. };
  58249. return MirrorTexture;
  58250. }(BABYLON.RenderTargetTexture));
  58251. BABYLON.MirrorTexture = MirrorTexture;
  58252. })(BABYLON || (BABYLON = {}));
  58253. //# sourceMappingURL=babylon.mirrorTexture.js.map
  58254. var BABYLON;
  58255. (function (BABYLON) {
  58256. /**
  58257. * Creates a refraction texture used by refraction channel of the standard material.
  58258. * @param name the texture name
  58259. * @param size size of the underlying texture
  58260. * @param scene root scene
  58261. */
  58262. var RefractionTexture = /** @class */ (function (_super) {
  58263. __extends(RefractionTexture, _super);
  58264. function RefractionTexture(name, size, scene, generateMipMaps) {
  58265. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  58266. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  58267. _this.depth = 2.0;
  58268. _this.onBeforeRenderObservable.add(function () {
  58269. scene.clipPlane = _this.refractionPlane;
  58270. });
  58271. _this.onAfterRenderObservable.add(function () {
  58272. delete scene.clipPlane;
  58273. });
  58274. return _this;
  58275. }
  58276. RefractionTexture.prototype.clone = function () {
  58277. var scene = this.getScene();
  58278. if (!scene) {
  58279. return this;
  58280. }
  58281. var textureSize = this.getSize();
  58282. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  58283. // Base texture
  58284. newTexture.hasAlpha = this.hasAlpha;
  58285. newTexture.level = this.level;
  58286. // Refraction Texture
  58287. newTexture.refractionPlane = this.refractionPlane.clone();
  58288. if (this.renderList) {
  58289. newTexture.renderList = this.renderList.slice(0);
  58290. }
  58291. newTexture.depth = this.depth;
  58292. return newTexture;
  58293. };
  58294. RefractionTexture.prototype.serialize = function () {
  58295. if (!this.name) {
  58296. return null;
  58297. }
  58298. var serializationObject = _super.prototype.serialize.call(this);
  58299. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  58300. serializationObject.depth = this.depth;
  58301. return serializationObject;
  58302. };
  58303. return RefractionTexture;
  58304. }(BABYLON.RenderTargetTexture));
  58305. BABYLON.RefractionTexture = RefractionTexture;
  58306. })(BABYLON || (BABYLON = {}));
  58307. //# sourceMappingURL=babylon.refractionTexture.js.map
  58308. var BABYLON;
  58309. (function (BABYLON) {
  58310. var DynamicTexture = /** @class */ (function (_super) {
  58311. __extends(DynamicTexture, _super);
  58312. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  58313. if (scene === void 0) { scene = null; }
  58314. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58315. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58316. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  58317. _this.name = name;
  58318. _this._engine = _this.getScene().getEngine();
  58319. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58320. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58321. _this._generateMipMaps = generateMipMaps;
  58322. if (options.getContext) {
  58323. _this._canvas = options;
  58324. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58325. }
  58326. else {
  58327. _this._canvas = document.createElement("canvas");
  58328. if (options.width) {
  58329. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  58330. }
  58331. else {
  58332. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  58333. }
  58334. }
  58335. var textureSize = _this.getSize();
  58336. _this._canvas.width = textureSize.width;
  58337. _this._canvas.height = textureSize.height;
  58338. _this._context = _this._canvas.getContext("2d");
  58339. return _this;
  58340. }
  58341. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  58342. get: function () {
  58343. return true;
  58344. },
  58345. enumerable: true,
  58346. configurable: true
  58347. });
  58348. DynamicTexture.prototype._recreate = function (textureSize) {
  58349. this._canvas.width = textureSize.width;
  58350. this._canvas.height = textureSize.height;
  58351. this.releaseInternalTexture();
  58352. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  58353. };
  58354. DynamicTexture.prototype.scale = function (ratio) {
  58355. var textureSize = this.getSize();
  58356. textureSize.width *= ratio;
  58357. textureSize.height *= ratio;
  58358. this._recreate(textureSize);
  58359. };
  58360. DynamicTexture.prototype.scaleTo = function (width, height) {
  58361. var textureSize = this.getSize();
  58362. textureSize.width = width;
  58363. textureSize.height = height;
  58364. this._recreate(textureSize);
  58365. };
  58366. DynamicTexture.prototype.getContext = function () {
  58367. return this._context;
  58368. };
  58369. DynamicTexture.prototype.clear = function () {
  58370. var size = this.getSize();
  58371. this._context.fillRect(0, 0, size.width, size.height);
  58372. };
  58373. DynamicTexture.prototype.update = function (invertY) {
  58374. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  58375. };
  58376. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  58377. if (update === void 0) { update = true; }
  58378. var size = this.getSize();
  58379. if (clearColor) {
  58380. this._context.fillStyle = clearColor;
  58381. this._context.fillRect(0, 0, size.width, size.height);
  58382. }
  58383. this._context.font = font;
  58384. if (x === null || x === undefined) {
  58385. var textSize = this._context.measureText(text);
  58386. x = (size.width - textSize.width) / 2;
  58387. }
  58388. if (y === null || y === undefined) {
  58389. var fontSize = parseInt((font.replace(/\D/g, '')));
  58390. ;
  58391. y = (size.height / 2) + (fontSize / 3.65);
  58392. }
  58393. this._context.fillStyle = color;
  58394. this._context.fillText(text, x, y);
  58395. if (update) {
  58396. this.update(invertY);
  58397. }
  58398. };
  58399. DynamicTexture.prototype.clone = function () {
  58400. var scene = this.getScene();
  58401. if (!scene) {
  58402. return this;
  58403. }
  58404. var textureSize = this.getSize();
  58405. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  58406. // Base texture
  58407. newTexture.hasAlpha = this.hasAlpha;
  58408. newTexture.level = this.level;
  58409. // Dynamic Texture
  58410. newTexture.wrapU = this.wrapU;
  58411. newTexture.wrapV = this.wrapV;
  58412. return newTexture;
  58413. };
  58414. DynamicTexture.prototype._rebuild = function () {
  58415. this.update();
  58416. };
  58417. return DynamicTexture;
  58418. }(BABYLON.Texture));
  58419. BABYLON.DynamicTexture = DynamicTexture;
  58420. })(BABYLON || (BABYLON = {}));
  58421. //# sourceMappingURL=babylon.dynamicTexture.js.map
  58422. var BABYLON;
  58423. (function (BABYLON) {
  58424. var VideoTexture = /** @class */ (function (_super) {
  58425. __extends(VideoTexture, _super);
  58426. /**
  58427. * Creates a video texture.
  58428. * Sample : https://doc.babylonjs.com/how_to/video_texture
  58429. * @param {string | null} name optional name, will detect from video source, if not defined
  58430. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  58431. * @param {BABYLON.Scene} scene is obviously the current scene.
  58432. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  58433. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  58434. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  58435. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  58436. */
  58437. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  58438. if (generateMipMaps === void 0) { generateMipMaps = false; }
  58439. if (invertY === void 0) { invertY = false; }
  58440. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58441. if (settings === void 0) { settings = {
  58442. autoPlay: true,
  58443. loop: true,
  58444. autoUpdateTexture: true,
  58445. }; }
  58446. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58447. _this._createInternalTexture = function () {
  58448. if (_this._texture != null) {
  58449. return;
  58450. }
  58451. if (!_this._engine.needPOTTextures ||
  58452. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  58453. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  58454. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  58455. }
  58456. else {
  58457. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58458. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58459. _this._generateMipMaps = false;
  58460. }
  58461. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  58462. _this._texture.isReady = true;
  58463. _this._updateInternalTexture();
  58464. };
  58465. _this.reset = function () {
  58466. if (_this._texture == null) {
  58467. return;
  58468. }
  58469. _this._texture.dispose();
  58470. _this._texture = null;
  58471. };
  58472. _this._updateInternalTexture = function (e) {
  58473. if (_this._texture == null || !_this._texture.isReady) {
  58474. return;
  58475. }
  58476. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  58477. return;
  58478. }
  58479. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  58480. };
  58481. _this._engine = _this.getScene().getEngine();
  58482. _this._generateMipMaps = generateMipMaps;
  58483. _this._samplingMode = samplingMode;
  58484. _this.autoUpdateTexture = settings.autoUpdateTexture;
  58485. _this.name = name || _this._getName(src);
  58486. _this.video = _this._getVideo(src);
  58487. if (settings.autoPlay !== undefined) {
  58488. _this.video.autoplay = settings.autoPlay;
  58489. }
  58490. if (settings.loop !== undefined) {
  58491. _this.video.loop = settings.loop;
  58492. }
  58493. _this.video.addEventListener("canplay", _this._createInternalTexture);
  58494. _this.video.addEventListener("paused", _this._updateInternalTexture);
  58495. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  58496. _this.video.addEventListener("emptied", _this.reset);
  58497. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  58498. _this._createInternalTexture();
  58499. }
  58500. return _this;
  58501. }
  58502. VideoTexture.prototype._getName = function (src) {
  58503. if (src instanceof HTMLVideoElement) {
  58504. return src.currentSrc;
  58505. }
  58506. if (typeof src === "object") {
  58507. return src.toString();
  58508. }
  58509. return src;
  58510. };
  58511. ;
  58512. VideoTexture.prototype._getVideo = function (src) {
  58513. if (src instanceof HTMLVideoElement) {
  58514. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  58515. return src;
  58516. }
  58517. var video = document.createElement("video");
  58518. if (typeof src === "string") {
  58519. BABYLON.Tools.SetCorsBehavior(src, video);
  58520. video.src = src;
  58521. }
  58522. else {
  58523. BABYLON.Tools.SetCorsBehavior(src[0], video);
  58524. src.forEach(function (url) {
  58525. var source = document.createElement("source");
  58526. source.src = url;
  58527. video.appendChild(source);
  58528. });
  58529. }
  58530. return video;
  58531. };
  58532. ;
  58533. /**
  58534. * Internal method to initiate `update`.
  58535. */
  58536. VideoTexture.prototype._rebuild = function () {
  58537. this.update();
  58538. };
  58539. /**
  58540. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  58541. */
  58542. VideoTexture.prototype.update = function () {
  58543. if (!this.autoUpdateTexture) {
  58544. // Expecting user to call `updateTexture` manually
  58545. return;
  58546. }
  58547. this.updateTexture(true);
  58548. };
  58549. /**
  58550. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  58551. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  58552. */
  58553. VideoTexture.prototype.updateTexture = function (isVisible) {
  58554. if (!isVisible) {
  58555. return;
  58556. }
  58557. if (this.video.paused) {
  58558. return;
  58559. }
  58560. this._updateInternalTexture();
  58561. };
  58562. /**
  58563. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  58564. * @param url New url.
  58565. */
  58566. VideoTexture.prototype.updateURL = function (url) {
  58567. this.video.src = url;
  58568. };
  58569. VideoTexture.prototype.dispose = function () {
  58570. _super.prototype.dispose.call(this);
  58571. this.video.removeEventListener("canplay", this._createInternalTexture);
  58572. this.video.removeEventListener("paused", this._updateInternalTexture);
  58573. this.video.removeEventListener("seeked", this._updateInternalTexture);
  58574. this.video.removeEventListener("emptied", this.reset);
  58575. };
  58576. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  58577. var video = document.createElement("video");
  58578. var constraintsDeviceId;
  58579. if (constraints && constraints.deviceId) {
  58580. constraintsDeviceId = {
  58581. exact: constraints.deviceId,
  58582. };
  58583. }
  58584. navigator.getUserMedia =
  58585. navigator.getUserMedia ||
  58586. navigator.webkitGetUserMedia ||
  58587. navigator.mozGetUserMedia ||
  58588. navigator.msGetUserMedia;
  58589. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  58590. if (navigator.getUserMedia) {
  58591. navigator.getUserMedia({
  58592. video: {
  58593. deviceId: constraintsDeviceId,
  58594. width: {
  58595. min: (constraints && constraints.minWidth) || 256,
  58596. max: (constraints && constraints.maxWidth) || 640,
  58597. },
  58598. height: {
  58599. min: (constraints && constraints.minHeight) || 256,
  58600. max: (constraints && constraints.maxHeight) || 480,
  58601. },
  58602. },
  58603. }, function (stream) {
  58604. if (video.mozSrcObject !== undefined) {
  58605. // hack for Firefox < 19
  58606. video.mozSrcObject = stream;
  58607. }
  58608. else {
  58609. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  58610. }
  58611. video.play();
  58612. if (onReady) {
  58613. onReady(new VideoTexture("video", video, scene, true, true));
  58614. }
  58615. }, function (e) {
  58616. BABYLON.Tools.Error(e.name);
  58617. });
  58618. }
  58619. };
  58620. return VideoTexture;
  58621. }(BABYLON.Texture));
  58622. BABYLON.VideoTexture = VideoTexture;
  58623. })(BABYLON || (BABYLON = {}));
  58624. //# sourceMappingURL=babylon.videoTexture.js.map
  58625. var BABYLON;
  58626. (function (BABYLON) {
  58627. var RawTexture = /** @class */ (function (_super) {
  58628. __extends(RawTexture, _super);
  58629. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  58630. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58631. if (invertY === void 0) { invertY = false; }
  58632. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58633. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58634. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  58635. _this.format = format;
  58636. _this._engine = scene.getEngine();
  58637. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  58638. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58639. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58640. return _this;
  58641. }
  58642. RawTexture.prototype.update = function (data) {
  58643. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  58644. };
  58645. // Statics
  58646. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58647. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58648. if (invertY === void 0) { invertY = false; }
  58649. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58650. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  58651. };
  58652. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58653. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58654. if (invertY === void 0) { invertY = false; }
  58655. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58656. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58657. };
  58658. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  58659. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58660. if (invertY === void 0) { invertY = false; }
  58661. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58662. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  58663. };
  58664. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58665. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58666. if (invertY === void 0) { invertY = false; }
  58667. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58668. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58669. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  58670. };
  58671. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  58672. if (generateMipMaps === void 0) { generateMipMaps = true; }
  58673. if (invertY === void 0) { invertY = false; }
  58674. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58675. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58676. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  58677. };
  58678. return RawTexture;
  58679. }(BABYLON.Texture));
  58680. BABYLON.RawTexture = RawTexture;
  58681. })(BABYLON || (BABYLON = {}));
  58682. //# sourceMappingURL=babylon.rawTexture.js.map
  58683. var BABYLON;
  58684. (function (BABYLON) {
  58685. /**
  58686. * PostProcess can be used to apply a shader to a texture after it has been rendered
  58687. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  58688. */
  58689. var PostProcess = /** @class */ (function () {
  58690. /**
  58691. * Creates a new instance of @see PostProcess
  58692. * @param name The name of the PostProcess.
  58693. * @param fragmentUrl The url of the fragment shader to be used.
  58694. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  58695. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  58696. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  58697. * @param camera The camera to apply the render pass to.
  58698. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  58699. * @param engine The engine which the post process will be applied. (default: current engine)
  58700. * @param reusable If the post process can be reused on the same frame. (default: false)
  58701. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  58702. * @param textureType Type of textures used when performing the post process. (default: 0)
  58703. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  58704. * @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
  58705. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  58706. */
  58707. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  58708. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  58709. if (defines === void 0) { defines = null; }
  58710. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58711. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  58712. if (blockCompilation === void 0) { blockCompilation = false; }
  58713. this.name = name;
  58714. /**
  58715. * Width of the texture to apply the post process on
  58716. */
  58717. this.width = -1;
  58718. /**
  58719. * Height of the texture to apply the post process on
  58720. */
  58721. this.height = -1;
  58722. /**
  58723. * If the buffer needs to be cleared before applying the post process. (default: true)
  58724. * Should be set to false if shader will overwrite all previous pixels.
  58725. */
  58726. this.autoClear = true;
  58727. /**
  58728. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  58729. */
  58730. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  58731. /**
  58732. * Animations to be used for the post processing
  58733. */
  58734. this.animations = new Array();
  58735. /**
  58736. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  58737. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  58738. */
  58739. this.enablePixelPerfectMode = false;
  58740. /**
  58741. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  58742. */
  58743. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  58744. /**
  58745. * Force textures to be a power of two (default: false)
  58746. */
  58747. this.alwaysForcePOT = false;
  58748. /**
  58749. * Number of sample textures (default: 1)
  58750. */
  58751. this.samples = 1;
  58752. /**
  58753. * Modify the scale of the post process to be the same as the viewport (default: false)
  58754. */
  58755. this.adaptScaleToCurrentViewport = false;
  58756. this._reusable = false;
  58757. /**
  58758. * Smart array of input and output textures for the post process.
  58759. */
  58760. this._textures = new BABYLON.SmartArray(2);
  58761. /**
  58762. * The index in _textures that corresponds to the output texture.
  58763. */
  58764. this._currentRenderTextureInd = 0;
  58765. this._scaleRatio = new BABYLON.Vector2(1, 1);
  58766. this._texelSize = BABYLON.Vector2.Zero();
  58767. // Events
  58768. /**
  58769. * An event triggered when the postprocess is activated.
  58770. * @type {BABYLON.Observable}
  58771. */
  58772. this.onActivateObservable = new BABYLON.Observable();
  58773. /**
  58774. * An event triggered when the postprocess changes its size.
  58775. * @type {BABYLON.Observable}
  58776. */
  58777. this.onSizeChangedObservable = new BABYLON.Observable();
  58778. /**
  58779. * An event triggered when the postprocess applies its effect.
  58780. * @type {BABYLON.Observable}
  58781. */
  58782. this.onApplyObservable = new BABYLON.Observable();
  58783. /**
  58784. * An event triggered before rendering the postprocess
  58785. * @type {BABYLON.Observable}
  58786. */
  58787. this.onBeforeRenderObservable = new BABYLON.Observable();
  58788. /**
  58789. * An event triggered after rendering the postprocess
  58790. * @type {BABYLON.Observable}
  58791. */
  58792. this.onAfterRenderObservable = new BABYLON.Observable();
  58793. if (camera != null) {
  58794. this._camera = camera;
  58795. this._scene = camera.getScene();
  58796. camera.attachPostProcess(this);
  58797. this._engine = this._scene.getEngine();
  58798. this._scene.postProcesses.push(this);
  58799. }
  58800. else if (engine) {
  58801. this._engine = engine;
  58802. this._engine.postProcesses.push(this);
  58803. }
  58804. this._options = options;
  58805. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  58806. this._reusable = reusable || false;
  58807. this._textureType = textureType;
  58808. this._samplers = samplers || [];
  58809. this._samplers.push("textureSampler");
  58810. this._fragmentUrl = fragmentUrl;
  58811. this._vertexUrl = vertexUrl;
  58812. this._parameters = parameters || [];
  58813. this._parameters.push("scale");
  58814. this._indexParameters = indexParameters;
  58815. if (!blockCompilation) {
  58816. this.updateEffect(defines);
  58817. }
  58818. }
  58819. Object.defineProperty(PostProcess.prototype, "onActivate", {
  58820. /**
  58821. * A function that is added to the onActivateObservable
  58822. */
  58823. set: function (callback) {
  58824. if (this._onActivateObserver) {
  58825. this.onActivateObservable.remove(this._onActivateObserver);
  58826. }
  58827. if (callback) {
  58828. this._onActivateObserver = this.onActivateObservable.add(callback);
  58829. }
  58830. },
  58831. enumerable: true,
  58832. configurable: true
  58833. });
  58834. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  58835. /**
  58836. * A function that is added to the onSizeChangedObservable
  58837. */
  58838. set: function (callback) {
  58839. if (this._onSizeChangedObserver) {
  58840. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  58841. }
  58842. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  58843. },
  58844. enumerable: true,
  58845. configurable: true
  58846. });
  58847. Object.defineProperty(PostProcess.prototype, "onApply", {
  58848. /**
  58849. * A function that is added to the onApplyObservable
  58850. */
  58851. set: function (callback) {
  58852. if (this._onApplyObserver) {
  58853. this.onApplyObservable.remove(this._onApplyObserver);
  58854. }
  58855. this._onApplyObserver = this.onApplyObservable.add(callback);
  58856. },
  58857. enumerable: true,
  58858. configurable: true
  58859. });
  58860. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  58861. /**
  58862. * A function that is added to the onBeforeRenderObservable
  58863. */
  58864. set: function (callback) {
  58865. if (this._onBeforeRenderObserver) {
  58866. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58867. }
  58868. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58869. },
  58870. enumerable: true,
  58871. configurable: true
  58872. });
  58873. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  58874. /**
  58875. * A function that is added to the onAfterRenderObservable
  58876. */
  58877. set: function (callback) {
  58878. if (this._onAfterRenderObserver) {
  58879. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58880. }
  58881. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58882. },
  58883. enumerable: true,
  58884. configurable: true
  58885. });
  58886. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  58887. /**
  58888. * 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
  58889. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  58890. */
  58891. get: function () {
  58892. return this._textures.data[this._currentRenderTextureInd];
  58893. },
  58894. set: function (value) {
  58895. this._forcedOutputTexture = value;
  58896. },
  58897. enumerable: true,
  58898. configurable: true
  58899. });
  58900. /**
  58901. * Gets the camera which post process is applied to.
  58902. * @returns The camera the post process is applied to.
  58903. */
  58904. PostProcess.prototype.getCamera = function () {
  58905. return this._camera;
  58906. };
  58907. Object.defineProperty(PostProcess.prototype, "texelSize", {
  58908. /**
  58909. * Gets the texel size of the postprocess.
  58910. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  58911. */
  58912. get: function () {
  58913. if (this._shareOutputWithPostProcess) {
  58914. return this._shareOutputWithPostProcess.texelSize;
  58915. }
  58916. if (this._forcedOutputTexture) {
  58917. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  58918. }
  58919. return this._texelSize;
  58920. },
  58921. enumerable: true,
  58922. configurable: true
  58923. });
  58924. /**
  58925. * Gets the engine which this post process belongs to.
  58926. * @returns The engine the post process was enabled with.
  58927. */
  58928. PostProcess.prototype.getEngine = function () {
  58929. return this._engine;
  58930. };
  58931. /**
  58932. * The effect that is created when initializing the post process.
  58933. * @returns The created effect corrisponding the the postprocess.
  58934. */
  58935. PostProcess.prototype.getEffect = function () {
  58936. return this._effect;
  58937. };
  58938. /**
  58939. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  58940. * @param postProcess The post process to share the output with.
  58941. * @returns This post process.
  58942. */
  58943. PostProcess.prototype.shareOutputWith = function (postProcess) {
  58944. this._disposeTextures();
  58945. this._shareOutputWithPostProcess = postProcess;
  58946. return this;
  58947. };
  58948. /**
  58949. * Updates the effect with the current post process compile time values and recompiles the shader.
  58950. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  58951. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  58952. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  58953. * @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
  58954. * @param onCompiled Called when the shader has been compiled.
  58955. * @param onError Called if there is an error when compiling a shader.
  58956. */
  58957. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  58958. if (defines === void 0) { defines = null; }
  58959. if (uniforms === void 0) { uniforms = null; }
  58960. if (samplers === void 0) { samplers = null; }
  58961. 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);
  58962. };
  58963. /**
  58964. * The post process is reusable if it can be used multiple times within one frame.
  58965. * @returns If the post process is reusable
  58966. */
  58967. PostProcess.prototype.isReusable = function () {
  58968. return this._reusable;
  58969. };
  58970. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  58971. PostProcess.prototype.markTextureDirty = function () {
  58972. this.width = -1;
  58973. };
  58974. /**
  58975. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  58976. * 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.
  58977. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  58978. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  58979. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  58980. */
  58981. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  58982. var _this = this;
  58983. if (sourceTexture === void 0) { sourceTexture = null; }
  58984. camera = camera || this._camera;
  58985. var scene = camera.getScene();
  58986. var engine = scene.getEngine();
  58987. var maxSize = engine.getCaps().maxTextureSize;
  58988. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  58989. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  58990. var desiredWidth = (this._options.width || requiredWidth);
  58991. var desiredHeight = this._options.height || requiredHeight;
  58992. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  58993. if (this.adaptScaleToCurrentViewport) {
  58994. var currentViewport = engine.currentViewport;
  58995. if (currentViewport) {
  58996. desiredWidth *= currentViewport.width;
  58997. desiredHeight *= currentViewport.height;
  58998. }
  58999. }
  59000. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  59001. if (!this._options.width) {
  59002. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  59003. }
  59004. if (!this._options.height) {
  59005. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  59006. }
  59007. }
  59008. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  59009. if (this._textures.length > 0) {
  59010. for (var i = 0; i < this._textures.length; i++) {
  59011. this._engine._releaseTexture(this._textures.data[i]);
  59012. }
  59013. this._textures.reset();
  59014. }
  59015. this.width = desiredWidth;
  59016. this.height = desiredHeight;
  59017. var textureSize = { width: this.width, height: this.height };
  59018. var textureOptions = {
  59019. generateMipMaps: false,
  59020. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  59021. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  59022. samplingMode: this.renderTargetSamplingMode,
  59023. type: this._textureType
  59024. };
  59025. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59026. if (this._reusable) {
  59027. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  59028. }
  59029. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  59030. this.onSizeChangedObservable.notifyObservers(this);
  59031. }
  59032. this._textures.forEach(function (texture) {
  59033. if (texture.samples !== _this.samples) {
  59034. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  59035. }
  59036. });
  59037. }
  59038. var target;
  59039. if (this._shareOutputWithPostProcess) {
  59040. target = this._shareOutputWithPostProcess.inputTexture;
  59041. }
  59042. else if (this._forcedOutputTexture) {
  59043. target = this._forcedOutputTexture;
  59044. this.width = this._forcedOutputTexture.width;
  59045. this.height = this._forcedOutputTexture.height;
  59046. }
  59047. else {
  59048. target = this.inputTexture;
  59049. }
  59050. // Bind the input of this post process to be used as the output of the previous post process.
  59051. if (this.enablePixelPerfectMode) {
  59052. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  59053. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  59054. }
  59055. else {
  59056. this._scaleRatio.copyFromFloats(1, 1);
  59057. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  59058. }
  59059. this.onActivateObservable.notifyObservers(camera);
  59060. // Clear
  59061. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  59062. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  59063. }
  59064. if (this._reusable) {
  59065. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  59066. }
  59067. };
  59068. Object.defineProperty(PostProcess.prototype, "isSupported", {
  59069. /**
  59070. * If the post process is supported.
  59071. */
  59072. get: function () {
  59073. return this._effect.isSupported;
  59074. },
  59075. enumerable: true,
  59076. configurable: true
  59077. });
  59078. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  59079. /**
  59080. * The aspect ratio of the output texture.
  59081. */
  59082. get: function () {
  59083. if (this._shareOutputWithPostProcess) {
  59084. return this._shareOutputWithPostProcess.aspectRatio;
  59085. }
  59086. if (this._forcedOutputTexture) {
  59087. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  59088. }
  59089. return this.width / this.height;
  59090. },
  59091. enumerable: true,
  59092. configurable: true
  59093. });
  59094. /**
  59095. * Get a value indicating if the post-process is ready to be used
  59096. * @returns true if the post-process is ready (shader is compiled)
  59097. */
  59098. PostProcess.prototype.isReady = function () {
  59099. return this._effect && this._effect.isReady();
  59100. };
  59101. /**
  59102. * Binds all textures and uniforms to the shader, this will be run on every pass.
  59103. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  59104. */
  59105. PostProcess.prototype.apply = function () {
  59106. // Check
  59107. if (!this._effect || !this._effect.isReady())
  59108. return null;
  59109. // States
  59110. this._engine.enableEffect(this._effect);
  59111. this._engine.setState(false);
  59112. this._engine.setDepthBuffer(false);
  59113. this._engine.setDepthWrite(false);
  59114. // Alpha
  59115. this._engine.setAlphaMode(this.alphaMode);
  59116. if (this.alphaConstants) {
  59117. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  59118. }
  59119. // Bind the output texture of the preivous post process as the input to this post process.
  59120. var source;
  59121. if (this._shareOutputWithPostProcess) {
  59122. source = this._shareOutputWithPostProcess.inputTexture;
  59123. }
  59124. else if (this._forcedOutputTexture) {
  59125. source = this._forcedOutputTexture;
  59126. }
  59127. else {
  59128. source = this.inputTexture;
  59129. }
  59130. this._effect._bindTexture("textureSampler", source);
  59131. // Parameters
  59132. this._effect.setVector2("scale", this._scaleRatio);
  59133. this.onApplyObservable.notifyObservers(this._effect);
  59134. return this._effect;
  59135. };
  59136. PostProcess.prototype._disposeTextures = function () {
  59137. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  59138. return;
  59139. }
  59140. if (this._textures.length > 0) {
  59141. for (var i = 0; i < this._textures.length; i++) {
  59142. this._engine._releaseTexture(this._textures.data[i]);
  59143. }
  59144. }
  59145. this._textures.dispose();
  59146. };
  59147. /**
  59148. * Disposes the post process.
  59149. * @param camera The camera to dispose the post process on.
  59150. */
  59151. PostProcess.prototype.dispose = function (camera) {
  59152. camera = camera || this._camera;
  59153. this._disposeTextures();
  59154. if (this._scene) {
  59155. var index_1 = this._scene.postProcesses.indexOf(this);
  59156. if (index_1 !== -1) {
  59157. this._scene.postProcesses.splice(index_1, 1);
  59158. }
  59159. }
  59160. else {
  59161. var index_2 = this._engine.postProcesses.indexOf(this);
  59162. if (index_2 !== -1) {
  59163. this._engine.postProcesses.splice(index_2, 1);
  59164. }
  59165. }
  59166. if (!camera) {
  59167. return;
  59168. }
  59169. camera.detachPostProcess(this);
  59170. var index = camera._postProcesses.indexOf(this);
  59171. if (index === 0 && camera._postProcesses.length > 0) {
  59172. this._camera._postProcesses[0].markTextureDirty();
  59173. }
  59174. this.onActivateObservable.clear();
  59175. this.onAfterRenderObservable.clear();
  59176. this.onApplyObservable.clear();
  59177. this.onBeforeRenderObservable.clear();
  59178. this.onSizeChangedObservable.clear();
  59179. };
  59180. return PostProcess;
  59181. }());
  59182. BABYLON.PostProcess = PostProcess;
  59183. })(BABYLON || (BABYLON = {}));
  59184. //# sourceMappingURL=babylon.postProcess.js.map
  59185. var BABYLON;
  59186. (function (BABYLON) {
  59187. var PassPostProcess = /** @class */ (function (_super) {
  59188. __extends(PassPostProcess, _super);
  59189. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  59190. if (camera === void 0) { camera = null; }
  59191. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59192. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType) || this;
  59193. }
  59194. return PassPostProcess;
  59195. }(BABYLON.PostProcess));
  59196. BABYLON.PassPostProcess = PassPostProcess;
  59197. })(BABYLON || (BABYLON = {}));
  59198. //# sourceMappingURL=babylon.passPostProcess.js.map
  59199. var __assign = (this && this.__assign) || Object.assign || function(t) {
  59200. for (var s, i = 1, n = arguments.length; i < n; i++) {
  59201. s = arguments[i];
  59202. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  59203. t[p] = s[p];
  59204. }
  59205. return t;
  59206. };
  59207. var BABYLON;
  59208. (function (BABYLON) {
  59209. /**
  59210. * Default implementation of @see IShadowGenerator.
  59211. * This is the main object responsible of generating shadows in the framework.
  59212. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  59213. */
  59214. var ShadowGenerator = /** @class */ (function () {
  59215. /**
  59216. * Creates a ShadowGenerator object.
  59217. * A ShadowGenerator is the required tool to use the shadows.
  59218. * Each light casting shadows needs to use its own ShadowGenerator.
  59219. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  59220. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  59221. * @param light The light object generating the shadows.
  59222. * @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.
  59223. */
  59224. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  59225. this._bias = 0.00005;
  59226. this._blurBoxOffset = 1;
  59227. this._blurScale = 2;
  59228. this._blurKernel = 1;
  59229. this._useKernelBlur = false;
  59230. this._filter = ShadowGenerator.FILTER_NONE;
  59231. this._darkness = 0;
  59232. this._transparencyShadow = false;
  59233. /**
  59234. * Controls the extent to which the shadows fade out at the edge of the frustum
  59235. * Used only by directionals and spots
  59236. */
  59237. this.frustumEdgeFalloff = 0;
  59238. /**
  59239. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  59240. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  59241. * It might on the other hand introduce peter panning.
  59242. */
  59243. this.forceBackFacesOnly = false;
  59244. this._lightDirection = BABYLON.Vector3.Zero();
  59245. this._viewMatrix = BABYLON.Matrix.Zero();
  59246. this._projectionMatrix = BABYLON.Matrix.Zero();
  59247. this._transformMatrix = BABYLON.Matrix.Zero();
  59248. this._currentFaceIndex = 0;
  59249. this._currentFaceIndexCache = 0;
  59250. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  59251. this._mapSize = mapSize;
  59252. this._light = light;
  59253. this._scene = light.getScene();
  59254. light._shadowGenerator = this;
  59255. // Texture type fallback from float to int if not supported.
  59256. var caps = this._scene.getEngine().getCaps();
  59257. if (!useFullFloatFirst) {
  59258. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59259. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59260. }
  59261. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59262. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59263. }
  59264. else {
  59265. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59266. }
  59267. }
  59268. else {
  59269. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  59270. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  59271. }
  59272. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  59273. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59274. }
  59275. else {
  59276. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  59277. }
  59278. }
  59279. this._initializeGenerator();
  59280. }
  59281. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  59282. /**
  59283. * Shadow generator mode None: no filtering applied.
  59284. */
  59285. get: function () {
  59286. return ShadowGenerator._FILTER_NONE;
  59287. },
  59288. enumerable: true,
  59289. configurable: true
  59290. });
  59291. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  59292. /**
  59293. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  59294. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  59295. */
  59296. get: function () {
  59297. return ShadowGenerator._FILTER_POISSONSAMPLING;
  59298. },
  59299. enumerable: true,
  59300. configurable: true
  59301. });
  59302. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  59303. /**
  59304. * Shadow generator mode ESM: Exponential Shadow Mapping.
  59305. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59306. */
  59307. get: function () {
  59308. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  59309. },
  59310. enumerable: true,
  59311. configurable: true
  59312. });
  59313. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  59314. /**
  59315. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  59316. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59317. */
  59318. get: function () {
  59319. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  59320. },
  59321. enumerable: true,
  59322. configurable: true
  59323. });
  59324. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  59325. /**
  59326. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  59327. * edge artifacts on steep falloff.
  59328. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59329. */
  59330. get: function () {
  59331. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59332. },
  59333. enumerable: true,
  59334. configurable: true
  59335. });
  59336. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  59337. /**
  59338. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  59339. * edge artifacts on steep falloff.
  59340. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  59341. */
  59342. get: function () {
  59343. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59344. },
  59345. enumerable: true,
  59346. configurable: true
  59347. });
  59348. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  59349. /**
  59350. * Gets the bias: offset applied on the depth preventing acnea.
  59351. */
  59352. get: function () {
  59353. return this._bias;
  59354. },
  59355. /**
  59356. * Sets the bias: offset applied on the depth preventing acnea.
  59357. */
  59358. set: function (bias) {
  59359. this._bias = bias;
  59360. },
  59361. enumerable: true,
  59362. configurable: true
  59363. });
  59364. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  59365. /**
  59366. * Gets the blur box offset: offset applied during the blur pass.
  59367. * Only usefull if useKernelBlur = false
  59368. */
  59369. get: function () {
  59370. return this._blurBoxOffset;
  59371. },
  59372. /**
  59373. * Sets the blur box offset: offset applied during the blur pass.
  59374. * Only usefull if useKernelBlur = false
  59375. */
  59376. set: function (value) {
  59377. if (this._blurBoxOffset === value) {
  59378. return;
  59379. }
  59380. this._blurBoxOffset = value;
  59381. this._disposeBlurPostProcesses();
  59382. },
  59383. enumerable: true,
  59384. configurable: true
  59385. });
  59386. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  59387. /**
  59388. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  59389. * 2 means half of the size.
  59390. */
  59391. get: function () {
  59392. return this._blurScale;
  59393. },
  59394. /**
  59395. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  59396. * 2 means half of the size.
  59397. */
  59398. set: function (value) {
  59399. if (this._blurScale === value) {
  59400. return;
  59401. }
  59402. this._blurScale = value;
  59403. this._disposeBlurPostProcesses();
  59404. },
  59405. enumerable: true,
  59406. configurable: true
  59407. });
  59408. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  59409. /**
  59410. * Gets the blur kernel: kernel size of the blur pass.
  59411. * Only usefull if useKernelBlur = true
  59412. */
  59413. get: function () {
  59414. return this._blurKernel;
  59415. },
  59416. /**
  59417. * Sets the blur kernel: kernel size of the blur pass.
  59418. * Only usefull if useKernelBlur = true
  59419. */
  59420. set: function (value) {
  59421. if (this._blurKernel === value) {
  59422. return;
  59423. }
  59424. this._blurKernel = value;
  59425. this._disposeBlurPostProcesses();
  59426. },
  59427. enumerable: true,
  59428. configurable: true
  59429. });
  59430. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  59431. /**
  59432. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  59433. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59434. */
  59435. get: function () {
  59436. return this._useKernelBlur;
  59437. },
  59438. /**
  59439. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  59440. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  59441. */
  59442. set: function (value) {
  59443. if (this._useKernelBlur === value) {
  59444. return;
  59445. }
  59446. this._useKernelBlur = value;
  59447. this._disposeBlurPostProcesses();
  59448. },
  59449. enumerable: true,
  59450. configurable: true
  59451. });
  59452. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  59453. /**
  59454. * Gets the depth scale used in ESM mode.
  59455. */
  59456. get: function () {
  59457. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  59458. },
  59459. /**
  59460. * Sets the depth scale used in ESM mode.
  59461. * This can override the scale stored on the light.
  59462. */
  59463. set: function (value) {
  59464. this._depthScale = value;
  59465. },
  59466. enumerable: true,
  59467. configurable: true
  59468. });
  59469. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  59470. /**
  59471. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  59472. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59473. */
  59474. get: function () {
  59475. return this._filter;
  59476. },
  59477. /**
  59478. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  59479. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  59480. */
  59481. set: function (value) {
  59482. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  59483. if (this._light.needCube()) {
  59484. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59485. this.useExponentialShadowMap = true;
  59486. return;
  59487. }
  59488. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59489. this.useCloseExponentialShadowMap = true;
  59490. return;
  59491. }
  59492. }
  59493. if (this._filter === value) {
  59494. return;
  59495. }
  59496. this._filter = value;
  59497. this._disposeBlurPostProcesses();
  59498. this._applyFilterValues();
  59499. this._light._markMeshesAsLightDirty();
  59500. },
  59501. enumerable: true,
  59502. configurable: true
  59503. });
  59504. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  59505. /**
  59506. * Gets if the current filter is set to Poisson Sampling aka PCF.
  59507. */
  59508. get: function () {
  59509. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  59510. },
  59511. /**
  59512. * Sets the current filter to Poisson Sampling aka PCF.
  59513. */
  59514. set: function (value) {
  59515. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  59516. return;
  59517. }
  59518. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  59519. },
  59520. enumerable: true,
  59521. configurable: true
  59522. });
  59523. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  59524. /**
  59525. * Gets if the current filter is set to VSM.
  59526. * DEPRECATED. Should use useExponentialShadowMap instead.
  59527. */
  59528. get: function () {
  59529. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59530. return this.useExponentialShadowMap;
  59531. },
  59532. /**
  59533. * Sets the current filter is to VSM.
  59534. * DEPRECATED. Should use useExponentialShadowMap instead.
  59535. */
  59536. set: function (value) {
  59537. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  59538. this.useExponentialShadowMap = value;
  59539. },
  59540. enumerable: true,
  59541. configurable: true
  59542. });
  59543. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  59544. /**
  59545. * Gets if the current filter is set to blurred VSM.
  59546. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59547. */
  59548. get: function () {
  59549. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59550. return this.useBlurExponentialShadowMap;
  59551. },
  59552. /**
  59553. * Sets the current filter is to blurred VSM.
  59554. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  59555. */
  59556. set: function (value) {
  59557. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  59558. this.useBlurExponentialShadowMap = value;
  59559. },
  59560. enumerable: true,
  59561. configurable: true
  59562. });
  59563. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  59564. /**
  59565. * Gets if the current filter is set to ESM.
  59566. */
  59567. get: function () {
  59568. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  59569. },
  59570. /**
  59571. * Sets the current filter is to ESM.
  59572. */
  59573. set: function (value) {
  59574. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  59575. return;
  59576. }
  59577. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59578. },
  59579. enumerable: true,
  59580. configurable: true
  59581. });
  59582. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  59583. /**
  59584. * Gets if the current filter is set to filtered ESM.
  59585. */
  59586. get: function () {
  59587. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  59588. },
  59589. /**
  59590. * Gets if the current filter is set to filtered ESM.
  59591. */
  59592. set: function (value) {
  59593. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  59594. return;
  59595. }
  59596. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59597. },
  59598. enumerable: true,
  59599. configurable: true
  59600. });
  59601. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  59602. /**
  59603. * Gets if the current filter is set to "close ESM" (using the inverse of the
  59604. * exponential to prevent steep falloff artifacts).
  59605. */
  59606. get: function () {
  59607. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  59608. },
  59609. /**
  59610. * Sets the current filter to "close ESM" (using the inverse of the
  59611. * exponential to prevent steep falloff artifacts).
  59612. */
  59613. set: function (value) {
  59614. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  59615. return;
  59616. }
  59617. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59618. },
  59619. enumerable: true,
  59620. configurable: true
  59621. });
  59622. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  59623. /**
  59624. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  59625. * exponential to prevent steep falloff artifacts).
  59626. */
  59627. get: function () {
  59628. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  59629. },
  59630. /**
  59631. * Sets the current filter to fileterd "close ESM" (using the inverse of the
  59632. * exponential to prevent steep falloff artifacts).
  59633. */
  59634. set: function (value) {
  59635. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  59636. return;
  59637. }
  59638. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  59639. },
  59640. enumerable: true,
  59641. configurable: true
  59642. });
  59643. /**
  59644. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  59645. * 0 means strongest and 1 would means no shadow.
  59646. * @returns the darkness.
  59647. */
  59648. ShadowGenerator.prototype.getDarkness = function () {
  59649. return this._darkness;
  59650. };
  59651. /**
  59652. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  59653. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  59654. * @returns the shadow generator allowing fluent coding.
  59655. */
  59656. ShadowGenerator.prototype.setDarkness = function (darkness) {
  59657. if (darkness >= 1.0)
  59658. this._darkness = 1.0;
  59659. else if (darkness <= 0.0)
  59660. this._darkness = 0.0;
  59661. else
  59662. this._darkness = darkness;
  59663. return this;
  59664. };
  59665. /**
  59666. * Sets the ability to have transparent shadow (boolean).
  59667. * @param transparent True if transparent else False
  59668. * @returns the shadow generator allowing fluent coding
  59669. */
  59670. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  59671. this._transparencyShadow = transparent;
  59672. return this;
  59673. };
  59674. /**
  59675. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  59676. * @returns The render target texture if present otherwise, null
  59677. */
  59678. ShadowGenerator.prototype.getShadowMap = function () {
  59679. return this._shadowMap;
  59680. };
  59681. /**
  59682. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  59683. * @returns The render target texture if the shadow map is present otherwise, null
  59684. */
  59685. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  59686. if (this._shadowMap2) {
  59687. return this._shadowMap2;
  59688. }
  59689. return this._shadowMap;
  59690. };
  59691. /**
  59692. * Helper function to add a mesh and its descendants to the list of shadow casters.
  59693. * @param mesh Mesh to add
  59694. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  59695. * @returns the Shadow Generator itself
  59696. */
  59697. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  59698. if (includeDescendants === void 0) { includeDescendants = true; }
  59699. if (!this._shadowMap) {
  59700. return this;
  59701. }
  59702. if (!this._shadowMap.renderList) {
  59703. this._shadowMap.renderList = [];
  59704. }
  59705. this._shadowMap.renderList.push(mesh);
  59706. if (includeDescendants) {
  59707. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  59708. }
  59709. return this;
  59710. var _a;
  59711. };
  59712. /**
  59713. * Helper function to remove a mesh and its descendants from the list of shadow casters
  59714. * @param mesh Mesh to remove
  59715. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  59716. * @returns the Shadow Generator itself
  59717. */
  59718. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  59719. if (includeDescendants === void 0) { includeDescendants = true; }
  59720. if (!this._shadowMap || !this._shadowMap.renderList) {
  59721. return this;
  59722. }
  59723. var index = this._shadowMap.renderList.indexOf(mesh);
  59724. if (index !== -1) {
  59725. this._shadowMap.renderList.splice(index, 1);
  59726. }
  59727. if (includeDescendants) {
  59728. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  59729. var child = _a[_i];
  59730. this.removeShadowCaster(child);
  59731. }
  59732. }
  59733. return this;
  59734. };
  59735. /**
  59736. * Returns the associated light object.
  59737. * @returns the light generating the shadow
  59738. */
  59739. ShadowGenerator.prototype.getLight = function () {
  59740. return this._light;
  59741. };
  59742. ShadowGenerator.prototype._initializeGenerator = function () {
  59743. this._light._markMeshesAsLightDirty();
  59744. this._initializeShadowMap();
  59745. };
  59746. ShadowGenerator.prototype._initializeShadowMap = function () {
  59747. var _this = this;
  59748. // Render target
  59749. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  59750. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59751. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59752. this._shadowMap.anisotropicFilteringLevel = 1;
  59753. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59754. this._shadowMap.renderParticles = false;
  59755. this._shadowMap.ignoreCameraViewport = true;
  59756. // Record Face Index before render.
  59757. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  59758. _this._currentFaceIndex = faceIndex;
  59759. });
  59760. // Custom render function.
  59761. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  59762. // Blur if required afer render.
  59763. this._shadowMap.onAfterUnbindObservable.add(function () {
  59764. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  59765. return;
  59766. }
  59767. var shadowMap = _this.getShadowMapForRendering();
  59768. if (shadowMap) {
  59769. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  59770. }
  59771. });
  59772. // Clear according to the chosen filter.
  59773. this._shadowMap.onClearObservable.add(function (engine) {
  59774. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  59775. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  59776. }
  59777. else {
  59778. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  59779. }
  59780. });
  59781. };
  59782. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  59783. var _this = this;
  59784. var engine = this._scene.getEngine();
  59785. var targetSize = this._mapSize / this.blurScale;
  59786. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  59787. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  59788. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59789. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59790. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59791. }
  59792. if (this.useKernelBlur) {
  59793. 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);
  59794. this._kernelBlurXPostprocess.width = targetSize;
  59795. this._kernelBlurXPostprocess.height = targetSize;
  59796. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  59797. effect.setTexture("textureSampler", _this._shadowMap);
  59798. });
  59799. 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);
  59800. this._kernelBlurXPostprocess.autoClear = false;
  59801. this._kernelBlurYPostprocess.autoClear = false;
  59802. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59803. this._kernelBlurXPostprocess.packedFloat = true;
  59804. this._kernelBlurYPostprocess.packedFloat = true;
  59805. }
  59806. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  59807. }
  59808. else {
  59809. 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);
  59810. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  59811. effect.setFloat2("screenSize", targetSize, targetSize);
  59812. effect.setTexture("textureSampler", _this._shadowMap);
  59813. });
  59814. this._boxBlurPostprocess.autoClear = false;
  59815. this._blurPostProcesses = [this._boxBlurPostprocess];
  59816. }
  59817. };
  59818. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  59819. var index;
  59820. var engine = this._scene.getEngine();
  59821. if (depthOnlySubMeshes.length) {
  59822. engine.setColorWrite(false);
  59823. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  59824. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  59825. }
  59826. engine.setColorWrite(true);
  59827. }
  59828. for (index = 0; index < opaqueSubMeshes.length; index++) {
  59829. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  59830. }
  59831. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  59832. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  59833. }
  59834. if (this._transparencyShadow) {
  59835. for (index = 0; index < transparentSubMeshes.length; index++) {
  59836. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  59837. }
  59838. }
  59839. };
  59840. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  59841. var _this = this;
  59842. var mesh = subMesh.getRenderingMesh();
  59843. var scene = this._scene;
  59844. var engine = scene.getEngine();
  59845. var material = subMesh.getMaterial();
  59846. if (!material) {
  59847. return;
  59848. }
  59849. // Culling
  59850. engine.setState(material.backFaceCulling);
  59851. // Managing instances
  59852. var batch = mesh._getInstancesRenderList(subMesh._id);
  59853. if (batch.mustReturn) {
  59854. return;
  59855. }
  59856. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  59857. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  59858. engine.enableEffect(this._effect);
  59859. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  59860. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  59861. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  59862. this._effect.setVector3("lightPosition", this.getLight().position);
  59863. if (scene.activeCamera) {
  59864. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  59865. }
  59866. // Alpha test
  59867. if (material && material.needAlphaTesting()) {
  59868. var alphaTexture = material.getAlphaTestTexture();
  59869. if (alphaTexture) {
  59870. this._effect.setTexture("diffuseSampler", alphaTexture);
  59871. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  59872. }
  59873. }
  59874. // Bones
  59875. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  59876. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  59877. }
  59878. if (this.forceBackFacesOnly) {
  59879. engine.setState(true, 0, false, true);
  59880. }
  59881. // Draw
  59882. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  59883. if (this.forceBackFacesOnly) {
  59884. engine.setState(true, 0, false, false);
  59885. }
  59886. }
  59887. else {
  59888. // Need to reset refresh rate of the shadowMap
  59889. if (this._shadowMap) {
  59890. this._shadowMap.resetRefreshCounter();
  59891. }
  59892. }
  59893. };
  59894. ShadowGenerator.prototype._applyFilterValues = function () {
  59895. if (!this._shadowMap) {
  59896. return;
  59897. }
  59898. if (this.filter === ShadowGenerator.FILTER_NONE) {
  59899. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  59900. }
  59901. else {
  59902. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59903. }
  59904. };
  59905. /**
  59906. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  59907. * @param onCompiled Callback triggered at the and of the effects compilation
  59908. * @param options Sets of optional options forcing the compilation with different modes
  59909. */
  59910. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  59911. var _this = this;
  59912. var localOptions = __assign({ useInstances: false }, options);
  59913. var shadowMap = this.getShadowMap();
  59914. if (!shadowMap) {
  59915. if (onCompiled) {
  59916. onCompiled(this);
  59917. }
  59918. return;
  59919. }
  59920. var renderList = shadowMap.renderList;
  59921. if (!renderList) {
  59922. if (onCompiled) {
  59923. onCompiled(this);
  59924. }
  59925. return;
  59926. }
  59927. var subMeshes = new Array();
  59928. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  59929. var mesh = renderList_1[_i];
  59930. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  59931. }
  59932. if (subMeshes.length === 0) {
  59933. if (onCompiled) {
  59934. onCompiled(this);
  59935. }
  59936. return;
  59937. }
  59938. var currentIndex = 0;
  59939. var checkReady = function () {
  59940. if (!_this._scene || !_this._scene.getEngine()) {
  59941. return;
  59942. }
  59943. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  59944. currentIndex++;
  59945. if (currentIndex >= subMeshes.length) {
  59946. if (onCompiled) {
  59947. onCompiled(_this);
  59948. }
  59949. return;
  59950. }
  59951. }
  59952. setTimeout(checkReady, 16);
  59953. };
  59954. checkReady();
  59955. };
  59956. /**
  59957. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  59958. * @param options Sets of optional options forcing the compilation with different modes
  59959. * @returns A promise that resolves when the compilation completes
  59960. */
  59961. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  59962. var _this = this;
  59963. return new Promise(function (resolve) {
  59964. _this.forceCompilation(function () {
  59965. resolve();
  59966. }, options);
  59967. });
  59968. };
  59969. /**
  59970. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  59971. * @param subMesh The submesh we want to render in the shadow map
  59972. * @param useInstances Defines wether will draw in the map using instances
  59973. * @returns true if ready otherwise, false
  59974. */
  59975. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  59976. var defines = [];
  59977. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  59978. defines.push("#define FLOAT");
  59979. }
  59980. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  59981. defines.push("#define ESM");
  59982. }
  59983. var attribs = [BABYLON.VertexBuffer.PositionKind];
  59984. var mesh = subMesh.getMesh();
  59985. var material = subMesh.getMaterial();
  59986. // Alpha test
  59987. if (material && material.needAlphaTesting()) {
  59988. var alphaTexture = material.getAlphaTestTexture();
  59989. if (alphaTexture) {
  59990. defines.push("#define ALPHATEST");
  59991. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  59992. attribs.push(BABYLON.VertexBuffer.UVKind);
  59993. defines.push("#define UV1");
  59994. }
  59995. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  59996. if (alphaTexture.coordinatesIndex === 1) {
  59997. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  59998. defines.push("#define UV2");
  59999. }
  60000. }
  60001. }
  60002. }
  60003. // Bones
  60004. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  60005. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  60006. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  60007. if (mesh.numBoneInfluencers > 4) {
  60008. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  60009. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  60010. }
  60011. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  60012. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  60013. }
  60014. else {
  60015. defines.push("#define NUM_BONE_INFLUENCERS 0");
  60016. }
  60017. // Instances
  60018. if (useInstances) {
  60019. defines.push("#define INSTANCES");
  60020. attribs.push("world0");
  60021. attribs.push("world1");
  60022. attribs.push("world2");
  60023. attribs.push("world3");
  60024. }
  60025. // Get correct effect
  60026. var join = defines.join("\n");
  60027. if (this._cachedDefines !== join) {
  60028. this._cachedDefines = join;
  60029. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  60030. }
  60031. if (!this._effect.isReady()) {
  60032. return false;
  60033. }
  60034. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60035. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  60036. this._initializeBlurRTTAndPostProcesses();
  60037. }
  60038. }
  60039. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  60040. return false;
  60041. }
  60042. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  60043. return false;
  60044. }
  60045. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  60046. return false;
  60047. }
  60048. return true;
  60049. };
  60050. /**
  60051. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  60052. * @param defines Defines of the material we want to update
  60053. * @param lightIndex Index of the light in the enabled light list of the material
  60054. */
  60055. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  60056. var scene = this._scene;
  60057. var light = this._light;
  60058. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60059. return;
  60060. }
  60061. defines["SHADOW" + lightIndex] = true;
  60062. if (this.usePoissonSampling) {
  60063. defines["SHADOWPCF" + lightIndex] = true;
  60064. }
  60065. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  60066. defines["SHADOWESM" + lightIndex] = true;
  60067. }
  60068. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  60069. defines["SHADOWCLOSEESM" + lightIndex] = true;
  60070. }
  60071. if (light.needCube()) {
  60072. defines["SHADOWCUBE" + lightIndex] = true;
  60073. }
  60074. };
  60075. /**
  60076. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  60077. * defined in the generator but impacting the effect).
  60078. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  60079. * @param effect The effect we are binfing the information for
  60080. */
  60081. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  60082. var light = this._light;
  60083. var scene = this._scene;
  60084. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  60085. return;
  60086. }
  60087. var camera = scene.activeCamera;
  60088. if (!camera) {
  60089. return;
  60090. }
  60091. var shadowMap = this.getShadowMap();
  60092. if (!shadowMap) {
  60093. return;
  60094. }
  60095. if (!light.needCube()) {
  60096. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  60097. }
  60098. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  60099. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  60100. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  60101. };
  60102. /**
  60103. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  60104. * (eq to shadow prjection matrix * light transform matrix)
  60105. * @returns The transform matrix used to create the shadow map
  60106. */
  60107. ShadowGenerator.prototype.getTransformMatrix = function () {
  60108. var scene = this._scene;
  60109. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  60110. return this._transformMatrix;
  60111. }
  60112. this._currentRenderID = scene.getRenderId();
  60113. this._currentFaceIndexCache = this._currentFaceIndex;
  60114. var lightPosition = this._light.position;
  60115. if (this._light.computeTransformedInformation()) {
  60116. lightPosition = this._light.transformedPosition;
  60117. }
  60118. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  60119. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  60120. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  60121. }
  60122. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  60123. this._cachedPosition = lightPosition.clone();
  60124. this._cachedDirection = this._lightDirection.clone();
  60125. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  60126. var shadowMap = this.getShadowMap();
  60127. if (shadowMap) {
  60128. var renderList = shadowMap.renderList;
  60129. if (renderList) {
  60130. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  60131. }
  60132. }
  60133. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  60134. }
  60135. return this._transformMatrix;
  60136. };
  60137. /**
  60138. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  60139. * Cube and 2D textures for instance.
  60140. */
  60141. ShadowGenerator.prototype.recreateShadowMap = function () {
  60142. var shadowMap = this._shadowMap;
  60143. if (!shadowMap) {
  60144. return;
  60145. }
  60146. // Track render list.
  60147. var renderList = shadowMap.renderList;
  60148. // Clean up existing data.
  60149. this._disposeRTTandPostProcesses();
  60150. // Reinitializes.
  60151. this._initializeGenerator();
  60152. // Reaffect the filter to ensure a correct fallback if necessary.
  60153. this.filter = this.filter;
  60154. // Reaffect the filter.
  60155. this._applyFilterValues();
  60156. // Reaffect Render List.
  60157. this._shadowMap.renderList = renderList;
  60158. };
  60159. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  60160. if (this._shadowMap2) {
  60161. this._shadowMap2.dispose();
  60162. this._shadowMap2 = null;
  60163. }
  60164. if (this._boxBlurPostprocess) {
  60165. this._boxBlurPostprocess.dispose();
  60166. this._boxBlurPostprocess = null;
  60167. }
  60168. if (this._kernelBlurXPostprocess) {
  60169. this._kernelBlurXPostprocess.dispose();
  60170. this._kernelBlurXPostprocess = null;
  60171. }
  60172. if (this._kernelBlurYPostprocess) {
  60173. this._kernelBlurYPostprocess.dispose();
  60174. this._kernelBlurYPostprocess = null;
  60175. }
  60176. this._blurPostProcesses = [];
  60177. };
  60178. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  60179. if (this._shadowMap) {
  60180. this._shadowMap.dispose();
  60181. this._shadowMap = null;
  60182. }
  60183. this._disposeBlurPostProcesses();
  60184. };
  60185. /**
  60186. * Disposes the ShadowGenerator.
  60187. * Returns nothing.
  60188. */
  60189. ShadowGenerator.prototype.dispose = function () {
  60190. this._disposeRTTandPostProcesses();
  60191. if (this._light) {
  60192. this._light._shadowGenerator = null;
  60193. this._light._markMeshesAsLightDirty();
  60194. }
  60195. };
  60196. /**
  60197. * Serializes the shadow generator setup to a json object.
  60198. * @returns The serialized JSON object
  60199. */
  60200. ShadowGenerator.prototype.serialize = function () {
  60201. var serializationObject = {};
  60202. var shadowMap = this.getShadowMap();
  60203. if (!shadowMap) {
  60204. return serializationObject;
  60205. }
  60206. serializationObject.lightId = this._light.id;
  60207. serializationObject.mapSize = shadowMap.getRenderSize();
  60208. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  60209. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  60210. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60211. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  60212. serializationObject.usePoissonSampling = this.usePoissonSampling;
  60213. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  60214. serializationObject.depthScale = this.depthScale;
  60215. serializationObject.darkness = this.getDarkness();
  60216. serializationObject.blurBoxOffset = this.blurBoxOffset;
  60217. serializationObject.blurKernel = this.blurKernel;
  60218. serializationObject.blurScale = this.blurScale;
  60219. serializationObject.useKernelBlur = this.useKernelBlur;
  60220. serializationObject.transparencyShadow = this._transparencyShadow;
  60221. serializationObject.renderList = [];
  60222. if (shadowMap.renderList) {
  60223. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  60224. var mesh = shadowMap.renderList[meshIndex];
  60225. serializationObject.renderList.push(mesh.id);
  60226. }
  60227. }
  60228. return serializationObject;
  60229. };
  60230. /**
  60231. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  60232. * @param parsedShadowGenerator The JSON object to parse
  60233. * @param scene The scene to create the shadow map for
  60234. * @returns The parsed shadow generator
  60235. */
  60236. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  60237. //casting to point light, as light is missing the position attr and typescript complains.
  60238. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  60239. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  60240. var shadowMap = shadowGenerator.getShadowMap();
  60241. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  60242. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  60243. meshes.forEach(function (mesh) {
  60244. if (!shadowMap) {
  60245. return;
  60246. }
  60247. if (!shadowMap.renderList) {
  60248. shadowMap.renderList = [];
  60249. }
  60250. shadowMap.renderList.push(mesh);
  60251. });
  60252. }
  60253. if (parsedShadowGenerator.usePoissonSampling) {
  60254. shadowGenerator.usePoissonSampling = true;
  60255. }
  60256. else if (parsedShadowGenerator.useExponentialShadowMap) {
  60257. shadowGenerator.useExponentialShadowMap = true;
  60258. }
  60259. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  60260. shadowGenerator.useBlurExponentialShadowMap = true;
  60261. }
  60262. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  60263. shadowGenerator.useCloseExponentialShadowMap = true;
  60264. }
  60265. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  60266. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  60267. }
  60268. else if (parsedShadowGenerator.useVarianceShadowMap) {
  60269. shadowGenerator.useExponentialShadowMap = true;
  60270. }
  60271. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  60272. shadowGenerator.useBlurExponentialShadowMap = true;
  60273. }
  60274. if (parsedShadowGenerator.depthScale) {
  60275. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  60276. }
  60277. if (parsedShadowGenerator.blurScale) {
  60278. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  60279. }
  60280. if (parsedShadowGenerator.blurBoxOffset) {
  60281. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  60282. }
  60283. if (parsedShadowGenerator.useKernelBlur) {
  60284. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  60285. }
  60286. if (parsedShadowGenerator.blurKernel) {
  60287. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  60288. }
  60289. if (parsedShadowGenerator.bias !== undefined) {
  60290. shadowGenerator.bias = parsedShadowGenerator.bias;
  60291. }
  60292. if (parsedShadowGenerator.darkness) {
  60293. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  60294. }
  60295. if (parsedShadowGenerator.transparencyShadow) {
  60296. shadowGenerator.setTransparencyShadow(true);
  60297. }
  60298. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  60299. return shadowGenerator;
  60300. };
  60301. ShadowGenerator._FILTER_NONE = 0;
  60302. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  60303. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  60304. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  60305. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  60306. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  60307. return ShadowGenerator;
  60308. }());
  60309. BABYLON.ShadowGenerator = ShadowGenerator;
  60310. })(BABYLON || (BABYLON = {}));
  60311. //# sourceMappingURL=babylon.shadowGenerator.js.map
  60312. var BABYLON;
  60313. (function (BABYLON) {
  60314. var DefaultLoadingScreen = /** @class */ (function () {
  60315. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  60316. if (_loadingText === void 0) { _loadingText = ""; }
  60317. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  60318. var _this = this;
  60319. this._renderingCanvas = _renderingCanvas;
  60320. this._loadingText = _loadingText;
  60321. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  60322. // Resize
  60323. this._resizeLoadingUI = function () {
  60324. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  60325. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  60326. if (!_this._loadingDiv) {
  60327. return;
  60328. }
  60329. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  60330. _this._loadingDiv.style.left = canvasRect.left + "px";
  60331. _this._loadingDiv.style.top = canvasRect.top + "px";
  60332. _this._loadingDiv.style.width = canvasRect.width + "px";
  60333. _this._loadingDiv.style.height = canvasRect.height + "px";
  60334. };
  60335. }
  60336. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  60337. if (this._loadingDiv) {
  60338. // Do not add a loading screen if there is already one
  60339. return;
  60340. }
  60341. this._loadingDiv = document.createElement("div");
  60342. this._loadingDiv.id = "babylonjsLoadingDiv";
  60343. this._loadingDiv.style.opacity = "0";
  60344. this._loadingDiv.style.transition = "opacity 1.5s ease";
  60345. this._loadingDiv.style.pointerEvents = "none";
  60346. // Loading text
  60347. this._loadingTextDiv = document.createElement("div");
  60348. this._loadingTextDiv.style.position = "absolute";
  60349. this._loadingTextDiv.style.left = "0";
  60350. this._loadingTextDiv.style.top = "50%";
  60351. this._loadingTextDiv.style.marginTop = "80px";
  60352. this._loadingTextDiv.style.width = "100%";
  60353. this._loadingTextDiv.style.height = "20px";
  60354. this._loadingTextDiv.style.fontFamily = "Arial";
  60355. this._loadingTextDiv.style.fontSize = "14px";
  60356. this._loadingTextDiv.style.color = "white";
  60357. this._loadingTextDiv.style.textAlign = "center";
  60358. this._loadingTextDiv.innerHTML = "Loading";
  60359. this._loadingDiv.appendChild(this._loadingTextDiv);
  60360. //set the predefined text
  60361. this._loadingTextDiv.innerHTML = this._loadingText;
  60362. // Generating keyframes
  60363. var style = document.createElement('style');
  60364. style.type = 'text/css';
  60365. 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 }";
  60366. style.innerHTML = keyFrames;
  60367. document.getElementsByTagName('head')[0].appendChild(style);
  60368. // Loading img
  60369. var imgBack = new Image();
  60370. 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";
  60371. imgBack.style.position = "absolute";
  60372. imgBack.style.left = "50%";
  60373. imgBack.style.top = "50%";
  60374. imgBack.style.marginLeft = "-60px";
  60375. imgBack.style.marginTop = "-60px";
  60376. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  60377. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  60378. imgBack.style.transformOrigin = "50% 50%";
  60379. imgBack.style.webkitTransformOrigin = "50% 50%";
  60380. this._loadingDiv.appendChild(imgBack);
  60381. this._resizeLoadingUI();
  60382. window.addEventListener("resize", this._resizeLoadingUI);
  60383. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60384. document.body.appendChild(this._loadingDiv);
  60385. this._loadingDiv.style.opacity = "1";
  60386. };
  60387. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  60388. var _this = this;
  60389. if (!this._loadingDiv) {
  60390. return;
  60391. }
  60392. var onTransitionEnd = function () {
  60393. if (!_this._loadingDiv) {
  60394. return;
  60395. }
  60396. document.body.removeChild(_this._loadingDiv);
  60397. window.removeEventListener("resize", _this._resizeLoadingUI);
  60398. _this._loadingDiv = null;
  60399. };
  60400. this._loadingDiv.style.opacity = "0";
  60401. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  60402. };
  60403. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  60404. set: function (text) {
  60405. this._loadingText = text;
  60406. if (this._loadingTextDiv) {
  60407. this._loadingTextDiv.innerHTML = this._loadingText;
  60408. }
  60409. },
  60410. enumerable: true,
  60411. configurable: true
  60412. });
  60413. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  60414. get: function () {
  60415. return this._loadingDivBackgroundColor;
  60416. },
  60417. set: function (color) {
  60418. this._loadingDivBackgroundColor = color;
  60419. if (!this._loadingDiv) {
  60420. return;
  60421. }
  60422. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  60423. },
  60424. enumerable: true,
  60425. configurable: true
  60426. });
  60427. return DefaultLoadingScreen;
  60428. }());
  60429. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  60430. })(BABYLON || (BABYLON = {}));
  60431. //# sourceMappingURL=babylon.loadingScreen.js.map
  60432. var BABYLON;
  60433. (function (BABYLON) {
  60434. var SceneLoaderProgressEvent = /** @class */ (function () {
  60435. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  60436. this.lengthComputable = lengthComputable;
  60437. this.loaded = loaded;
  60438. this.total = total;
  60439. }
  60440. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  60441. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  60442. };
  60443. return SceneLoaderProgressEvent;
  60444. }());
  60445. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  60446. var SceneLoader = /** @class */ (function () {
  60447. function SceneLoader() {
  60448. }
  60449. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  60450. get: function () {
  60451. return 0;
  60452. },
  60453. enumerable: true,
  60454. configurable: true
  60455. });
  60456. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  60457. get: function () {
  60458. return 1;
  60459. },
  60460. enumerable: true,
  60461. configurable: true
  60462. });
  60463. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  60464. get: function () {
  60465. return 2;
  60466. },
  60467. enumerable: true,
  60468. configurable: true
  60469. });
  60470. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  60471. get: function () {
  60472. return 3;
  60473. },
  60474. enumerable: true,
  60475. configurable: true
  60476. });
  60477. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  60478. get: function () {
  60479. return SceneLoader._ForceFullSceneLoadingForIncremental;
  60480. },
  60481. set: function (value) {
  60482. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  60483. },
  60484. enumerable: true,
  60485. configurable: true
  60486. });
  60487. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  60488. get: function () {
  60489. return SceneLoader._ShowLoadingScreen;
  60490. },
  60491. set: function (value) {
  60492. SceneLoader._ShowLoadingScreen = value;
  60493. },
  60494. enumerable: true,
  60495. configurable: true
  60496. });
  60497. Object.defineProperty(SceneLoader, "loggingLevel", {
  60498. get: function () {
  60499. return SceneLoader._loggingLevel;
  60500. },
  60501. set: function (value) {
  60502. SceneLoader._loggingLevel = value;
  60503. },
  60504. enumerable: true,
  60505. configurable: true
  60506. });
  60507. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  60508. get: function () {
  60509. return SceneLoader._CleanBoneMatrixWeights;
  60510. },
  60511. set: function (value) {
  60512. SceneLoader._CleanBoneMatrixWeights = value;
  60513. },
  60514. enumerable: true,
  60515. configurable: true
  60516. });
  60517. SceneLoader._getDefaultPlugin = function () {
  60518. return SceneLoader._registeredPlugins[".babylon"];
  60519. };
  60520. SceneLoader._getPluginForExtension = function (extension) {
  60521. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  60522. if (registeredPlugin) {
  60523. return registeredPlugin;
  60524. }
  60525. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  60526. return SceneLoader._getDefaultPlugin();
  60527. };
  60528. SceneLoader._getPluginForDirectLoad = function (data) {
  60529. for (var extension in SceneLoader._registeredPlugins) {
  60530. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  60531. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  60532. return SceneLoader._registeredPlugins[extension];
  60533. }
  60534. }
  60535. return SceneLoader._getDefaultPlugin();
  60536. };
  60537. SceneLoader._getPluginForFilename = function (sceneFilename) {
  60538. if (sceneFilename.name) {
  60539. sceneFilename = sceneFilename.name;
  60540. }
  60541. var queryStringPosition = sceneFilename.indexOf("?");
  60542. if (queryStringPosition !== -1) {
  60543. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  60544. }
  60545. var dotPosition = sceneFilename.lastIndexOf(".");
  60546. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  60547. return SceneLoader._getPluginForExtension(extension);
  60548. };
  60549. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  60550. SceneLoader._getDirectLoad = function (sceneFilename) {
  60551. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  60552. return sceneFilename.substr(5);
  60553. }
  60554. return null;
  60555. };
  60556. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  60557. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  60558. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  60559. var plugin;
  60560. if (registeredPlugin.plugin.createPlugin) {
  60561. plugin = registeredPlugin.plugin.createPlugin();
  60562. }
  60563. else {
  60564. plugin = registeredPlugin.plugin;
  60565. }
  60566. var useArrayBuffer = registeredPlugin.isBinary;
  60567. var database;
  60568. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  60569. var dataCallback = function (data, responseURL) {
  60570. if (scene.isDisposed) {
  60571. onError("Scene has been disposed");
  60572. return;
  60573. }
  60574. scene.database = database;
  60575. onSuccess(plugin, data, responseURL);
  60576. };
  60577. var request = null;
  60578. var pluginDisposed = false;
  60579. var onDisposeObservable = plugin.onDisposeObservable;
  60580. if (onDisposeObservable) {
  60581. onDisposeObservable.add(function () {
  60582. pluginDisposed = true;
  60583. if (request) {
  60584. request.abort();
  60585. request = null;
  60586. }
  60587. onDispose();
  60588. });
  60589. }
  60590. var manifestChecked = function () {
  60591. if (pluginDisposed) {
  60592. return;
  60593. }
  60594. var url = rootUrl + sceneFilename;
  60595. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  60596. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  60597. } : undefined, database, useArrayBuffer, function (request, exception) {
  60598. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  60599. });
  60600. };
  60601. if (directLoad) {
  60602. dataCallback(directLoad);
  60603. return plugin;
  60604. }
  60605. if (rootUrl.indexOf("file:") === -1) {
  60606. if (scene.getEngine().enableOfflineSupport) {
  60607. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  60608. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  60609. }
  60610. else {
  60611. manifestChecked();
  60612. }
  60613. }
  60614. else {
  60615. var fileOrString = sceneFilename;
  60616. if (fileOrString.name) {
  60617. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  60618. }
  60619. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  60620. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  60621. }
  60622. else {
  60623. onError("Unable to find file named " + sceneFilename);
  60624. }
  60625. }
  60626. return plugin;
  60627. };
  60628. // Public functions
  60629. SceneLoader.GetPluginForExtension = function (extension) {
  60630. return SceneLoader._getPluginForExtension(extension).plugin;
  60631. };
  60632. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  60633. return !!SceneLoader._registeredPlugins[extension];
  60634. };
  60635. SceneLoader.RegisterPlugin = function (plugin) {
  60636. if (typeof plugin.extensions === "string") {
  60637. var extension = plugin.extensions;
  60638. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60639. plugin: plugin,
  60640. isBinary: false
  60641. };
  60642. }
  60643. else {
  60644. var extensions = plugin.extensions;
  60645. Object.keys(extensions).forEach(function (extension) {
  60646. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  60647. plugin: plugin,
  60648. isBinary: extensions[extension].isBinary
  60649. };
  60650. });
  60651. }
  60652. };
  60653. /**
  60654. * Import meshes into a scene
  60655. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60656. * @param rootUrl a string that defines the root url for scene and resources
  60657. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60658. * @param scene the instance of BABYLON.Scene to append to
  60659. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  60660. * @param onProgress a callback with a progress event for each file being loaded
  60661. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60662. * @param pluginExtension the extension used to determine the plugin
  60663. * @returns The loaded plugin
  60664. */
  60665. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60666. if (onSuccess === void 0) { onSuccess = null; }
  60667. if (onProgress === void 0) { onProgress = null; }
  60668. if (onError === void 0) { onError = null; }
  60669. if (pluginExtension === void 0) { pluginExtension = null; }
  60670. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60671. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60672. return null;
  60673. }
  60674. var loadingToken = {};
  60675. scene._addPendingData(loadingToken);
  60676. var disposeHandler = function () {
  60677. scene._removePendingData(loadingToken);
  60678. };
  60679. var errorHandler = function (message, exception) {
  60680. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  60681. if (onError) {
  60682. onError(scene, errorMessage, exception);
  60683. }
  60684. else {
  60685. BABYLON.Tools.Error(errorMessage);
  60686. // should the exception be thrown?
  60687. }
  60688. disposeHandler();
  60689. };
  60690. var progressHandler = onProgress ? function (event) {
  60691. try {
  60692. onProgress(event);
  60693. }
  60694. catch (e) {
  60695. errorHandler("Error in onProgress callback", e);
  60696. }
  60697. } : undefined;
  60698. var successHandler = function (meshes, particleSystems, skeletons) {
  60699. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  60700. if (onSuccess) {
  60701. try {
  60702. onSuccess(meshes, particleSystems, skeletons);
  60703. }
  60704. catch (e) {
  60705. errorHandler("Error in onSuccess callback", e);
  60706. }
  60707. }
  60708. scene._removePendingData(loadingToken);
  60709. };
  60710. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60711. if (plugin.rewriteRootURL) {
  60712. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  60713. }
  60714. if (sceneFilename === "") {
  60715. if (sceneFilename === "") {
  60716. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60717. }
  60718. }
  60719. if (plugin.importMesh) {
  60720. var syncedPlugin = plugin;
  60721. var meshes = new Array();
  60722. var particleSystems = new Array();
  60723. var skeletons = new Array();
  60724. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  60725. return;
  60726. }
  60727. scene.loadingPluginName = plugin.name;
  60728. successHandler(meshes, particleSystems, skeletons);
  60729. }
  60730. else {
  60731. var asyncedPlugin = plugin;
  60732. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  60733. scene.loadingPluginName = plugin.name;
  60734. successHandler(result.meshes, result.particleSystems, result.skeletons);
  60735. }).catch(function (error) {
  60736. errorHandler(error.message, error);
  60737. });
  60738. }
  60739. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60740. };
  60741. /**
  60742. * Import meshes into a scene
  60743. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  60744. * @param rootUrl a string that defines the root url for scene and resources
  60745. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60746. * @param scene the instance of BABYLON.Scene to append to
  60747. * @param onProgress a callback with a progress event for each file being loaded
  60748. * @param pluginExtension the extension used to determine the plugin
  60749. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  60750. */
  60751. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60752. if (onProgress === void 0) { onProgress = null; }
  60753. if (pluginExtension === void 0) { pluginExtension = null; }
  60754. return new Promise(function (resolve, reject) {
  60755. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  60756. resolve({
  60757. meshes: meshes,
  60758. particleSystems: particleSystems,
  60759. skeletons: skeletons
  60760. });
  60761. }, onProgress, function (scene, message, exception) {
  60762. reject(exception || new Error(message));
  60763. });
  60764. });
  60765. };
  60766. /**
  60767. * Load a scene
  60768. * @param rootUrl a string that defines the root url for scene and resources
  60769. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60770. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60771. * @param onSuccess a callback with the scene when import succeeds
  60772. * @param onProgress a callback with a progress event for each file being loaded
  60773. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60774. * @param pluginExtension the extension used to determine the plugin
  60775. * @returns The loaded plugin
  60776. */
  60777. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  60778. if (onSuccess === void 0) { onSuccess = null; }
  60779. if (onProgress === void 0) { onProgress = null; }
  60780. if (onError === void 0) { onError = null; }
  60781. if (pluginExtension === void 0) { pluginExtension = null; }
  60782. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  60783. };
  60784. /**
  60785. * Load a scene
  60786. * @param rootUrl a string that defines the root url for scene and resources
  60787. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60788. * @param engine is the instance of BABYLON.Engine to use to create the scene
  60789. * @param onProgress a callback with a progress event for each file being loaded
  60790. * @param pluginExtension the extension used to determine the plugin
  60791. * @returns The loaded scene
  60792. */
  60793. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  60794. if (onProgress === void 0) { onProgress = null; }
  60795. if (pluginExtension === void 0) { pluginExtension = null; }
  60796. return new Promise(function (resolve, reject) {
  60797. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  60798. resolve(scene);
  60799. }, onProgress, function (scene, message, exception) {
  60800. reject(exception || new Error(message));
  60801. }, pluginExtension);
  60802. });
  60803. };
  60804. /**
  60805. * Append a scene
  60806. * @param rootUrl a string that defines the root url for scene and resources
  60807. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60808. * @param scene is the instance of BABYLON.Scene to append to
  60809. * @param onSuccess a callback with the scene when import succeeds
  60810. * @param onProgress a callback with a progress event for each file being loaded
  60811. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60812. * @param pluginExtension the extension used to determine the plugin
  60813. * @returns The loaded plugin
  60814. */
  60815. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60816. if (onSuccess === void 0) { onSuccess = null; }
  60817. if (onProgress === void 0) { onProgress = null; }
  60818. if (onError === void 0) { onError = null; }
  60819. if (pluginExtension === void 0) { pluginExtension = null; }
  60820. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60821. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60822. return null;
  60823. }
  60824. if (SceneLoader.ShowLoadingScreen) {
  60825. scene.getEngine().displayLoadingUI();
  60826. }
  60827. var loadingToken = {};
  60828. scene._addPendingData(loadingToken);
  60829. var disposeHandler = function () {
  60830. scene._removePendingData(loadingToken);
  60831. scene.getEngine().hideLoadingUI();
  60832. };
  60833. var errorHandler = function (message, exception) {
  60834. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  60835. if (onError) {
  60836. onError(scene, errorMessage, exception);
  60837. }
  60838. else {
  60839. BABYLON.Tools.Error(errorMessage);
  60840. // should the exception be thrown?
  60841. }
  60842. disposeHandler();
  60843. };
  60844. var progressHandler = onProgress ? function (event) {
  60845. try {
  60846. onProgress(event);
  60847. }
  60848. catch (e) {
  60849. errorHandler("Error in onProgress callback", e);
  60850. }
  60851. } : undefined;
  60852. var successHandler = function () {
  60853. if (onSuccess) {
  60854. try {
  60855. onSuccess(scene);
  60856. }
  60857. catch (e) {
  60858. errorHandler("Error in onSuccess callback", e);
  60859. }
  60860. }
  60861. scene._removePendingData(loadingToken);
  60862. };
  60863. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60864. if (sceneFilename === "") {
  60865. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  60866. }
  60867. if (plugin.load) {
  60868. var syncedPlugin = plugin;
  60869. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  60870. return;
  60871. }
  60872. scene.loadingPluginName = plugin.name;
  60873. successHandler();
  60874. }
  60875. else {
  60876. var asyncedPlugin = plugin;
  60877. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  60878. scene.loadingPluginName = plugin.name;
  60879. successHandler();
  60880. }).catch(function (error) {
  60881. errorHandler(error.message, error);
  60882. });
  60883. }
  60884. if (SceneLoader.ShowLoadingScreen) {
  60885. scene.executeWhenReady(function () {
  60886. scene.getEngine().hideLoadingUI();
  60887. });
  60888. }
  60889. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60890. };
  60891. /**
  60892. * Append a scene
  60893. * @param rootUrl a string that defines the root url for scene and resources
  60894. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60895. * @param scene is the instance of BABYLON.Scene to append to
  60896. * @param onProgress a callback with a progress event for each file being loaded
  60897. * @param pluginExtension the extension used to determine the plugin
  60898. * @returns The given scene
  60899. */
  60900. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  60901. if (onProgress === void 0) { onProgress = null; }
  60902. if (pluginExtension === void 0) { pluginExtension = null; }
  60903. return new Promise(function (resolve, reject) {
  60904. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  60905. resolve(scene);
  60906. }, onProgress, function (scene, message, exception) {
  60907. reject(exception || new Error(message));
  60908. }, pluginExtension);
  60909. });
  60910. };
  60911. /**
  60912. * Load a scene into an asset container
  60913. * @param rootUrl a string that defines the root url for scene and resources
  60914. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60915. * @param scene is the instance of BABYLON.Scene to append to
  60916. * @param onSuccess a callback with the scene when import succeeds
  60917. * @param onProgress a callback with a progress event for each file being loaded
  60918. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  60919. * @param pluginExtension the extension used to determine the plugin
  60920. * @returns The loaded plugin
  60921. */
  60922. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  60923. if (onSuccess === void 0) { onSuccess = null; }
  60924. if (onProgress === void 0) { onProgress = null; }
  60925. if (onError === void 0) { onError = null; }
  60926. if (pluginExtension === void 0) { pluginExtension = null; }
  60927. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  60928. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  60929. return null;
  60930. }
  60931. var loadingToken = {};
  60932. scene._addPendingData(loadingToken);
  60933. var disposeHandler = function () {
  60934. scene._removePendingData(loadingToken);
  60935. };
  60936. var errorHandler = function (message, exception) {
  60937. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  60938. if (onError) {
  60939. onError(scene, errorMessage, exception);
  60940. }
  60941. else {
  60942. BABYLON.Tools.Error(errorMessage);
  60943. // should the exception be thrown?
  60944. }
  60945. disposeHandler();
  60946. };
  60947. var progressHandler = onProgress ? function (event) {
  60948. try {
  60949. onProgress(event);
  60950. }
  60951. catch (e) {
  60952. errorHandler("Error in onProgress callback", e);
  60953. }
  60954. } : undefined;
  60955. var successHandler = function (assets) {
  60956. if (onSuccess) {
  60957. try {
  60958. onSuccess(assets);
  60959. }
  60960. catch (e) {
  60961. errorHandler("Error in onSuccess callback", e);
  60962. }
  60963. }
  60964. scene._removePendingData(loadingToken);
  60965. };
  60966. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  60967. if (plugin.loadAssetContainer) {
  60968. var syncedPlugin = plugin;
  60969. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  60970. if (!assetContainer) {
  60971. return;
  60972. }
  60973. scene.loadingPluginName = plugin.name;
  60974. successHandler(assetContainer);
  60975. }
  60976. else if (plugin.loadAssetContainerAsync) {
  60977. var asyncedPlugin = plugin;
  60978. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  60979. scene.loadingPluginName = plugin.name;
  60980. successHandler(assetContainer);
  60981. }).catch(function (error) {
  60982. errorHandler(error.message, error);
  60983. });
  60984. }
  60985. else {
  60986. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  60987. }
  60988. if (SceneLoader.ShowLoadingScreen) {
  60989. scene.executeWhenReady(function () {
  60990. scene.getEngine().hideLoadingUI();
  60991. });
  60992. }
  60993. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  60994. };
  60995. /**
  60996. * Load a scene into an asset container
  60997. * @param rootUrl a string that defines the root url for scene and resources
  60998. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  60999. * @param scene is the instance of BABYLON.Scene to append to
  61000. * @param onProgress a callback with a progress event for each file being loaded
  61001. * @param pluginExtension the extension used to determine the plugin
  61002. * @returns The loaded asset container
  61003. */
  61004. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  61005. if (onProgress === void 0) { onProgress = null; }
  61006. if (pluginExtension === void 0) { pluginExtension = null; }
  61007. return new Promise(function (resolve, reject) {
  61008. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  61009. resolve(assetContainer);
  61010. }, onProgress, function (scene, message, exception) {
  61011. reject(exception || new Error(message));
  61012. }, pluginExtension);
  61013. });
  61014. };
  61015. // Flags
  61016. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  61017. SceneLoader._ShowLoadingScreen = true;
  61018. SceneLoader._CleanBoneMatrixWeights = false;
  61019. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  61020. // Members
  61021. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  61022. SceneLoader._registeredPlugins = {};
  61023. return SceneLoader;
  61024. }());
  61025. BABYLON.SceneLoader = SceneLoader;
  61026. ;
  61027. })(BABYLON || (BABYLON = {}));
  61028. //# sourceMappingURL=babylon.sceneLoader.js.map
  61029. var BABYLON;
  61030. (function (BABYLON) {
  61031. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  61032. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61033. var parsedMaterial = parsedData.materials[index];
  61034. if (parsedMaterial.id === id) {
  61035. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61036. }
  61037. }
  61038. return null;
  61039. };
  61040. var isDescendantOf = function (mesh, names, hierarchyIds) {
  61041. for (var i in names) {
  61042. if (mesh.name === names[i]) {
  61043. hierarchyIds.push(mesh.id);
  61044. return true;
  61045. }
  61046. }
  61047. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  61048. hierarchyIds.push(mesh.id);
  61049. return true;
  61050. }
  61051. return false;
  61052. };
  61053. var logOperation = function (operation, producer) {
  61054. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  61055. };
  61056. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  61057. if (addToScene === void 0) { addToScene = false; }
  61058. var container = new BABYLON.AssetContainer(scene);
  61059. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61060. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61061. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61062. // and avoid problems with multiple concurrent .babylon loads.
  61063. var log = "importScene has failed JSON parse";
  61064. try {
  61065. var parsedData = JSON.parse(data);
  61066. log = "";
  61067. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61068. var index;
  61069. var cache;
  61070. // Lights
  61071. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  61072. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  61073. var parsedLight = parsedData.lights[index];
  61074. var light = BABYLON.Light.Parse(parsedLight, scene);
  61075. if (light) {
  61076. container.lights.push(light);
  61077. log += (index === 0 ? "\n\tLights:" : "");
  61078. log += "\n\t\t" + light.toString(fullDetails);
  61079. }
  61080. }
  61081. }
  61082. // Animations
  61083. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  61084. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  61085. var parsedAnimation = parsedData.animations[index];
  61086. var animation = BABYLON.Animation.Parse(parsedAnimation);
  61087. scene.animations.push(animation);
  61088. container.animations.push(animation);
  61089. log += (index === 0 ? "\n\tAnimations:" : "");
  61090. log += "\n\t\t" + animation.toString(fullDetails);
  61091. }
  61092. }
  61093. // Materials
  61094. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  61095. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  61096. var parsedMaterial = parsedData.materials[index];
  61097. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  61098. container.materials.push(mat);
  61099. log += (index === 0 ? "\n\tMaterials:" : "");
  61100. log += "\n\t\t" + mat.toString(fullDetails);
  61101. }
  61102. }
  61103. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61104. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  61105. var parsedMultiMaterial = parsedData.multiMaterials[index];
  61106. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61107. container.multiMaterials.push(mmat);
  61108. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  61109. log += "\n\t\t" + mmat.toString(fullDetails);
  61110. }
  61111. }
  61112. // Morph targets
  61113. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  61114. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  61115. var managerData = _a[_i];
  61116. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  61117. }
  61118. }
  61119. // Skeletons
  61120. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61121. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  61122. var parsedSkeleton = parsedData.skeletons[index];
  61123. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61124. container.skeletons.push(skeleton);
  61125. log += (index === 0 ? "\n\tSkeletons:" : "");
  61126. log += "\n\t\t" + skeleton.toString(fullDetails);
  61127. }
  61128. }
  61129. // Geometries
  61130. var geometries = parsedData.geometries;
  61131. if (geometries !== undefined && geometries !== null) {
  61132. var addedGeometry = new Array();
  61133. // Boxes
  61134. var boxes = geometries.boxes;
  61135. if (boxes !== undefined && boxes !== null) {
  61136. for (index = 0, cache = boxes.length; index < cache; index++) {
  61137. var parsedBox = boxes[index];
  61138. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  61139. }
  61140. }
  61141. // Spheres
  61142. var spheres = geometries.spheres;
  61143. if (spheres !== undefined && spheres !== null) {
  61144. for (index = 0, cache = spheres.length; index < cache; index++) {
  61145. var parsedSphere = spheres[index];
  61146. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  61147. }
  61148. }
  61149. // Cylinders
  61150. var cylinders = geometries.cylinders;
  61151. if (cylinders !== undefined && cylinders !== null) {
  61152. for (index = 0, cache = cylinders.length; index < cache; index++) {
  61153. var parsedCylinder = cylinders[index];
  61154. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  61155. }
  61156. }
  61157. // Toruses
  61158. var toruses = geometries.toruses;
  61159. if (toruses !== undefined && toruses !== null) {
  61160. for (index = 0, cache = toruses.length; index < cache; index++) {
  61161. var parsedTorus = toruses[index];
  61162. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  61163. }
  61164. }
  61165. // Grounds
  61166. var grounds = geometries.grounds;
  61167. if (grounds !== undefined && grounds !== null) {
  61168. for (index = 0, cache = grounds.length; index < cache; index++) {
  61169. var parsedGround = grounds[index];
  61170. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  61171. }
  61172. }
  61173. // Planes
  61174. var planes = geometries.planes;
  61175. if (planes !== undefined && planes !== null) {
  61176. for (index = 0, cache = planes.length; index < cache; index++) {
  61177. var parsedPlane = planes[index];
  61178. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  61179. }
  61180. }
  61181. // TorusKnots
  61182. var torusKnots = geometries.torusKnots;
  61183. if (torusKnots !== undefined && torusKnots !== null) {
  61184. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  61185. var parsedTorusKnot = torusKnots[index];
  61186. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  61187. }
  61188. }
  61189. // VertexData
  61190. var vertexData = geometries.vertexData;
  61191. if (vertexData !== undefined && vertexData !== null) {
  61192. for (index = 0, cache = vertexData.length; index < cache; index++) {
  61193. var parsedVertexData = vertexData[index];
  61194. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  61195. }
  61196. }
  61197. addedGeometry.forEach(function (g) {
  61198. if (g) {
  61199. container.geometries.push(g);
  61200. }
  61201. });
  61202. }
  61203. // Transform nodes
  61204. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  61205. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  61206. var parsedTransformNode = parsedData.transformNodes[index];
  61207. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  61208. container.transformNodes.push(node);
  61209. }
  61210. }
  61211. // Meshes
  61212. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61213. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61214. var parsedMesh = parsedData.meshes[index];
  61215. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61216. container.meshes.push(mesh);
  61217. log += (index === 0 ? "\n\tMeshes:" : "");
  61218. log += "\n\t\t" + mesh.toString(fullDetails);
  61219. }
  61220. }
  61221. // Cameras
  61222. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  61223. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  61224. var parsedCamera = parsedData.cameras[index];
  61225. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  61226. container.cameras.push(camera);
  61227. log += (index === 0 ? "\n\tCameras:" : "");
  61228. log += "\n\t\t" + camera.toString(fullDetails);
  61229. }
  61230. }
  61231. // Browsing all the graph to connect the dots
  61232. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  61233. var camera = scene.cameras[index];
  61234. if (camera._waitingParentId) {
  61235. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  61236. camera._waitingParentId = null;
  61237. }
  61238. }
  61239. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61240. var light_1 = scene.lights[index];
  61241. if (light_1 && light_1._waitingParentId) {
  61242. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  61243. light_1._waitingParentId = null;
  61244. }
  61245. }
  61246. // Sounds
  61247. // TODO: add sound
  61248. var loadedSounds = [];
  61249. var loadedSound;
  61250. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  61251. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  61252. var parsedSound = parsedData.sounds[index];
  61253. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  61254. if (!parsedSound.url)
  61255. parsedSound.url = parsedSound.name;
  61256. if (!loadedSounds[parsedSound.url]) {
  61257. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  61258. loadedSounds[parsedSound.url] = loadedSound;
  61259. container.sounds.push(loadedSound);
  61260. }
  61261. else {
  61262. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  61263. }
  61264. }
  61265. else {
  61266. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  61267. }
  61268. }
  61269. }
  61270. loadedSounds = [];
  61271. // Connect parents & children and parse actions
  61272. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  61273. var transformNode = scene.transformNodes[index];
  61274. if (transformNode._waitingParentId) {
  61275. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  61276. transformNode._waitingParentId = null;
  61277. }
  61278. }
  61279. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61280. var mesh = scene.meshes[index];
  61281. if (mesh._waitingParentId) {
  61282. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  61283. mesh._waitingParentId = null;
  61284. }
  61285. if (mesh._waitingActions) {
  61286. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  61287. mesh._waitingActions = null;
  61288. }
  61289. }
  61290. // freeze world matrix application
  61291. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61292. var currentMesh = scene.meshes[index];
  61293. if (currentMesh._waitingFreezeWorldMatrix) {
  61294. currentMesh.freezeWorldMatrix();
  61295. currentMesh._waitingFreezeWorldMatrix = null;
  61296. }
  61297. else {
  61298. currentMesh.computeWorldMatrix(true);
  61299. }
  61300. }
  61301. // Particles Systems
  61302. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61303. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61304. var parsedParticleSystem = parsedData.particleSystems[index];
  61305. if (parsedParticleSystem.activeParticleCount) {
  61306. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61307. container.particleSystems.push(ps);
  61308. }
  61309. else {
  61310. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  61311. container.particleSystems.push(ps);
  61312. }
  61313. }
  61314. }
  61315. // Lens flares
  61316. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  61317. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  61318. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  61319. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  61320. container.lensFlareSystems.push(lf);
  61321. }
  61322. }
  61323. // Shadows
  61324. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  61325. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  61326. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  61327. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  61328. container.shadowGenerators.push(sg);
  61329. }
  61330. }
  61331. // Lights exclusions / inclusions
  61332. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  61333. var light_2 = scene.lights[index];
  61334. // Excluded check
  61335. if (light_2._excludedMeshesIds.length > 0) {
  61336. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  61337. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  61338. if (excludedMesh) {
  61339. light_2.excludedMeshes.push(excludedMesh);
  61340. }
  61341. }
  61342. light_2._excludedMeshesIds = [];
  61343. }
  61344. // Included check
  61345. if (light_2._includedOnlyMeshesIds.length > 0) {
  61346. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  61347. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  61348. if (includedOnlyMesh) {
  61349. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  61350. }
  61351. }
  61352. light_2._includedOnlyMeshesIds = [];
  61353. }
  61354. }
  61355. // Actions (scene)
  61356. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  61357. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  61358. }
  61359. if (!addToScene) {
  61360. container.removeAllFromScene();
  61361. }
  61362. }
  61363. catch (err) {
  61364. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  61365. if (onError) {
  61366. onError(msg, err);
  61367. }
  61368. else {
  61369. BABYLON.Tools.Log(msg);
  61370. throw err;
  61371. }
  61372. }
  61373. finally {
  61374. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61375. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61376. }
  61377. }
  61378. return container;
  61379. };
  61380. BABYLON.SceneLoader.RegisterPlugin({
  61381. name: "babylon.js",
  61382. extensions: ".babylon",
  61383. canDirectLoad: function (data) {
  61384. if (data.indexOf("babylon") !== -1) {
  61385. return true;
  61386. }
  61387. return false;
  61388. },
  61389. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  61390. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61391. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61392. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61393. // and avoid problems with multiple concurrent .babylon loads.
  61394. var log = "importMesh has failed JSON parse";
  61395. try {
  61396. var parsedData = JSON.parse(data);
  61397. log = "";
  61398. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  61399. if (!meshesNames) {
  61400. meshesNames = null;
  61401. }
  61402. else if (!Array.isArray(meshesNames)) {
  61403. meshesNames = [meshesNames];
  61404. }
  61405. var hierarchyIds = new Array();
  61406. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  61407. var loadedSkeletonsIds = [];
  61408. var loadedMaterialsIds = [];
  61409. var index;
  61410. var cache;
  61411. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  61412. var parsedMesh = parsedData.meshes[index];
  61413. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  61414. if (meshesNames !== null) {
  61415. // Remove found mesh name from list.
  61416. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  61417. }
  61418. //Geometry?
  61419. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  61420. //does the file contain geometries?
  61421. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  61422. //find the correct geometry and add it to the scene
  61423. var found = false;
  61424. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  61425. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  61426. return;
  61427. }
  61428. else {
  61429. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  61430. if (parsedGeometryData.id === parsedMesh.geometryId) {
  61431. switch (geometryType) {
  61432. case "boxes":
  61433. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  61434. break;
  61435. case "spheres":
  61436. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  61437. break;
  61438. case "cylinders":
  61439. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  61440. break;
  61441. case "toruses":
  61442. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  61443. break;
  61444. case "grounds":
  61445. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  61446. break;
  61447. case "planes":
  61448. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  61449. break;
  61450. case "torusKnots":
  61451. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  61452. break;
  61453. case "vertexData":
  61454. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  61455. break;
  61456. }
  61457. found = true;
  61458. }
  61459. });
  61460. }
  61461. });
  61462. if (found === false) {
  61463. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  61464. }
  61465. }
  61466. }
  61467. // Material ?
  61468. if (parsedMesh.materialId) {
  61469. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  61470. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  61471. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  61472. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  61473. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  61474. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  61475. var subMatId = parsedMultiMaterial.materials[matIndex];
  61476. loadedMaterialsIds.push(subMatId);
  61477. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  61478. if (mat) {
  61479. log += "\n\tMaterial " + mat.toString(fullDetails);
  61480. }
  61481. }
  61482. loadedMaterialsIds.push(parsedMultiMaterial.id);
  61483. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  61484. if (mmat) {
  61485. materialFound = true;
  61486. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  61487. }
  61488. break;
  61489. }
  61490. }
  61491. }
  61492. if (materialFound === false) {
  61493. loadedMaterialsIds.push(parsedMesh.materialId);
  61494. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  61495. if (!mat) {
  61496. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  61497. }
  61498. else {
  61499. log += "\n\tMaterial " + mat.toString(fullDetails);
  61500. }
  61501. }
  61502. }
  61503. // Skeleton ?
  61504. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  61505. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  61506. if (skeletonAlreadyLoaded === false) {
  61507. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  61508. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  61509. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  61510. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  61511. skeletons.push(skeleton);
  61512. loadedSkeletonsIds.push(parsedSkeleton.id);
  61513. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  61514. }
  61515. }
  61516. }
  61517. }
  61518. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  61519. meshes.push(mesh);
  61520. log += "\n\tMesh " + mesh.toString(fullDetails);
  61521. }
  61522. }
  61523. // Connecting parents
  61524. var currentMesh;
  61525. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61526. currentMesh = scene.meshes[index];
  61527. if (currentMesh._waitingParentId) {
  61528. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  61529. currentMesh._waitingParentId = null;
  61530. }
  61531. }
  61532. // freeze and compute world matrix application
  61533. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  61534. currentMesh = scene.meshes[index];
  61535. if (currentMesh._waitingFreezeWorldMatrix) {
  61536. currentMesh.freezeWorldMatrix();
  61537. currentMesh._waitingFreezeWorldMatrix = null;
  61538. }
  61539. else {
  61540. currentMesh.computeWorldMatrix(true);
  61541. }
  61542. }
  61543. }
  61544. // Particles
  61545. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  61546. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  61547. var parsedParticleSystem = parsedData.particleSystems[index];
  61548. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  61549. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  61550. }
  61551. }
  61552. }
  61553. return true;
  61554. }
  61555. catch (err) {
  61556. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  61557. if (onError) {
  61558. onError(msg, err);
  61559. }
  61560. else {
  61561. BABYLON.Tools.Log(msg);
  61562. throw err;
  61563. }
  61564. }
  61565. finally {
  61566. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61567. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61568. }
  61569. }
  61570. return false;
  61571. },
  61572. load: function (scene, data, rootUrl, onError) {
  61573. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  61574. // when SceneLoader.debugLogging = true (default), or exception encountered.
  61575. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  61576. // and avoid problems with multiple concurrent .babylon loads.
  61577. var log = "importScene has failed JSON parse";
  61578. try {
  61579. var parsedData = JSON.parse(data);
  61580. log = "";
  61581. // Scene
  61582. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  61583. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  61584. }
  61585. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  61586. scene.autoClear = parsedData.autoClear;
  61587. }
  61588. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  61589. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  61590. }
  61591. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  61592. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  61593. }
  61594. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  61595. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  61596. }
  61597. // Fog
  61598. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  61599. scene.fogMode = parsedData.fogMode;
  61600. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  61601. scene.fogStart = parsedData.fogStart;
  61602. scene.fogEnd = parsedData.fogEnd;
  61603. scene.fogDensity = parsedData.fogDensity;
  61604. log += "\tFog mode for scene: ";
  61605. switch (scene.fogMode) {
  61606. // getters not compiling, so using hardcoded
  61607. case 1:
  61608. log += "exp\n";
  61609. break;
  61610. case 2:
  61611. log += "exp2\n";
  61612. break;
  61613. case 3:
  61614. log += "linear\n";
  61615. break;
  61616. }
  61617. }
  61618. //Physics
  61619. if (parsedData.physicsEnabled) {
  61620. var physicsPlugin;
  61621. if (parsedData.physicsEngine === "cannon") {
  61622. physicsPlugin = new BABYLON.CannonJSPlugin();
  61623. }
  61624. else if (parsedData.physicsEngine === "oimo") {
  61625. physicsPlugin = new BABYLON.OimoJSPlugin();
  61626. }
  61627. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  61628. //else - default engine, which is currently oimo
  61629. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  61630. scene.enablePhysics(physicsGravity, physicsPlugin);
  61631. }
  61632. // Metadata
  61633. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  61634. scene.metadata = parsedData.metadata;
  61635. }
  61636. //collisions, if defined. otherwise, default is true
  61637. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  61638. scene.collisionsEnabled = parsedData.collisionsEnabled;
  61639. }
  61640. scene.workerCollisions = !!parsedData.workerCollisions;
  61641. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  61642. if (!container) {
  61643. return false;
  61644. }
  61645. if (parsedData.autoAnimate) {
  61646. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  61647. }
  61648. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  61649. scene.setActiveCameraByID(parsedData.activeCameraID);
  61650. }
  61651. // Environment texture
  61652. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  61653. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  61654. if (parsedData.createDefaultSkybox === true) {
  61655. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  61656. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  61657. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  61658. }
  61659. }
  61660. // Finish
  61661. return true;
  61662. }
  61663. catch (err) {
  61664. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  61665. if (onError) {
  61666. onError(msg, err);
  61667. }
  61668. else {
  61669. BABYLON.Tools.Log(msg);
  61670. throw err;
  61671. }
  61672. }
  61673. finally {
  61674. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  61675. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  61676. }
  61677. }
  61678. return false;
  61679. },
  61680. loadAssetContainer: function (scene, data, rootUrl, onError) {
  61681. var container = loadAssetContainer(scene, data, rootUrl, onError);
  61682. return container;
  61683. }
  61684. });
  61685. })(BABYLON || (BABYLON = {}));
  61686. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  61687. var BABYLON;
  61688. (function (BABYLON) {
  61689. var FilesInput = /** @class */ (function () {
  61690. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  61691. this.onProcessFileCallback = function () { return true; };
  61692. this._engine = engine;
  61693. this._currentScene = scene;
  61694. this._sceneLoadedCallback = sceneLoadedCallback;
  61695. this._progressCallback = progressCallback;
  61696. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  61697. this._textureLoadingCallback = textureLoadingCallback;
  61698. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  61699. this._onReloadCallback = onReloadCallback;
  61700. this._errorCallback = errorCallback;
  61701. }
  61702. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  61703. var _this = this;
  61704. if (elementToMonitor) {
  61705. this._elementToMonitor = elementToMonitor;
  61706. this._dragEnterHandler = function (e) { _this.drag(e); };
  61707. this._dragOverHandler = function (e) { _this.drag(e); };
  61708. this._dropHandler = function (e) { _this.drop(e); };
  61709. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  61710. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  61711. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  61712. }
  61713. };
  61714. FilesInput.prototype.dispose = function () {
  61715. if (!this._elementToMonitor) {
  61716. return;
  61717. }
  61718. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  61719. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  61720. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  61721. };
  61722. FilesInput.prototype.renderFunction = function () {
  61723. if (this._additionalRenderLoopLogicCallback) {
  61724. this._additionalRenderLoopLogicCallback();
  61725. }
  61726. if (this._currentScene) {
  61727. if (this._textureLoadingCallback) {
  61728. var remaining = this._currentScene.getWaitingItemsCount();
  61729. if (remaining > 0) {
  61730. this._textureLoadingCallback(remaining);
  61731. }
  61732. }
  61733. this._currentScene.render();
  61734. }
  61735. };
  61736. FilesInput.prototype.drag = function (e) {
  61737. e.stopPropagation();
  61738. e.preventDefault();
  61739. };
  61740. FilesInput.prototype.drop = function (eventDrop) {
  61741. eventDrop.stopPropagation();
  61742. eventDrop.preventDefault();
  61743. this.loadFiles(eventDrop);
  61744. };
  61745. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  61746. var _this = this;
  61747. var reader = folder.createReader();
  61748. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  61749. reader.readEntries(function (entries) {
  61750. remaining.count += entries.length;
  61751. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  61752. var entry = entries_1[_i];
  61753. if (entry.isFile) {
  61754. entry.file(function (file) {
  61755. file.correctName = relativePath + file.name;
  61756. files.push(file);
  61757. if (--remaining.count === 0) {
  61758. callback();
  61759. }
  61760. });
  61761. }
  61762. else if (entry.isDirectory) {
  61763. _this._traverseFolder(entry, files, remaining, callback);
  61764. }
  61765. }
  61766. if (--remaining.count) {
  61767. callback();
  61768. }
  61769. });
  61770. };
  61771. FilesInput.prototype._processFiles = function (files) {
  61772. for (var i = 0; i < files.length; i++) {
  61773. var name = files[i].correctName.toLowerCase();
  61774. var extension = name.split('.').pop();
  61775. if (!this.onProcessFileCallback(files[i], name, extension)) {
  61776. continue;
  61777. }
  61778. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  61779. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  61780. this._sceneFileToLoad = files[i];
  61781. }
  61782. else {
  61783. FilesInput.FilesToLoad[name] = files[i];
  61784. }
  61785. }
  61786. };
  61787. FilesInput.prototype.loadFiles = function (event) {
  61788. var _this = this;
  61789. if (this._startingProcessingFilesCallback)
  61790. this._startingProcessingFilesCallback();
  61791. // Handling data transfer via drag'n'drop
  61792. if (event && event.dataTransfer && event.dataTransfer.files) {
  61793. this._filesToLoad = event.dataTransfer.files;
  61794. }
  61795. // Handling files from input files
  61796. if (event && event.target && event.target.files) {
  61797. this._filesToLoad = event.target.files;
  61798. }
  61799. if (this._filesToLoad && this._filesToLoad.length > 0) {
  61800. var files_1 = new Array();
  61801. var folders = [];
  61802. var items = event.dataTransfer ? event.dataTransfer.items : null;
  61803. for (var i = 0; i < this._filesToLoad.length; i++) {
  61804. var fileToLoad = this._filesToLoad[i];
  61805. var name_1 = fileToLoad.name.toLowerCase();
  61806. var entry = void 0;
  61807. fileToLoad.correctName = name_1;
  61808. if (items) {
  61809. var item = items[i];
  61810. if (item.getAsEntry) {
  61811. entry = item.getAsEntry();
  61812. }
  61813. else if (item.webkitGetAsEntry) {
  61814. entry = item.webkitGetAsEntry();
  61815. }
  61816. }
  61817. if (!entry) {
  61818. files_1.push(fileToLoad);
  61819. }
  61820. else {
  61821. if (entry.isDirectory) {
  61822. folders.push(entry);
  61823. }
  61824. else {
  61825. files_1.push(fileToLoad);
  61826. }
  61827. }
  61828. }
  61829. if (folders.length === 0) {
  61830. this._processFiles(files_1);
  61831. this._processReload();
  61832. }
  61833. else {
  61834. var remaining = { count: folders.length };
  61835. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  61836. var folder = folders_1[_i];
  61837. this._traverseFolder(folder, files_1, remaining, function () {
  61838. _this._processFiles(files_1);
  61839. if (remaining.count === 0) {
  61840. _this._processReload();
  61841. }
  61842. });
  61843. }
  61844. }
  61845. }
  61846. };
  61847. FilesInput.prototype._processReload = function () {
  61848. if (this._onReloadCallback) {
  61849. this._onReloadCallback(this._sceneFileToLoad);
  61850. }
  61851. else {
  61852. this.reload();
  61853. }
  61854. };
  61855. FilesInput.prototype.reload = function () {
  61856. var _this = this;
  61857. // If a scene file has been provided
  61858. if (this._sceneFileToLoad) {
  61859. if (this._currentScene) {
  61860. if (BABYLON.Tools.errorsCount > 0) {
  61861. BABYLON.Tools.ClearLogCache();
  61862. }
  61863. this._engine.stopRenderLoop();
  61864. this._currentScene.dispose();
  61865. }
  61866. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  61867. if (_this._progressCallback) {
  61868. _this._progressCallback(progress);
  61869. }
  61870. }).then(function (scene) {
  61871. _this._currentScene = scene;
  61872. if (_this._sceneLoadedCallback) {
  61873. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  61874. }
  61875. // Wait for textures and shaders to be ready
  61876. _this._currentScene.executeWhenReady(function () {
  61877. _this._engine.runRenderLoop(function () {
  61878. _this.renderFunction();
  61879. });
  61880. });
  61881. }).catch(function (error) {
  61882. if (_this._errorCallback) {
  61883. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  61884. }
  61885. });
  61886. }
  61887. else {
  61888. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  61889. }
  61890. };
  61891. FilesInput.FilesToLoad = {};
  61892. return FilesInput;
  61893. }());
  61894. BABYLON.FilesInput = FilesInput;
  61895. })(BABYLON || (BABYLON = {}));
  61896. //# sourceMappingURL=babylon.filesInput.js.map
  61897. var BABYLON;
  61898. (function (BABYLON) {
  61899. /**
  61900. * This class implement a typical dictionary using a string as key and the generic type T as value.
  61901. * The underlying implementation relies on an associative array to ensure the best performances.
  61902. * The value can be anything including 'null' but except 'undefined'
  61903. */
  61904. var StringDictionary = /** @class */ (function () {
  61905. function StringDictionary() {
  61906. this._count = 0;
  61907. this._data = {};
  61908. }
  61909. /**
  61910. * This will clear this dictionary and copy the content from the 'source' one.
  61911. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  61912. * @param source the dictionary to take the content from and copy to this dictionary
  61913. */
  61914. StringDictionary.prototype.copyFrom = function (source) {
  61915. var _this = this;
  61916. this.clear();
  61917. source.forEach(function (t, v) { return _this.add(t, v); });
  61918. };
  61919. /**
  61920. * Get a value based from its key
  61921. * @param key the given key to get the matching value from
  61922. * @return the value if found, otherwise undefined is returned
  61923. */
  61924. StringDictionary.prototype.get = function (key) {
  61925. var val = this._data[key];
  61926. if (val !== undefined) {
  61927. return val;
  61928. }
  61929. return undefined;
  61930. };
  61931. /**
  61932. * Get a value from its key or add it if it doesn't exist.
  61933. * This method will ensure you that a given key/data will be present in the dictionary.
  61934. * @param key the given key to get the matching value from
  61935. * @param factory the factory that will create the value if the key is not present in the dictionary.
  61936. * The factory will only be invoked if there's no data for the given key.
  61937. * @return the value corresponding to the key.
  61938. */
  61939. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  61940. var val = this.get(key);
  61941. if (val !== undefined) {
  61942. return val;
  61943. }
  61944. val = factory(key);
  61945. if (val) {
  61946. this.add(key, val);
  61947. }
  61948. return val;
  61949. };
  61950. /**
  61951. * Get a value from its key if present in the dictionary otherwise add it
  61952. * @param key the key to get the value from
  61953. * @param val if there's no such key/value pair in the dictionary add it with this value
  61954. * @return the value corresponding to the key
  61955. */
  61956. StringDictionary.prototype.getOrAdd = function (key, val) {
  61957. var curVal = this.get(key);
  61958. if (curVal !== undefined) {
  61959. return curVal;
  61960. }
  61961. this.add(key, val);
  61962. return val;
  61963. };
  61964. /**
  61965. * Check if there's a given key in the dictionary
  61966. * @param key the key to check for
  61967. * @return true if the key is present, false otherwise
  61968. */
  61969. StringDictionary.prototype.contains = function (key) {
  61970. return this._data[key] !== undefined;
  61971. };
  61972. /**
  61973. * Add a new key and its corresponding value
  61974. * @param key the key to add
  61975. * @param value the value corresponding to the key
  61976. * @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
  61977. */
  61978. StringDictionary.prototype.add = function (key, value) {
  61979. if (this._data[key] !== undefined) {
  61980. return false;
  61981. }
  61982. this._data[key] = value;
  61983. ++this._count;
  61984. return true;
  61985. };
  61986. StringDictionary.prototype.set = function (key, value) {
  61987. if (this._data[key] === undefined) {
  61988. return false;
  61989. }
  61990. this._data[key] = value;
  61991. return true;
  61992. };
  61993. /**
  61994. * Get the element of the given key and remove it from the dictionary
  61995. * @param key
  61996. */
  61997. StringDictionary.prototype.getAndRemove = function (key) {
  61998. var val = this.get(key);
  61999. if (val !== undefined) {
  62000. delete this._data[key];
  62001. --this._count;
  62002. return val;
  62003. }
  62004. return null;
  62005. };
  62006. /**
  62007. * Remove a key/value from the dictionary.
  62008. * @param key the key to remove
  62009. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  62010. */
  62011. StringDictionary.prototype.remove = function (key) {
  62012. if (this.contains(key)) {
  62013. delete this._data[key];
  62014. --this._count;
  62015. return true;
  62016. }
  62017. return false;
  62018. };
  62019. /**
  62020. * Clear the whole content of the dictionary
  62021. */
  62022. StringDictionary.prototype.clear = function () {
  62023. this._data = {};
  62024. this._count = 0;
  62025. };
  62026. Object.defineProperty(StringDictionary.prototype, "count", {
  62027. get: function () {
  62028. return this._count;
  62029. },
  62030. enumerable: true,
  62031. configurable: true
  62032. });
  62033. /**
  62034. * Execute a callback on each key/val of the dictionary.
  62035. * Note that you can remove any element in this dictionary in the callback implementation
  62036. * @param callback the callback to execute on a given key/value pair
  62037. */
  62038. StringDictionary.prototype.forEach = function (callback) {
  62039. for (var cur in this._data) {
  62040. var val = this._data[cur];
  62041. callback(cur, val);
  62042. }
  62043. };
  62044. /**
  62045. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  62046. * If the callback returns null or undefined the method will iterate to the next key/value pair
  62047. * Note that you can remove any element in this dictionary in the callback implementation
  62048. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  62049. */
  62050. StringDictionary.prototype.first = function (callback) {
  62051. for (var cur in this._data) {
  62052. var val = this._data[cur];
  62053. var res = callback(cur, val);
  62054. if (res) {
  62055. return res;
  62056. }
  62057. }
  62058. return null;
  62059. };
  62060. return StringDictionary;
  62061. }());
  62062. BABYLON.StringDictionary = StringDictionary;
  62063. })(BABYLON || (BABYLON = {}));
  62064. //# sourceMappingURL=babylon.stringDictionary.js.map
  62065. var BABYLON;
  62066. (function (BABYLON) {
  62067. var Tags = /** @class */ (function () {
  62068. function Tags() {
  62069. }
  62070. Tags.EnableFor = function (obj) {
  62071. obj._tags = obj._tags || {};
  62072. obj.hasTags = function () {
  62073. return Tags.HasTags(obj);
  62074. };
  62075. obj.addTags = function (tagsString) {
  62076. return Tags.AddTagsTo(obj, tagsString);
  62077. };
  62078. obj.removeTags = function (tagsString) {
  62079. return Tags.RemoveTagsFrom(obj, tagsString);
  62080. };
  62081. obj.matchesTagsQuery = function (tagsQuery) {
  62082. return Tags.MatchesQuery(obj, tagsQuery);
  62083. };
  62084. };
  62085. Tags.DisableFor = function (obj) {
  62086. delete obj._tags;
  62087. delete obj.hasTags;
  62088. delete obj.addTags;
  62089. delete obj.removeTags;
  62090. delete obj.matchesTagsQuery;
  62091. };
  62092. Tags.HasTags = function (obj) {
  62093. if (!obj._tags) {
  62094. return false;
  62095. }
  62096. return !BABYLON.Tools.IsEmpty(obj._tags);
  62097. };
  62098. Tags.GetTags = function (obj, asString) {
  62099. if (asString === void 0) { asString = true; }
  62100. if (!obj._tags) {
  62101. return null;
  62102. }
  62103. if (asString) {
  62104. var tagsArray = [];
  62105. for (var tag in obj._tags) {
  62106. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  62107. tagsArray.push(tag);
  62108. }
  62109. }
  62110. return tagsArray.join(" ");
  62111. }
  62112. else {
  62113. return obj._tags;
  62114. }
  62115. };
  62116. // the tags 'true' and 'false' are reserved and cannot be used as tags
  62117. // a tag cannot start with '||', '&&', and '!'
  62118. // it cannot contain whitespaces
  62119. Tags.AddTagsTo = function (obj, tagsString) {
  62120. if (!tagsString) {
  62121. return;
  62122. }
  62123. if (typeof tagsString !== "string") {
  62124. return;
  62125. }
  62126. var tags = tagsString.split(" ");
  62127. tags.forEach(function (tag, index, array) {
  62128. Tags._AddTagTo(obj, tag);
  62129. });
  62130. };
  62131. Tags._AddTagTo = function (obj, tag) {
  62132. tag = tag.trim();
  62133. if (tag === "" || tag === "true" || tag === "false") {
  62134. return;
  62135. }
  62136. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  62137. return;
  62138. }
  62139. Tags.EnableFor(obj);
  62140. obj._tags[tag] = true;
  62141. };
  62142. Tags.RemoveTagsFrom = function (obj, tagsString) {
  62143. if (!Tags.HasTags(obj)) {
  62144. return;
  62145. }
  62146. var tags = tagsString.split(" ");
  62147. for (var t in tags) {
  62148. Tags._RemoveTagFrom(obj, tags[t]);
  62149. }
  62150. };
  62151. Tags._RemoveTagFrom = function (obj, tag) {
  62152. delete obj._tags[tag];
  62153. };
  62154. Tags.MatchesQuery = function (obj, tagsQuery) {
  62155. if (tagsQuery === undefined) {
  62156. return true;
  62157. }
  62158. if (tagsQuery === "") {
  62159. return Tags.HasTags(obj);
  62160. }
  62161. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  62162. };
  62163. return Tags;
  62164. }());
  62165. BABYLON.Tags = Tags;
  62166. })(BABYLON || (BABYLON = {}));
  62167. //# sourceMappingURL=babylon.tags.js.map
  62168. var BABYLON;
  62169. (function (BABYLON) {
  62170. var AndOrNotEvaluator = /** @class */ (function () {
  62171. function AndOrNotEvaluator() {
  62172. }
  62173. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  62174. if (!query.match(/\([^\(\)]*\)/g)) {
  62175. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  62176. }
  62177. else {
  62178. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  62179. // remove parenthesis
  62180. r = r.slice(1, r.length - 1);
  62181. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  62182. });
  62183. }
  62184. if (query === "true") {
  62185. return true;
  62186. }
  62187. if (query === "false") {
  62188. return false;
  62189. }
  62190. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  62191. };
  62192. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  62193. evaluateCallback = evaluateCallback || (function (r) {
  62194. return r === "true" ? true : false;
  62195. });
  62196. var result;
  62197. var or = parenthesisContent.split("||");
  62198. for (var i in or) {
  62199. if (or.hasOwnProperty(i)) {
  62200. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  62201. var and = ori.split("&&");
  62202. if (and.length > 1) {
  62203. for (var j = 0; j < and.length; ++j) {
  62204. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  62205. if (andj !== "true" && andj !== "false") {
  62206. if (andj[0] === "!") {
  62207. result = !evaluateCallback(andj.substring(1));
  62208. }
  62209. else {
  62210. result = evaluateCallback(andj);
  62211. }
  62212. }
  62213. else {
  62214. result = andj === "true" ? true : false;
  62215. }
  62216. if (!result) {
  62217. ori = "false";
  62218. break;
  62219. }
  62220. }
  62221. }
  62222. if (result || ori === "true") {
  62223. result = true;
  62224. break;
  62225. }
  62226. // result equals false (or undefined)
  62227. if (ori !== "true" && ori !== "false") {
  62228. if (ori[0] === "!") {
  62229. result = !evaluateCallback(ori.substring(1));
  62230. }
  62231. else {
  62232. result = evaluateCallback(ori);
  62233. }
  62234. }
  62235. else {
  62236. result = ori === "true" ? true : false;
  62237. }
  62238. }
  62239. }
  62240. // the whole parenthesis scope is replaced by 'true' or 'false'
  62241. return result ? "true" : "false";
  62242. };
  62243. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  62244. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  62245. // remove whitespaces
  62246. r = r.replace(/[\s]/g, function () { return ""; });
  62247. return r.length % 2 ? "!" : "";
  62248. });
  62249. booleanString = booleanString.trim();
  62250. if (booleanString === "!true") {
  62251. booleanString = "false";
  62252. }
  62253. else if (booleanString === "!false") {
  62254. booleanString = "true";
  62255. }
  62256. return booleanString;
  62257. };
  62258. return AndOrNotEvaluator;
  62259. }());
  62260. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  62261. })(BABYLON || (BABYLON = {}));
  62262. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  62263. var BABYLON;
  62264. (function (BABYLON) {
  62265. var Database = /** @class */ (function () {
  62266. function Database(urlToScene, callbackManifestChecked) {
  62267. // Handling various flavors of prefixed version of IndexedDB
  62268. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  62269. this.callbackManifestChecked = callbackManifestChecked;
  62270. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  62271. this.db = null;
  62272. this._enableSceneOffline = false;
  62273. this._enableTexturesOffline = false;
  62274. this.manifestVersionFound = 0;
  62275. this.mustUpdateRessources = false;
  62276. this.hasReachedQuota = false;
  62277. if (!Database.IDBStorageEnabled) {
  62278. this.callbackManifestChecked(true);
  62279. }
  62280. else {
  62281. this.checkManifestFile();
  62282. }
  62283. }
  62284. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  62285. get: function () {
  62286. return this._enableSceneOffline;
  62287. },
  62288. enumerable: true,
  62289. configurable: true
  62290. });
  62291. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  62292. get: function () {
  62293. return this._enableTexturesOffline;
  62294. },
  62295. enumerable: true,
  62296. configurable: true
  62297. });
  62298. Database.prototype.checkManifestFile = function () {
  62299. var _this = this;
  62300. var noManifestFile = function () {
  62301. _this._enableSceneOffline = false;
  62302. _this._enableTexturesOffline = false;
  62303. _this.callbackManifestChecked(false);
  62304. };
  62305. var timeStampUsed = false;
  62306. var manifestURL = this.currentSceneUrl + ".manifest";
  62307. var xhr = new XMLHttpRequest();
  62308. if (navigator.onLine) {
  62309. // Adding a timestamp to by-pass browsers' cache
  62310. timeStampUsed = true;
  62311. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  62312. }
  62313. xhr.open("GET", manifestURL, true);
  62314. xhr.addEventListener("load", function () {
  62315. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  62316. try {
  62317. var manifestFile = JSON.parse(xhr.response);
  62318. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  62319. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  62320. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  62321. _this.manifestVersionFound = manifestFile.version;
  62322. }
  62323. if (_this.callbackManifestChecked) {
  62324. _this.callbackManifestChecked(true);
  62325. }
  62326. }
  62327. catch (ex) {
  62328. noManifestFile();
  62329. }
  62330. }
  62331. else {
  62332. noManifestFile();
  62333. }
  62334. }, false);
  62335. xhr.addEventListener("error", function (event) {
  62336. if (timeStampUsed) {
  62337. timeStampUsed = false;
  62338. // Let's retry without the timeStamp
  62339. // It could fail when coupled with HTML5 Offline API
  62340. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  62341. xhr.open("GET", retryManifestURL, true);
  62342. xhr.send();
  62343. }
  62344. else {
  62345. noManifestFile();
  62346. }
  62347. }, false);
  62348. try {
  62349. xhr.send();
  62350. }
  62351. catch (ex) {
  62352. BABYLON.Tools.Error("Error on XHR send request.");
  62353. this.callbackManifestChecked(false);
  62354. }
  62355. };
  62356. Database.prototype.openAsync = function (successCallback, errorCallback) {
  62357. var _this = this;
  62358. var handleError = function () {
  62359. _this.isSupported = false;
  62360. if (errorCallback)
  62361. errorCallback();
  62362. };
  62363. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  62364. // Your browser doesn't support IndexedDB
  62365. this.isSupported = false;
  62366. if (errorCallback)
  62367. errorCallback();
  62368. }
  62369. else {
  62370. // If the DB hasn't been opened or created yet
  62371. if (!this.db) {
  62372. this.hasReachedQuota = false;
  62373. this.isSupported = true;
  62374. var request = this.idbFactory.open("babylonjs", 1);
  62375. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  62376. request.onerror = function (event) {
  62377. handleError();
  62378. };
  62379. // executes when a version change transaction cannot complete due to other active transactions
  62380. request.onblocked = function (event) {
  62381. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  62382. handleError();
  62383. };
  62384. // DB has been opened successfully
  62385. request.onsuccess = function (event) {
  62386. _this.db = request.result;
  62387. successCallback();
  62388. };
  62389. // Initialization of the DB. Creating Scenes & Textures stores
  62390. request.onupgradeneeded = function (event) {
  62391. _this.db = (event.target).result;
  62392. if (_this.db) {
  62393. try {
  62394. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  62395. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  62396. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  62397. }
  62398. catch (ex) {
  62399. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  62400. handleError();
  62401. }
  62402. }
  62403. };
  62404. }
  62405. else {
  62406. if (successCallback)
  62407. successCallback();
  62408. }
  62409. }
  62410. };
  62411. Database.prototype.loadImageFromDB = function (url, image) {
  62412. var _this = this;
  62413. var completeURL = Database.ReturnFullUrlLocation(url);
  62414. var saveAndLoadImage = function () {
  62415. if (!_this.hasReachedQuota && _this.db !== null) {
  62416. // the texture is not yet in the DB, let's try to save it
  62417. _this._saveImageIntoDBAsync(completeURL, image);
  62418. }
  62419. else {
  62420. image.src = url;
  62421. }
  62422. };
  62423. if (!this.mustUpdateRessources) {
  62424. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  62425. }
  62426. else {
  62427. saveAndLoadImage();
  62428. }
  62429. };
  62430. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  62431. if (this.isSupported && this.db !== null) {
  62432. var texture;
  62433. var transaction = this.db.transaction(["textures"]);
  62434. transaction.onabort = function (event) {
  62435. image.src = url;
  62436. };
  62437. transaction.oncomplete = function (event) {
  62438. var blobTextureURL;
  62439. if (texture) {
  62440. var URL = window.URL || window.webkitURL;
  62441. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  62442. image.onerror = function () {
  62443. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  62444. image.src = url;
  62445. };
  62446. image.src = blobTextureURL;
  62447. }
  62448. else {
  62449. notInDBCallback();
  62450. }
  62451. };
  62452. var getRequest = transaction.objectStore("textures").get(url);
  62453. getRequest.onsuccess = function (event) {
  62454. texture = (event.target).result;
  62455. };
  62456. getRequest.onerror = function (event) {
  62457. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  62458. image.src = url;
  62459. };
  62460. }
  62461. else {
  62462. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62463. image.src = url;
  62464. }
  62465. };
  62466. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  62467. var _this = this;
  62468. if (this.isSupported) {
  62469. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  62470. var generateBlobUrl = function () {
  62471. var blobTextureURL;
  62472. if (blob) {
  62473. var URL = window.URL || window.webkitURL;
  62474. try {
  62475. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  62476. }
  62477. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  62478. catch (ex) {
  62479. blobTextureURL = URL.createObjectURL(blob);
  62480. }
  62481. }
  62482. if (blobTextureURL) {
  62483. image.src = blobTextureURL;
  62484. }
  62485. };
  62486. if (Database.IsUASupportingBlobStorage) {
  62487. var xhr = new XMLHttpRequest(), blob;
  62488. xhr.open("GET", url, true);
  62489. xhr.responseType = "blob";
  62490. xhr.addEventListener("load", function () {
  62491. if (xhr.status === 200 && _this.db) {
  62492. // Blob as response (XHR2)
  62493. blob = xhr.response;
  62494. var transaction = _this.db.transaction(["textures"], "readwrite");
  62495. // the transaction could abort because of a QuotaExceededError error
  62496. transaction.onabort = function (event) {
  62497. try {
  62498. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62499. var srcElement = (event.srcElement || event.target);
  62500. var error = srcElement.error;
  62501. if (error && error.name === "QuotaExceededError") {
  62502. _this.hasReachedQuota = true;
  62503. }
  62504. }
  62505. catch (ex) { }
  62506. generateBlobUrl();
  62507. };
  62508. transaction.oncomplete = function (event) {
  62509. generateBlobUrl();
  62510. };
  62511. var newTexture = { textureUrl: url, data: blob };
  62512. try {
  62513. // Put the blob into the dabase
  62514. var addRequest = transaction.objectStore("textures").put(newTexture);
  62515. addRequest.onsuccess = function (event) {
  62516. };
  62517. addRequest.onerror = function (event) {
  62518. generateBlobUrl();
  62519. };
  62520. }
  62521. catch (ex) {
  62522. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  62523. if (ex.code === 25) {
  62524. Database.IsUASupportingBlobStorage = false;
  62525. }
  62526. image.src = url;
  62527. }
  62528. }
  62529. else {
  62530. image.src = url;
  62531. }
  62532. }, false);
  62533. xhr.addEventListener("error", function (event) {
  62534. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  62535. image.src = url;
  62536. }, false);
  62537. xhr.send();
  62538. }
  62539. else {
  62540. image.src = url;
  62541. }
  62542. }
  62543. else {
  62544. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62545. image.src = url;
  62546. }
  62547. };
  62548. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  62549. var _this = this;
  62550. var updateVersion = function () {
  62551. // the version is not yet in the DB or we need to update it
  62552. _this._saveVersionIntoDBAsync(url, versionLoaded);
  62553. };
  62554. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  62555. };
  62556. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  62557. var _this = this;
  62558. if (this.isSupported && this.db) {
  62559. var version;
  62560. try {
  62561. var transaction = this.db.transaction(["versions"]);
  62562. transaction.oncomplete = function (event) {
  62563. if (version) {
  62564. // If the version in the JSON file is > than the version in DB
  62565. if (_this.manifestVersionFound > version.data) {
  62566. _this.mustUpdateRessources = true;
  62567. updateInDBCallback();
  62568. }
  62569. else {
  62570. callback(version.data);
  62571. }
  62572. }
  62573. else {
  62574. _this.mustUpdateRessources = true;
  62575. updateInDBCallback();
  62576. }
  62577. };
  62578. transaction.onabort = function (event) {
  62579. callback(-1);
  62580. };
  62581. var getRequest = transaction.objectStore("versions").get(url);
  62582. getRequest.onsuccess = function (event) {
  62583. version = (event.target).result;
  62584. };
  62585. getRequest.onerror = function (event) {
  62586. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  62587. callback(-1);
  62588. };
  62589. }
  62590. catch (ex) {
  62591. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  62592. callback(-1);
  62593. }
  62594. }
  62595. else {
  62596. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62597. callback(-1);
  62598. }
  62599. };
  62600. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  62601. var _this = this;
  62602. if (this.isSupported && !this.hasReachedQuota && this.db) {
  62603. try {
  62604. // Open a transaction to the database
  62605. var transaction = this.db.transaction(["versions"], "readwrite");
  62606. // the transaction could abort because of a QuotaExceededError error
  62607. transaction.onabort = function (event) {
  62608. try {
  62609. var error = event.srcElement['error'];
  62610. if (error && error.name === "QuotaExceededError") {
  62611. _this.hasReachedQuota = true;
  62612. }
  62613. }
  62614. catch (ex) { }
  62615. callback(-1);
  62616. };
  62617. transaction.oncomplete = function (event) {
  62618. callback(_this.manifestVersionFound);
  62619. };
  62620. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  62621. // Put the scene into the database
  62622. var addRequest = transaction.objectStore("versions").put(newVersion);
  62623. addRequest.onsuccess = function (event) {
  62624. };
  62625. addRequest.onerror = function (event) {
  62626. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  62627. };
  62628. }
  62629. catch (ex) {
  62630. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  62631. callback(-1);
  62632. }
  62633. }
  62634. else {
  62635. callback(-1);
  62636. }
  62637. };
  62638. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  62639. var _this = this;
  62640. var completeUrl = Database.ReturnFullUrlLocation(url);
  62641. var saveAndLoadFile = function () {
  62642. // the scene is not yet in the DB, let's try to save it
  62643. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  62644. };
  62645. this._checkVersionFromDB(completeUrl, function (version) {
  62646. if (version !== -1) {
  62647. if (!_this.mustUpdateRessources) {
  62648. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  62649. }
  62650. else {
  62651. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  62652. }
  62653. }
  62654. else {
  62655. if (errorCallback) {
  62656. errorCallback();
  62657. }
  62658. }
  62659. });
  62660. };
  62661. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  62662. if (this.isSupported && this.db) {
  62663. var targetStore;
  62664. if (url.indexOf(".babylon") !== -1) {
  62665. targetStore = "scenes";
  62666. }
  62667. else {
  62668. targetStore = "textures";
  62669. }
  62670. var file;
  62671. var transaction = this.db.transaction([targetStore]);
  62672. transaction.oncomplete = function (event) {
  62673. if (file) {
  62674. callback(file.data);
  62675. }
  62676. else {
  62677. notInDBCallback();
  62678. }
  62679. };
  62680. transaction.onabort = function (event) {
  62681. notInDBCallback();
  62682. };
  62683. var getRequest = transaction.objectStore(targetStore).get(url);
  62684. getRequest.onsuccess = function (event) {
  62685. file = (event.target).result;
  62686. };
  62687. getRequest.onerror = function (event) {
  62688. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  62689. notInDBCallback();
  62690. };
  62691. }
  62692. else {
  62693. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62694. callback();
  62695. }
  62696. };
  62697. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  62698. var _this = this;
  62699. if (this.isSupported) {
  62700. var targetStore;
  62701. if (url.indexOf(".babylon") !== -1) {
  62702. targetStore = "scenes";
  62703. }
  62704. else {
  62705. targetStore = "textures";
  62706. }
  62707. // Create XHR
  62708. var xhr = new XMLHttpRequest();
  62709. var fileData;
  62710. xhr.open("GET", url, true);
  62711. if (useArrayBuffer) {
  62712. xhr.responseType = "arraybuffer";
  62713. }
  62714. if (progressCallback) {
  62715. xhr.onprogress = progressCallback;
  62716. }
  62717. xhr.addEventListener("load", function () {
  62718. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  62719. // Blob as response (XHR2)
  62720. //fileData = xhr.responseText;
  62721. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  62722. if (!_this.hasReachedQuota && _this.db) {
  62723. // Open a transaction to the database
  62724. var transaction = _this.db.transaction([targetStore], "readwrite");
  62725. // the transaction could abort because of a QuotaExceededError error
  62726. transaction.onabort = function (event) {
  62727. try {
  62728. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  62729. var error = event.srcElement['error'];
  62730. if (error && error.name === "QuotaExceededError") {
  62731. _this.hasReachedQuota = true;
  62732. }
  62733. }
  62734. catch (ex) { }
  62735. callback(fileData);
  62736. };
  62737. transaction.oncomplete = function (event) {
  62738. callback(fileData);
  62739. };
  62740. var newFile;
  62741. if (targetStore === "scenes") {
  62742. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  62743. }
  62744. else {
  62745. newFile = { textureUrl: url, data: fileData };
  62746. }
  62747. try {
  62748. // Put the scene into the database
  62749. var addRequest = transaction.objectStore(targetStore).put(newFile);
  62750. addRequest.onsuccess = function (event) {
  62751. };
  62752. addRequest.onerror = function (event) {
  62753. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  62754. };
  62755. }
  62756. catch (ex) {
  62757. callback(fileData);
  62758. }
  62759. }
  62760. else {
  62761. callback(fileData);
  62762. }
  62763. }
  62764. else {
  62765. callback();
  62766. }
  62767. }, false);
  62768. xhr.addEventListener("error", function (event) {
  62769. BABYLON.Tools.Error("error on XHR request.");
  62770. callback();
  62771. }, false);
  62772. xhr.send();
  62773. }
  62774. else {
  62775. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  62776. callback();
  62777. }
  62778. };
  62779. Database.IsUASupportingBlobStorage = true;
  62780. Database.IDBStorageEnabled = true;
  62781. Database.parseURL = function (url) {
  62782. var a = document.createElement('a');
  62783. a.href = url;
  62784. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  62785. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  62786. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  62787. return absLocation;
  62788. };
  62789. Database.ReturnFullUrlLocation = function (url) {
  62790. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  62791. return (Database.parseURL(window.location.href) + url);
  62792. }
  62793. else {
  62794. return url;
  62795. }
  62796. };
  62797. return Database;
  62798. }());
  62799. BABYLON.Database = Database;
  62800. })(BABYLON || (BABYLON = {}));
  62801. //# sourceMappingURL=babylon.database.js.map
  62802. var BABYLON;
  62803. (function (BABYLON) {
  62804. var FresnelParameters = /** @class */ (function () {
  62805. function FresnelParameters() {
  62806. this._isEnabled = true;
  62807. this.leftColor = BABYLON.Color3.White();
  62808. this.rightColor = BABYLON.Color3.Black();
  62809. this.bias = 0;
  62810. this.power = 1;
  62811. }
  62812. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  62813. get: function () {
  62814. return this._isEnabled;
  62815. },
  62816. set: function (value) {
  62817. if (this._isEnabled === value) {
  62818. return;
  62819. }
  62820. this._isEnabled = value;
  62821. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  62822. },
  62823. enumerable: true,
  62824. configurable: true
  62825. });
  62826. FresnelParameters.prototype.clone = function () {
  62827. var newFresnelParameters = new FresnelParameters();
  62828. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  62829. return newFresnelParameters;
  62830. };
  62831. FresnelParameters.prototype.serialize = function () {
  62832. var serializationObject = {};
  62833. serializationObject.isEnabled = this.isEnabled;
  62834. serializationObject.leftColor = this.leftColor;
  62835. serializationObject.rightColor = this.rightColor;
  62836. serializationObject.bias = this.bias;
  62837. serializationObject.power = this.power;
  62838. return serializationObject;
  62839. };
  62840. FresnelParameters.Parse = function (parsedFresnelParameters) {
  62841. var fresnelParameters = new FresnelParameters();
  62842. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  62843. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  62844. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  62845. fresnelParameters.bias = parsedFresnelParameters.bias;
  62846. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  62847. return fresnelParameters;
  62848. };
  62849. return FresnelParameters;
  62850. }());
  62851. BABYLON.FresnelParameters = FresnelParameters;
  62852. })(BABYLON || (BABYLON = {}));
  62853. //# sourceMappingURL=babylon.fresnelParameters.js.map
  62854. var BABYLON;
  62855. (function (BABYLON) {
  62856. var MultiMaterial = /** @class */ (function (_super) {
  62857. __extends(MultiMaterial, _super);
  62858. function MultiMaterial(name, scene) {
  62859. var _this = _super.call(this, name, scene, true) || this;
  62860. scene.multiMaterials.push(_this);
  62861. _this.subMaterials = new Array();
  62862. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  62863. return _this;
  62864. }
  62865. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  62866. get: function () {
  62867. return this._subMaterials;
  62868. },
  62869. set: function (value) {
  62870. this._subMaterials = value;
  62871. this._hookArray(value);
  62872. },
  62873. enumerable: true,
  62874. configurable: true
  62875. });
  62876. MultiMaterial.prototype._hookArray = function (array) {
  62877. var _this = this;
  62878. var oldPush = array.push;
  62879. array.push = function () {
  62880. var items = [];
  62881. for (var _i = 0; _i < arguments.length; _i++) {
  62882. items[_i] = arguments[_i];
  62883. }
  62884. var result = oldPush.apply(array, items);
  62885. _this._markAllSubMeshesAsTexturesDirty();
  62886. return result;
  62887. };
  62888. var oldSplice = array.splice;
  62889. array.splice = function (index, deleteCount) {
  62890. var deleted = oldSplice.apply(array, [index, deleteCount]);
  62891. _this._markAllSubMeshesAsTexturesDirty();
  62892. return deleted;
  62893. };
  62894. };
  62895. // Properties
  62896. MultiMaterial.prototype.getSubMaterial = function (index) {
  62897. if (index < 0 || index >= this.subMaterials.length) {
  62898. return this.getScene().defaultMaterial;
  62899. }
  62900. return this.subMaterials[index];
  62901. };
  62902. MultiMaterial.prototype.getActiveTextures = function () {
  62903. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  62904. if (subMaterial) {
  62905. return subMaterial.getActiveTextures();
  62906. }
  62907. else {
  62908. return [];
  62909. }
  62910. }));
  62911. var _a;
  62912. };
  62913. // Methods
  62914. MultiMaterial.prototype.getClassName = function () {
  62915. return "MultiMaterial";
  62916. };
  62917. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  62918. for (var index = 0; index < this.subMaterials.length; index++) {
  62919. var subMaterial = this.subMaterials[index];
  62920. if (subMaterial) {
  62921. if (subMaterial.storeEffectOnSubMeshes) {
  62922. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  62923. return false;
  62924. }
  62925. continue;
  62926. }
  62927. if (!subMaterial.isReady(mesh)) {
  62928. return false;
  62929. }
  62930. }
  62931. }
  62932. return true;
  62933. };
  62934. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  62935. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  62936. for (var index = 0; index < this.subMaterials.length; index++) {
  62937. var subMaterial = null;
  62938. var current = this.subMaterials[index];
  62939. if (cloneChildren && current) {
  62940. subMaterial = current.clone(name + "-" + current.name);
  62941. }
  62942. else {
  62943. subMaterial = this.subMaterials[index];
  62944. }
  62945. newMultiMaterial.subMaterials.push(subMaterial);
  62946. }
  62947. return newMultiMaterial;
  62948. };
  62949. MultiMaterial.prototype.serialize = function () {
  62950. var serializationObject = {};
  62951. serializationObject.name = this.name;
  62952. serializationObject.id = this.id;
  62953. if (BABYLON.Tags) {
  62954. serializationObject.tags = BABYLON.Tags.GetTags(this);
  62955. }
  62956. serializationObject.materials = [];
  62957. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  62958. var subMat = this.subMaterials[matIndex];
  62959. if (subMat) {
  62960. serializationObject.materials.push(subMat.id);
  62961. }
  62962. else {
  62963. serializationObject.materials.push(null);
  62964. }
  62965. }
  62966. return serializationObject;
  62967. };
  62968. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  62969. var scene = this.getScene();
  62970. if (!scene) {
  62971. return;
  62972. }
  62973. var index = scene.multiMaterials.indexOf(this);
  62974. if (index >= 0) {
  62975. scene.multiMaterials.splice(index, 1);
  62976. }
  62977. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  62978. };
  62979. return MultiMaterial;
  62980. }(BABYLON.Material));
  62981. BABYLON.MultiMaterial = MultiMaterial;
  62982. })(BABYLON || (BABYLON = {}));
  62983. //# sourceMappingURL=babylon.multiMaterial.js.map
  62984. var BABYLON;
  62985. (function (BABYLON) {
  62986. var FreeCameraTouchInput = /** @class */ (function () {
  62987. function FreeCameraTouchInput() {
  62988. this._offsetX = null;
  62989. this._offsetY = null;
  62990. this._pointerPressed = new Array();
  62991. this.touchAngularSensibility = 200000.0;
  62992. this.touchMoveSensibility = 250.0;
  62993. }
  62994. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  62995. var _this = this;
  62996. var previousPosition = null;
  62997. if (this._pointerInput === undefined) {
  62998. this._onLostFocus = function (evt) {
  62999. _this._offsetX = null;
  63000. _this._offsetY = null;
  63001. };
  63002. this._pointerInput = function (p, s) {
  63003. var evt = p.event;
  63004. if (evt.pointerType === "mouse") {
  63005. return;
  63006. }
  63007. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  63008. if (!noPreventDefault) {
  63009. evt.preventDefault();
  63010. }
  63011. _this._pointerPressed.push(evt.pointerId);
  63012. if (_this._pointerPressed.length !== 1) {
  63013. return;
  63014. }
  63015. previousPosition = {
  63016. x: evt.clientX,
  63017. y: evt.clientY
  63018. };
  63019. }
  63020. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  63021. if (!noPreventDefault) {
  63022. evt.preventDefault();
  63023. }
  63024. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63025. if (index === -1) {
  63026. return;
  63027. }
  63028. _this._pointerPressed.splice(index, 1);
  63029. if (index != 0) {
  63030. return;
  63031. }
  63032. previousPosition = null;
  63033. _this._offsetX = null;
  63034. _this._offsetY = null;
  63035. }
  63036. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  63037. if (!noPreventDefault) {
  63038. evt.preventDefault();
  63039. }
  63040. if (!previousPosition) {
  63041. return;
  63042. }
  63043. var index = _this._pointerPressed.indexOf(evt.pointerId);
  63044. if (index != 0) {
  63045. return;
  63046. }
  63047. _this._offsetX = evt.clientX - previousPosition.x;
  63048. _this._offsetY = -(evt.clientY - previousPosition.y);
  63049. }
  63050. };
  63051. }
  63052. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  63053. if (this._onLostFocus) {
  63054. element.addEventListener("blur", this._onLostFocus);
  63055. }
  63056. };
  63057. FreeCameraTouchInput.prototype.detachControl = function (element) {
  63058. if (this._pointerInput && element) {
  63059. if (this._observer) {
  63060. this.camera.getScene().onPointerObservable.remove(this._observer);
  63061. this._observer = null;
  63062. }
  63063. if (this._onLostFocus) {
  63064. element.removeEventListener("blur", this._onLostFocus);
  63065. this._onLostFocus = null;
  63066. }
  63067. this._pointerPressed = [];
  63068. this._offsetX = null;
  63069. this._offsetY = null;
  63070. }
  63071. };
  63072. FreeCameraTouchInput.prototype.checkInputs = function () {
  63073. if (this._offsetX && this._offsetY) {
  63074. var camera = this.camera;
  63075. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  63076. if (this._pointerPressed.length > 1) {
  63077. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  63078. }
  63079. else {
  63080. var speed = camera._computeLocalCameraSpeed();
  63081. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  63082. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  63083. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  63084. }
  63085. }
  63086. };
  63087. FreeCameraTouchInput.prototype.getClassName = function () {
  63088. return "FreeCameraTouchInput";
  63089. };
  63090. FreeCameraTouchInput.prototype.getSimpleName = function () {
  63091. return "touch";
  63092. };
  63093. __decorate([
  63094. BABYLON.serialize()
  63095. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  63096. __decorate([
  63097. BABYLON.serialize()
  63098. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  63099. return FreeCameraTouchInput;
  63100. }());
  63101. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  63102. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  63103. })(BABYLON || (BABYLON = {}));
  63104. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  63105. var BABYLON;
  63106. (function (BABYLON) {
  63107. // We're mainly based on the logic defined into the FreeCamera code
  63108. var TouchCamera = /** @class */ (function (_super) {
  63109. __extends(TouchCamera, _super);
  63110. //-- end properties for backward compatibility for inputs
  63111. function TouchCamera(name, position, scene) {
  63112. var _this = _super.call(this, name, position, scene) || this;
  63113. _this.inputs.addTouch();
  63114. _this._setupInputs();
  63115. return _this;
  63116. }
  63117. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  63118. //-- Begin properties for backward compatibility for inputs
  63119. get: function () {
  63120. var touch = this.inputs.attached["touch"];
  63121. if (touch)
  63122. return touch.touchAngularSensibility;
  63123. return 0;
  63124. },
  63125. set: function (value) {
  63126. var touch = this.inputs.attached["touch"];
  63127. if (touch)
  63128. touch.touchAngularSensibility = value;
  63129. },
  63130. enumerable: true,
  63131. configurable: true
  63132. });
  63133. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  63134. get: function () {
  63135. var touch = this.inputs.attached["touch"];
  63136. if (touch)
  63137. return touch.touchMoveSensibility;
  63138. return 0;
  63139. },
  63140. set: function (value) {
  63141. var touch = this.inputs.attached["touch"];
  63142. if (touch)
  63143. touch.touchMoveSensibility = value;
  63144. },
  63145. enumerable: true,
  63146. configurable: true
  63147. });
  63148. TouchCamera.prototype.getClassName = function () {
  63149. return "TouchCamera";
  63150. };
  63151. TouchCamera.prototype._setupInputs = function () {
  63152. var mouse = this.inputs.attached["mouse"];
  63153. if (mouse) {
  63154. mouse.touchEnabled = false;
  63155. }
  63156. };
  63157. return TouchCamera;
  63158. }(BABYLON.FreeCamera));
  63159. BABYLON.TouchCamera = TouchCamera;
  63160. })(BABYLON || (BABYLON = {}));
  63161. //# sourceMappingURL=babylon.touchCamera.js.map
  63162. var BABYLON;
  63163. (function (BABYLON) {
  63164. var ProceduralTexture = /** @class */ (function (_super) {
  63165. __extends(ProceduralTexture, _super);
  63166. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  63167. if (fallbackTexture === void 0) { fallbackTexture = null; }
  63168. if (generateMipMaps === void 0) { generateMipMaps = true; }
  63169. if (isCube === void 0) { isCube = false; }
  63170. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63171. _this.isCube = isCube;
  63172. _this.isEnabled = true;
  63173. _this._currentRefreshId = -1;
  63174. _this._refreshRate = 1;
  63175. _this._vertexBuffers = {};
  63176. _this._uniforms = new Array();
  63177. _this._samplers = new Array();
  63178. _this._textures = {};
  63179. _this._floats = {};
  63180. _this._floatsArrays = {};
  63181. _this._colors3 = {};
  63182. _this._colors4 = {};
  63183. _this._vectors2 = {};
  63184. _this._vectors3 = {};
  63185. _this._matrices = {};
  63186. _this._fallbackTextureUsed = false;
  63187. scene._proceduralTextures.push(_this);
  63188. _this._engine = scene.getEngine();
  63189. _this.name = name;
  63190. _this.isRenderTarget = true;
  63191. _this._size = size;
  63192. _this._generateMipMaps = generateMipMaps;
  63193. _this.setFragment(fragment);
  63194. _this._fallbackTexture = fallbackTexture;
  63195. if (isCube) {
  63196. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  63197. _this.setFloat("face", 0);
  63198. }
  63199. else {
  63200. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  63201. }
  63202. // VBO
  63203. var vertices = [];
  63204. vertices.push(1, 1);
  63205. vertices.push(-1, 1);
  63206. vertices.push(-1, -1);
  63207. vertices.push(1, -1);
  63208. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  63209. _this._createIndexBuffer();
  63210. return _this;
  63211. }
  63212. ProceduralTexture.prototype._createIndexBuffer = function () {
  63213. var engine = this._engine;
  63214. // Indices
  63215. var indices = [];
  63216. indices.push(0);
  63217. indices.push(1);
  63218. indices.push(2);
  63219. indices.push(0);
  63220. indices.push(2);
  63221. indices.push(3);
  63222. this._indexBuffer = engine.createIndexBuffer(indices);
  63223. };
  63224. ProceduralTexture.prototype._rebuild = function () {
  63225. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63226. if (vb) {
  63227. vb._rebuild();
  63228. }
  63229. this._createIndexBuffer();
  63230. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63231. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63232. }
  63233. };
  63234. ProceduralTexture.prototype.reset = function () {
  63235. if (this._effect === undefined) {
  63236. return;
  63237. }
  63238. var engine = this._engine;
  63239. engine._releaseEffect(this._effect);
  63240. };
  63241. ProceduralTexture.prototype.isReady = function () {
  63242. var _this = this;
  63243. var engine = this._engine;
  63244. var shaders;
  63245. if (!this._fragment) {
  63246. return false;
  63247. }
  63248. if (this._fallbackTextureUsed) {
  63249. return true;
  63250. }
  63251. if (this._fragment.fragmentElement !== undefined) {
  63252. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  63253. }
  63254. else {
  63255. shaders = { vertex: "procedural", fragment: this._fragment };
  63256. }
  63257. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  63258. _this.releaseInternalTexture();
  63259. if (_this._fallbackTexture) {
  63260. _this._texture = _this._fallbackTexture._texture;
  63261. if (_this._texture) {
  63262. _this._texture.incrementReferences();
  63263. }
  63264. }
  63265. _this._fallbackTextureUsed = true;
  63266. });
  63267. return this._effect.isReady();
  63268. };
  63269. ProceduralTexture.prototype.resetRefreshCounter = function () {
  63270. this._currentRefreshId = -1;
  63271. };
  63272. ProceduralTexture.prototype.setFragment = function (fragment) {
  63273. this._fragment = fragment;
  63274. };
  63275. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  63276. get: function () {
  63277. return this._refreshRate;
  63278. },
  63279. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63280. set: function (value) {
  63281. this._refreshRate = value;
  63282. this.resetRefreshCounter();
  63283. },
  63284. enumerable: true,
  63285. configurable: true
  63286. });
  63287. ProceduralTexture.prototype._shouldRender = function () {
  63288. if (!this.isEnabled || !this.isReady() || !this._texture) {
  63289. return false;
  63290. }
  63291. if (this._fallbackTextureUsed) {
  63292. return false;
  63293. }
  63294. if (this._currentRefreshId === -1) {
  63295. this._currentRefreshId = 1;
  63296. return true;
  63297. }
  63298. if (this.refreshRate === this._currentRefreshId) {
  63299. this._currentRefreshId = 1;
  63300. return true;
  63301. }
  63302. this._currentRefreshId++;
  63303. return false;
  63304. };
  63305. ProceduralTexture.prototype.getRenderSize = function () {
  63306. return this._size;
  63307. };
  63308. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  63309. if (this._fallbackTextureUsed) {
  63310. return;
  63311. }
  63312. this.releaseInternalTexture();
  63313. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  63314. };
  63315. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  63316. if (this._uniforms.indexOf(uniformName) === -1) {
  63317. this._uniforms.push(uniformName);
  63318. }
  63319. };
  63320. ProceduralTexture.prototype.setTexture = function (name, texture) {
  63321. if (this._samplers.indexOf(name) === -1) {
  63322. this._samplers.push(name);
  63323. }
  63324. this._textures[name] = texture;
  63325. return this;
  63326. };
  63327. ProceduralTexture.prototype.setFloat = function (name, value) {
  63328. this._checkUniform(name);
  63329. this._floats[name] = value;
  63330. return this;
  63331. };
  63332. ProceduralTexture.prototype.setFloats = function (name, value) {
  63333. this._checkUniform(name);
  63334. this._floatsArrays[name] = value;
  63335. return this;
  63336. };
  63337. ProceduralTexture.prototype.setColor3 = function (name, value) {
  63338. this._checkUniform(name);
  63339. this._colors3[name] = value;
  63340. return this;
  63341. };
  63342. ProceduralTexture.prototype.setColor4 = function (name, value) {
  63343. this._checkUniform(name);
  63344. this._colors4[name] = value;
  63345. return this;
  63346. };
  63347. ProceduralTexture.prototype.setVector2 = function (name, value) {
  63348. this._checkUniform(name);
  63349. this._vectors2[name] = value;
  63350. return this;
  63351. };
  63352. ProceduralTexture.prototype.setVector3 = function (name, value) {
  63353. this._checkUniform(name);
  63354. this._vectors3[name] = value;
  63355. return this;
  63356. };
  63357. ProceduralTexture.prototype.setMatrix = function (name, value) {
  63358. this._checkUniform(name);
  63359. this._matrices[name] = value;
  63360. return this;
  63361. };
  63362. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63363. var scene = this.getScene();
  63364. if (!scene) {
  63365. return;
  63366. }
  63367. var engine = this._engine;
  63368. // Render
  63369. engine.enableEffect(this._effect);
  63370. engine.setState(false);
  63371. // Texture
  63372. for (var name in this._textures) {
  63373. this._effect.setTexture(name, this._textures[name]);
  63374. }
  63375. // Float
  63376. for (name in this._floats) {
  63377. this._effect.setFloat(name, this._floats[name]);
  63378. }
  63379. // Floats
  63380. for (name in this._floatsArrays) {
  63381. this._effect.setArray(name, this._floatsArrays[name]);
  63382. }
  63383. // Color3
  63384. for (name in this._colors3) {
  63385. this._effect.setColor3(name, this._colors3[name]);
  63386. }
  63387. // Color4
  63388. for (name in this._colors4) {
  63389. var color = this._colors4[name];
  63390. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  63391. }
  63392. // Vector2
  63393. for (name in this._vectors2) {
  63394. this._effect.setVector2(name, this._vectors2[name]);
  63395. }
  63396. // Vector3
  63397. for (name in this._vectors3) {
  63398. this._effect.setVector3(name, this._vectors3[name]);
  63399. }
  63400. // Matrix
  63401. for (name in this._matrices) {
  63402. this._effect.setMatrix(name, this._matrices[name]);
  63403. }
  63404. if (!this._texture) {
  63405. return;
  63406. }
  63407. if (this.isCube) {
  63408. for (var face = 0; face < 6; face++) {
  63409. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  63410. // VBOs
  63411. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63412. this._effect.setFloat("face", face);
  63413. // Clear
  63414. engine.clear(scene.clearColor, true, true, true);
  63415. // Draw order
  63416. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63417. // Mipmaps
  63418. if (face === 5) {
  63419. engine.generateMipMapsForCubemap(this._texture);
  63420. }
  63421. }
  63422. }
  63423. else {
  63424. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  63425. // VBOs
  63426. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  63427. // Clear
  63428. engine.clear(scene.clearColor, true, true, true);
  63429. // Draw order
  63430. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  63431. }
  63432. // Unbind
  63433. engine.unBindFramebuffer(this._texture, this.isCube);
  63434. if (this.onGenerated) {
  63435. this.onGenerated();
  63436. }
  63437. };
  63438. ProceduralTexture.prototype.clone = function () {
  63439. var textureSize = this.getSize();
  63440. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  63441. // Base texture
  63442. newTexture.hasAlpha = this.hasAlpha;
  63443. newTexture.level = this.level;
  63444. // RenderTarget Texture
  63445. newTexture.coordinatesMode = this.coordinatesMode;
  63446. return newTexture;
  63447. };
  63448. ProceduralTexture.prototype.dispose = function () {
  63449. var scene = this.getScene();
  63450. if (!scene) {
  63451. return;
  63452. }
  63453. var index = scene._proceduralTextures.indexOf(this);
  63454. if (index >= 0) {
  63455. scene._proceduralTextures.splice(index, 1);
  63456. }
  63457. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63458. if (vertexBuffer) {
  63459. vertexBuffer.dispose();
  63460. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63461. }
  63462. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  63463. this._indexBuffer = null;
  63464. }
  63465. _super.prototype.dispose.call(this);
  63466. };
  63467. return ProceduralTexture;
  63468. }(BABYLON.Texture));
  63469. BABYLON.ProceduralTexture = ProceduralTexture;
  63470. })(BABYLON || (BABYLON = {}));
  63471. //# sourceMappingURL=babylon.proceduralTexture.js.map
  63472. var BABYLON;
  63473. (function (BABYLON) {
  63474. var CustomProceduralTexture = /** @class */ (function (_super) {
  63475. __extends(CustomProceduralTexture, _super);
  63476. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  63477. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  63478. _this._animate = true;
  63479. _this._time = 0;
  63480. _this._texturePath = texturePath;
  63481. //Try to load json
  63482. _this.loadJson(texturePath);
  63483. _this.refreshRate = 1;
  63484. return _this;
  63485. }
  63486. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  63487. var _this = this;
  63488. var noConfigFile = function () {
  63489. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  63490. try {
  63491. _this.setFragment(_this._texturePath);
  63492. }
  63493. catch (ex) {
  63494. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  63495. }
  63496. };
  63497. var configFileUrl = jsonUrl + "/config.json";
  63498. var xhr = new XMLHttpRequest();
  63499. xhr.open("GET", configFileUrl, true);
  63500. xhr.addEventListener("load", function () {
  63501. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  63502. try {
  63503. _this._config = JSON.parse(xhr.response);
  63504. _this.updateShaderUniforms();
  63505. _this.updateTextures();
  63506. _this.setFragment(_this._texturePath + "/custom");
  63507. _this._animate = _this._config.animate;
  63508. _this.refreshRate = _this._config.refreshrate;
  63509. }
  63510. catch (ex) {
  63511. noConfigFile();
  63512. }
  63513. }
  63514. else {
  63515. noConfigFile();
  63516. }
  63517. }, false);
  63518. xhr.addEventListener("error", function () {
  63519. noConfigFile();
  63520. }, false);
  63521. try {
  63522. xhr.send();
  63523. }
  63524. catch (ex) {
  63525. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  63526. }
  63527. };
  63528. CustomProceduralTexture.prototype.isReady = function () {
  63529. if (!_super.prototype.isReady.call(this)) {
  63530. return false;
  63531. }
  63532. for (var name in this._textures) {
  63533. var texture = this._textures[name];
  63534. if (!texture.isReady()) {
  63535. return false;
  63536. }
  63537. }
  63538. return true;
  63539. };
  63540. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  63541. var scene = this.getScene();
  63542. if (this._animate && scene) {
  63543. this._time += scene.getAnimationRatio() * 0.03;
  63544. this.updateShaderUniforms();
  63545. }
  63546. _super.prototype.render.call(this, useCameraPostProcess);
  63547. };
  63548. CustomProceduralTexture.prototype.updateTextures = function () {
  63549. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  63550. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  63551. }
  63552. };
  63553. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  63554. if (this._config) {
  63555. for (var j = 0; j < this._config.uniforms.length; j++) {
  63556. var uniform = this._config.uniforms[j];
  63557. switch (uniform.type) {
  63558. case "float":
  63559. this.setFloat(uniform.name, uniform.value);
  63560. break;
  63561. case "color3":
  63562. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  63563. break;
  63564. case "color4":
  63565. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  63566. break;
  63567. case "vector2":
  63568. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  63569. break;
  63570. case "vector3":
  63571. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  63572. break;
  63573. }
  63574. }
  63575. }
  63576. this.setFloat("time", this._time);
  63577. };
  63578. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  63579. get: function () {
  63580. return this._animate;
  63581. },
  63582. set: function (value) {
  63583. this._animate = value;
  63584. },
  63585. enumerable: true,
  63586. configurable: true
  63587. });
  63588. return CustomProceduralTexture;
  63589. }(BABYLON.ProceduralTexture));
  63590. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  63591. })(BABYLON || (BABYLON = {}));
  63592. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  63593. var BABYLON;
  63594. (function (BABYLON) {
  63595. var FreeCameraGamepadInput = /** @class */ (function () {
  63596. function FreeCameraGamepadInput() {
  63597. this.gamepadAngularSensibility = 200;
  63598. this.gamepadMoveSensibility = 40;
  63599. // private members
  63600. this._cameraTransform = BABYLON.Matrix.Identity();
  63601. this._deltaTransform = BABYLON.Vector3.Zero();
  63602. this._vector3 = BABYLON.Vector3.Zero();
  63603. this._vector2 = BABYLON.Vector2.Zero();
  63604. }
  63605. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63606. var _this = this;
  63607. var manager = this.camera.getScene().gamepadManager;
  63608. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63609. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63610. // prioritize XBOX gamepads.
  63611. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63612. _this.gamepad = gamepad;
  63613. }
  63614. }
  63615. });
  63616. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63617. if (_this.gamepad === gamepad) {
  63618. _this.gamepad = null;
  63619. }
  63620. });
  63621. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63622. };
  63623. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  63624. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63625. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63626. this.gamepad = null;
  63627. };
  63628. FreeCameraGamepadInput.prototype.checkInputs = function () {
  63629. if (this.gamepad && this.gamepad.leftStick) {
  63630. var camera = this.camera;
  63631. var LSValues = this.gamepad.leftStick;
  63632. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  63633. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63634. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  63635. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  63636. var RSValues = this.gamepad.rightStick;
  63637. if (RSValues) {
  63638. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  63639. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  63640. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  63641. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  63642. }
  63643. else {
  63644. RSValues = { x: 0, y: 0 };
  63645. }
  63646. if (!camera.rotationQuaternion) {
  63647. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  63648. }
  63649. else {
  63650. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  63651. }
  63652. var speed = camera._computeLocalCameraSpeed() * 50.0;
  63653. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  63654. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  63655. camera.cameraDirection.addInPlace(this._deltaTransform);
  63656. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  63657. camera.cameraRotation.addInPlace(this._vector2);
  63658. }
  63659. };
  63660. FreeCameraGamepadInput.prototype.getClassName = function () {
  63661. return "FreeCameraGamepadInput";
  63662. };
  63663. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  63664. return "gamepad";
  63665. };
  63666. __decorate([
  63667. BABYLON.serialize()
  63668. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  63669. __decorate([
  63670. BABYLON.serialize()
  63671. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63672. return FreeCameraGamepadInput;
  63673. }());
  63674. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  63675. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  63676. })(BABYLON || (BABYLON = {}));
  63677. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  63678. var BABYLON;
  63679. (function (BABYLON) {
  63680. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  63681. function ArcRotateCameraGamepadInput() {
  63682. this.gamepadRotationSensibility = 80;
  63683. this.gamepadMoveSensibility = 40;
  63684. }
  63685. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  63686. var _this = this;
  63687. var manager = this.camera.getScene().gamepadManager;
  63688. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  63689. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  63690. // prioritize XBOX gamepads.
  63691. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  63692. _this.gamepad = gamepad;
  63693. }
  63694. }
  63695. });
  63696. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  63697. if (_this.gamepad === gamepad) {
  63698. _this.gamepad = null;
  63699. }
  63700. });
  63701. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  63702. };
  63703. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  63704. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  63705. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  63706. this.gamepad = null;
  63707. };
  63708. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  63709. if (this.gamepad) {
  63710. var camera = this.camera;
  63711. var RSValues = this.gamepad.rightStick;
  63712. if (RSValues) {
  63713. if (RSValues.x != 0) {
  63714. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  63715. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  63716. camera.inertialAlphaOffset += normalizedRX;
  63717. }
  63718. }
  63719. if (RSValues.y != 0) {
  63720. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  63721. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  63722. camera.inertialBetaOffset += normalizedRY;
  63723. }
  63724. }
  63725. }
  63726. var LSValues = this.gamepad.leftStick;
  63727. if (LSValues && LSValues.y != 0) {
  63728. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  63729. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  63730. this.camera.inertialRadiusOffset -= normalizedLY;
  63731. }
  63732. }
  63733. }
  63734. };
  63735. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  63736. return "ArcRotateCameraGamepadInput";
  63737. };
  63738. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  63739. return "gamepad";
  63740. };
  63741. __decorate([
  63742. BABYLON.serialize()
  63743. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  63744. __decorate([
  63745. BABYLON.serialize()
  63746. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  63747. return ArcRotateCameraGamepadInput;
  63748. }());
  63749. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  63750. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  63751. })(BABYLON || (BABYLON = {}));
  63752. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  63753. var BABYLON;
  63754. (function (BABYLON) {
  63755. var GamepadManager = /** @class */ (function () {
  63756. function GamepadManager(_scene) {
  63757. var _this = this;
  63758. this._scene = _scene;
  63759. this._babylonGamepads = [];
  63760. this._oneGamepadConnected = false;
  63761. this._isMonitoring = false;
  63762. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  63763. if (!BABYLON.Tools.IsWindowObjectExist()) {
  63764. this._gamepadEventSupported = false;
  63765. }
  63766. else {
  63767. this._gamepadEventSupported = 'GamepadEvent' in window;
  63768. this._gamepadSupport = (navigator.getGamepads ||
  63769. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  63770. }
  63771. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  63772. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  63773. for (var i in _this._babylonGamepads) {
  63774. var gamepad = _this._babylonGamepads[i];
  63775. if (gamepad && gamepad._isConnected) {
  63776. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  63777. }
  63778. }
  63779. });
  63780. this._onGamepadConnectedEvent = function (evt) {
  63781. var gamepad = evt.gamepad;
  63782. if (gamepad.index in _this._babylonGamepads) {
  63783. if (_this._babylonGamepads[gamepad.index].isConnected) {
  63784. return;
  63785. }
  63786. }
  63787. var newGamepad;
  63788. if (_this._babylonGamepads[gamepad.index]) {
  63789. newGamepad = _this._babylonGamepads[gamepad.index];
  63790. newGamepad.browserGamepad = gamepad;
  63791. newGamepad._isConnected = true;
  63792. }
  63793. else {
  63794. newGamepad = _this._addNewGamepad(gamepad);
  63795. }
  63796. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  63797. _this._startMonitoringGamepads();
  63798. };
  63799. this._onGamepadDisconnectedEvent = function (evt) {
  63800. var gamepad = evt.gamepad;
  63801. // Remove the gamepad from the list of gamepads to monitor.
  63802. for (var i in _this._babylonGamepads) {
  63803. if (_this._babylonGamepads[i].index === gamepad.index) {
  63804. var disconnectedGamepad = _this._babylonGamepads[i];
  63805. disconnectedGamepad._isConnected = false;
  63806. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  63807. break;
  63808. }
  63809. }
  63810. };
  63811. if (this._gamepadSupport) {
  63812. //first add already-connected gamepads
  63813. this._updateGamepadObjects();
  63814. if (this._babylonGamepads.length) {
  63815. this._startMonitoringGamepads();
  63816. }
  63817. // Checking if the gamepad connected event is supported (like in Firefox)
  63818. if (this._gamepadEventSupported) {
  63819. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  63820. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  63821. }
  63822. else {
  63823. this._startMonitoringGamepads();
  63824. }
  63825. }
  63826. }
  63827. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  63828. get: function () {
  63829. return this._babylonGamepads;
  63830. },
  63831. enumerable: true,
  63832. configurable: true
  63833. });
  63834. GamepadManager.prototype.getGamepadByType = function (type) {
  63835. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  63836. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  63837. var gamepad = _a[_i];
  63838. if (gamepad && gamepad.type === type) {
  63839. return gamepad;
  63840. }
  63841. }
  63842. return null;
  63843. };
  63844. GamepadManager.prototype.dispose = function () {
  63845. if (this._gamepadEventSupported) {
  63846. if (this._onGamepadConnectedEvent) {
  63847. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  63848. }
  63849. if (this._onGamepadDisconnectedEvent) {
  63850. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  63851. }
  63852. this._onGamepadConnectedEvent = null;
  63853. this._onGamepadDisconnectedEvent = null;
  63854. }
  63855. this._babylonGamepads.forEach(function (gamepad) {
  63856. gamepad.dispose();
  63857. });
  63858. this.onGamepadConnectedObservable.clear();
  63859. this.onGamepadDisconnectedObservable.clear();
  63860. this._oneGamepadConnected = false;
  63861. this._stopMonitoringGamepads();
  63862. this._babylonGamepads = [];
  63863. };
  63864. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  63865. if (!this._oneGamepadConnected) {
  63866. this._oneGamepadConnected = true;
  63867. }
  63868. var newGamepad;
  63869. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  63870. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  63871. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  63872. }
  63873. else if (gamepad.pose) {
  63874. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  63875. }
  63876. else {
  63877. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  63878. }
  63879. this._babylonGamepads[newGamepad.index] = newGamepad;
  63880. return newGamepad;
  63881. };
  63882. GamepadManager.prototype._startMonitoringGamepads = function () {
  63883. if (!this._isMonitoring) {
  63884. this._isMonitoring = true;
  63885. //back-comp
  63886. if (!this._scene) {
  63887. this._checkGamepadsStatus();
  63888. }
  63889. }
  63890. };
  63891. GamepadManager.prototype._stopMonitoringGamepads = function () {
  63892. this._isMonitoring = false;
  63893. };
  63894. GamepadManager.prototype._checkGamepadsStatus = function () {
  63895. var _this = this;
  63896. // Hack to be compatible Chrome
  63897. this._updateGamepadObjects();
  63898. for (var i in this._babylonGamepads) {
  63899. var gamepad = this._babylonGamepads[i];
  63900. if (!gamepad || !gamepad.isConnected) {
  63901. continue;
  63902. }
  63903. gamepad.update();
  63904. }
  63905. if (this._isMonitoring && !this._scene) {
  63906. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  63907. }
  63908. };
  63909. // This function is called only on Chrome, which does not properly support
  63910. // connection/disconnection events and forces you to recopy again the gamepad object
  63911. GamepadManager.prototype._updateGamepadObjects = function () {
  63912. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  63913. for (var i = 0; i < gamepads.length; i++) {
  63914. if (gamepads[i]) {
  63915. if (!this._babylonGamepads[gamepads[i].index]) {
  63916. var newGamepad = this._addNewGamepad(gamepads[i]);
  63917. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  63918. }
  63919. else {
  63920. // Forced to copy again this object for Chrome for unknown reason
  63921. this._babylonGamepads[i].browserGamepad = gamepads[i];
  63922. if (!this._babylonGamepads[i].isConnected) {
  63923. this._babylonGamepads[i]._isConnected = true;
  63924. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  63925. }
  63926. }
  63927. }
  63928. }
  63929. };
  63930. return GamepadManager;
  63931. }());
  63932. BABYLON.GamepadManager = GamepadManager;
  63933. })(BABYLON || (BABYLON = {}));
  63934. //# sourceMappingURL=babylon.gamepadManager.js.map
  63935. var BABYLON;
  63936. (function (BABYLON) {
  63937. var StickValues = /** @class */ (function () {
  63938. function StickValues(x, y) {
  63939. this.x = x;
  63940. this.y = y;
  63941. }
  63942. return StickValues;
  63943. }());
  63944. BABYLON.StickValues = StickValues;
  63945. var Gamepad = /** @class */ (function () {
  63946. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  63947. if (leftStickX === void 0) { leftStickX = 0; }
  63948. if (leftStickY === void 0) { leftStickY = 1; }
  63949. if (rightStickX === void 0) { rightStickX = 2; }
  63950. if (rightStickY === void 0) { rightStickY = 3; }
  63951. this.id = id;
  63952. this.index = index;
  63953. this.browserGamepad = browserGamepad;
  63954. this._isConnected = true;
  63955. this._invertLeftStickY = false;
  63956. this.type = Gamepad.GAMEPAD;
  63957. this._leftStickAxisX = leftStickX;
  63958. this._leftStickAxisY = leftStickY;
  63959. this._rightStickAxisX = rightStickX;
  63960. this._rightStickAxisY = rightStickY;
  63961. if (this.browserGamepad.axes.length >= 2) {
  63962. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  63963. }
  63964. if (this.browserGamepad.axes.length >= 4) {
  63965. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  63966. }
  63967. }
  63968. Object.defineProperty(Gamepad.prototype, "isConnected", {
  63969. get: function () {
  63970. return this._isConnected;
  63971. },
  63972. enumerable: true,
  63973. configurable: true
  63974. });
  63975. Gamepad.prototype.onleftstickchanged = function (callback) {
  63976. this._onleftstickchanged = callback;
  63977. };
  63978. Gamepad.prototype.onrightstickchanged = function (callback) {
  63979. this._onrightstickchanged = callback;
  63980. };
  63981. Object.defineProperty(Gamepad.prototype, "leftStick", {
  63982. get: function () {
  63983. return this._leftStick;
  63984. },
  63985. set: function (newValues) {
  63986. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  63987. this._onleftstickchanged(newValues);
  63988. }
  63989. this._leftStick = newValues;
  63990. },
  63991. enumerable: true,
  63992. configurable: true
  63993. });
  63994. Object.defineProperty(Gamepad.prototype, "rightStick", {
  63995. get: function () {
  63996. return this._rightStick;
  63997. },
  63998. set: function (newValues) {
  63999. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  64000. this._onrightstickchanged(newValues);
  64001. }
  64002. this._rightStick = newValues;
  64003. },
  64004. enumerable: true,
  64005. configurable: true
  64006. });
  64007. Gamepad.prototype.update = function () {
  64008. if (this._leftStick) {
  64009. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  64010. if (this._invertLeftStickY) {
  64011. this.leftStick.y *= -1;
  64012. }
  64013. }
  64014. if (this._rightStick) {
  64015. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  64016. }
  64017. };
  64018. Gamepad.prototype.dispose = function () {
  64019. };
  64020. Gamepad.GAMEPAD = 0;
  64021. Gamepad.GENERIC = 1;
  64022. Gamepad.XBOX = 2;
  64023. Gamepad.POSE_ENABLED = 3;
  64024. return Gamepad;
  64025. }());
  64026. BABYLON.Gamepad = Gamepad;
  64027. var GenericPad = /** @class */ (function (_super) {
  64028. __extends(GenericPad, _super);
  64029. function GenericPad(id, index, browserGamepad) {
  64030. var _this = _super.call(this, id, index, browserGamepad) || this;
  64031. _this.onButtonDownObservable = new BABYLON.Observable();
  64032. _this.onButtonUpObservable = new BABYLON.Observable();
  64033. _this.type = Gamepad.GENERIC;
  64034. _this._buttons = new Array(browserGamepad.buttons.length);
  64035. return _this;
  64036. }
  64037. GenericPad.prototype.onbuttondown = function (callback) {
  64038. this._onbuttondown = callback;
  64039. };
  64040. GenericPad.prototype.onbuttonup = function (callback) {
  64041. this._onbuttonup = callback;
  64042. };
  64043. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  64044. if (newValue !== currentValue) {
  64045. if (newValue === 1) {
  64046. if (this._onbuttondown) {
  64047. this._onbuttondown(buttonIndex);
  64048. }
  64049. this.onButtonDownObservable.notifyObservers(buttonIndex);
  64050. }
  64051. if (newValue === 0) {
  64052. if (this._onbuttonup) {
  64053. this._onbuttonup(buttonIndex);
  64054. }
  64055. this.onButtonUpObservable.notifyObservers(buttonIndex);
  64056. }
  64057. }
  64058. return newValue;
  64059. };
  64060. GenericPad.prototype.update = function () {
  64061. _super.prototype.update.call(this);
  64062. for (var index = 0; index < this._buttons.length; index++) {
  64063. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  64064. }
  64065. };
  64066. GenericPad.prototype.dispose = function () {
  64067. _super.prototype.dispose.call(this);
  64068. this.onButtonDownObservable.clear();
  64069. this.onButtonUpObservable.clear();
  64070. };
  64071. return GenericPad;
  64072. }(Gamepad));
  64073. BABYLON.GenericPad = GenericPad;
  64074. })(BABYLON || (BABYLON = {}));
  64075. //# sourceMappingURL=babylon.gamepad.js.map
  64076. var BABYLON;
  64077. (function (BABYLON) {
  64078. var Xbox360Button;
  64079. (function (Xbox360Button) {
  64080. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  64081. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  64082. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  64083. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  64084. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  64085. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  64086. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  64087. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  64088. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  64089. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  64090. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  64091. var Xbox360Dpad;
  64092. (function (Xbox360Dpad) {
  64093. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  64094. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  64095. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  64096. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  64097. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  64098. var Xbox360Pad = /** @class */ (function (_super) {
  64099. __extends(Xbox360Pad, _super);
  64100. function Xbox360Pad(id, index, gamepad, xboxOne) {
  64101. if (xboxOne === void 0) { xboxOne = false; }
  64102. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  64103. _this._leftTrigger = 0;
  64104. _this._rightTrigger = 0;
  64105. _this.onButtonDownObservable = new BABYLON.Observable();
  64106. _this.onButtonUpObservable = new BABYLON.Observable();
  64107. _this.onPadDownObservable = new BABYLON.Observable();
  64108. _this.onPadUpObservable = new BABYLON.Observable();
  64109. _this._buttonA = 0;
  64110. _this._buttonB = 0;
  64111. _this._buttonX = 0;
  64112. _this._buttonY = 0;
  64113. _this._buttonBack = 0;
  64114. _this._buttonStart = 0;
  64115. _this._buttonLB = 0;
  64116. _this._buttonRB = 0;
  64117. _this._buttonLeftStick = 0;
  64118. _this._buttonRightStick = 0;
  64119. _this._dPadUp = 0;
  64120. _this._dPadDown = 0;
  64121. _this._dPadLeft = 0;
  64122. _this._dPadRight = 0;
  64123. _this._isXboxOnePad = false;
  64124. _this.type = BABYLON.Gamepad.XBOX;
  64125. _this._isXboxOnePad = xboxOne;
  64126. return _this;
  64127. }
  64128. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  64129. this._onlefttriggerchanged = callback;
  64130. };
  64131. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  64132. this._onrighttriggerchanged = callback;
  64133. };
  64134. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  64135. get: function () {
  64136. return this._leftTrigger;
  64137. },
  64138. set: function (newValue) {
  64139. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  64140. this._onlefttriggerchanged(newValue);
  64141. }
  64142. this._leftTrigger = newValue;
  64143. },
  64144. enumerable: true,
  64145. configurable: true
  64146. });
  64147. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  64148. get: function () {
  64149. return this._rightTrigger;
  64150. },
  64151. set: function (newValue) {
  64152. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  64153. this._onrighttriggerchanged(newValue);
  64154. }
  64155. this._rightTrigger = newValue;
  64156. },
  64157. enumerable: true,
  64158. configurable: true
  64159. });
  64160. Xbox360Pad.prototype.onbuttondown = function (callback) {
  64161. this._onbuttondown = callback;
  64162. };
  64163. Xbox360Pad.prototype.onbuttonup = function (callback) {
  64164. this._onbuttonup = callback;
  64165. };
  64166. Xbox360Pad.prototype.ondpaddown = function (callback) {
  64167. this._ondpaddown = callback;
  64168. };
  64169. Xbox360Pad.prototype.ondpadup = function (callback) {
  64170. this._ondpadup = callback;
  64171. };
  64172. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  64173. if (newValue !== currentValue) {
  64174. if (newValue === 1) {
  64175. if (this._onbuttondown) {
  64176. this._onbuttondown(buttonType);
  64177. }
  64178. this.onButtonDownObservable.notifyObservers(buttonType);
  64179. }
  64180. if (newValue === 0) {
  64181. if (this._onbuttonup) {
  64182. this._onbuttonup(buttonType);
  64183. }
  64184. this.onButtonUpObservable.notifyObservers(buttonType);
  64185. }
  64186. }
  64187. return newValue;
  64188. };
  64189. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  64190. if (newValue !== currentValue) {
  64191. if (newValue === 1) {
  64192. if (this._ondpaddown) {
  64193. this._ondpaddown(buttonType);
  64194. }
  64195. this.onPadDownObservable.notifyObservers(buttonType);
  64196. }
  64197. if (newValue === 0) {
  64198. if (this._ondpadup) {
  64199. this._ondpadup(buttonType);
  64200. }
  64201. this.onPadUpObservable.notifyObservers(buttonType);
  64202. }
  64203. }
  64204. return newValue;
  64205. };
  64206. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  64207. get: function () {
  64208. return this._buttonA;
  64209. },
  64210. set: function (value) {
  64211. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  64212. },
  64213. enumerable: true,
  64214. configurable: true
  64215. });
  64216. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  64217. get: function () {
  64218. return this._buttonB;
  64219. },
  64220. set: function (value) {
  64221. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  64222. },
  64223. enumerable: true,
  64224. configurable: true
  64225. });
  64226. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  64227. get: function () {
  64228. return this._buttonX;
  64229. },
  64230. set: function (value) {
  64231. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  64232. },
  64233. enumerable: true,
  64234. configurable: true
  64235. });
  64236. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  64237. get: function () {
  64238. return this._buttonY;
  64239. },
  64240. set: function (value) {
  64241. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  64242. },
  64243. enumerable: true,
  64244. configurable: true
  64245. });
  64246. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  64247. get: function () {
  64248. return this._buttonStart;
  64249. },
  64250. set: function (value) {
  64251. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  64252. },
  64253. enumerable: true,
  64254. configurable: true
  64255. });
  64256. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  64257. get: function () {
  64258. return this._buttonBack;
  64259. },
  64260. set: function (value) {
  64261. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  64262. },
  64263. enumerable: true,
  64264. configurable: true
  64265. });
  64266. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  64267. get: function () {
  64268. return this._buttonLB;
  64269. },
  64270. set: function (value) {
  64271. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  64272. },
  64273. enumerable: true,
  64274. configurable: true
  64275. });
  64276. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  64277. get: function () {
  64278. return this._buttonRB;
  64279. },
  64280. set: function (value) {
  64281. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  64282. },
  64283. enumerable: true,
  64284. configurable: true
  64285. });
  64286. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  64287. get: function () {
  64288. return this._buttonLeftStick;
  64289. },
  64290. set: function (value) {
  64291. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  64292. },
  64293. enumerable: true,
  64294. configurable: true
  64295. });
  64296. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  64297. get: function () {
  64298. return this._buttonRightStick;
  64299. },
  64300. set: function (value) {
  64301. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  64302. },
  64303. enumerable: true,
  64304. configurable: true
  64305. });
  64306. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  64307. get: function () {
  64308. return this._dPadUp;
  64309. },
  64310. set: function (value) {
  64311. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  64312. },
  64313. enumerable: true,
  64314. configurable: true
  64315. });
  64316. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  64317. get: function () {
  64318. return this._dPadDown;
  64319. },
  64320. set: function (value) {
  64321. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  64322. },
  64323. enumerable: true,
  64324. configurable: true
  64325. });
  64326. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  64327. get: function () {
  64328. return this._dPadLeft;
  64329. },
  64330. set: function (value) {
  64331. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  64332. },
  64333. enumerable: true,
  64334. configurable: true
  64335. });
  64336. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  64337. get: function () {
  64338. return this._dPadRight;
  64339. },
  64340. set: function (value) {
  64341. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  64342. },
  64343. enumerable: true,
  64344. configurable: true
  64345. });
  64346. Xbox360Pad.prototype.update = function () {
  64347. _super.prototype.update.call(this);
  64348. if (this._isXboxOnePad) {
  64349. this.buttonA = this.browserGamepad.buttons[0].value;
  64350. this.buttonB = this.browserGamepad.buttons[1].value;
  64351. this.buttonX = this.browserGamepad.buttons[2].value;
  64352. this.buttonY = this.browserGamepad.buttons[3].value;
  64353. this.buttonLB = this.browserGamepad.buttons[4].value;
  64354. this.buttonRB = this.browserGamepad.buttons[5].value;
  64355. this.leftTrigger = this.browserGamepad.axes[2];
  64356. this.rightTrigger = this.browserGamepad.axes[5];
  64357. this.buttonBack = this.browserGamepad.buttons[9].value;
  64358. this.buttonStart = this.browserGamepad.buttons[8].value;
  64359. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  64360. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  64361. this.dPadUp = this.browserGamepad.buttons[11].value;
  64362. this.dPadDown = this.browserGamepad.buttons[12].value;
  64363. this.dPadLeft = this.browserGamepad.buttons[13].value;
  64364. this.dPadRight = this.browserGamepad.buttons[14].value;
  64365. }
  64366. else {
  64367. this.buttonA = this.browserGamepad.buttons[0].value;
  64368. this.buttonB = this.browserGamepad.buttons[1].value;
  64369. this.buttonX = this.browserGamepad.buttons[2].value;
  64370. this.buttonY = this.browserGamepad.buttons[3].value;
  64371. this.buttonLB = this.browserGamepad.buttons[4].value;
  64372. this.buttonRB = this.browserGamepad.buttons[5].value;
  64373. this.leftTrigger = this.browserGamepad.buttons[6].value;
  64374. this.rightTrigger = this.browserGamepad.buttons[7].value;
  64375. this.buttonBack = this.browserGamepad.buttons[8].value;
  64376. this.buttonStart = this.browserGamepad.buttons[9].value;
  64377. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  64378. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  64379. this.dPadUp = this.browserGamepad.buttons[12].value;
  64380. this.dPadDown = this.browserGamepad.buttons[13].value;
  64381. this.dPadLeft = this.browserGamepad.buttons[14].value;
  64382. this.dPadRight = this.browserGamepad.buttons[15].value;
  64383. }
  64384. };
  64385. Xbox360Pad.prototype.dispose = function () {
  64386. _super.prototype.dispose.call(this);
  64387. this.onButtonDownObservable.clear();
  64388. this.onButtonUpObservable.clear();
  64389. this.onPadDownObservable.clear();
  64390. this.onPadUpObservable.clear();
  64391. };
  64392. return Xbox360Pad;
  64393. }(BABYLON.Gamepad));
  64394. BABYLON.Xbox360Pad = Xbox360Pad;
  64395. })(BABYLON || (BABYLON = {}));
  64396. //# sourceMappingURL=babylon.xboxGamepad.js.map
  64397. var BABYLON;
  64398. (function (BABYLON) {
  64399. var PoseEnabledControllerType;
  64400. (function (PoseEnabledControllerType) {
  64401. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  64402. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  64403. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  64404. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  64405. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 4] = "GENERIC";
  64406. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  64407. var PoseEnabledControllerHelper = /** @class */ (function () {
  64408. function PoseEnabledControllerHelper() {
  64409. }
  64410. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  64411. // Oculus Touch
  64412. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  64413. return new BABYLON.OculusTouchController(vrGamepad);
  64414. }
  64415. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  64416. return new BABYLON.WindowsMotionController(vrGamepad);
  64417. }
  64418. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  64419. return new BABYLON.ViveController(vrGamepad);
  64420. }
  64421. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  64422. return new BABYLON.GearVRController(vrGamepad);
  64423. }
  64424. else {
  64425. return new BABYLON.GenericController(vrGamepad);
  64426. }
  64427. };
  64428. return PoseEnabledControllerHelper;
  64429. }());
  64430. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  64431. var PoseEnabledController = /** @class */ (function (_super) {
  64432. __extends(PoseEnabledController, _super);
  64433. function PoseEnabledController(browserGamepad) {
  64434. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  64435. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  64436. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  64437. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  64438. // Represents device position and rotation in babylon space
  64439. _this.devicePosition = BABYLON.Vector3.Zero();
  64440. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  64441. _this.deviceScaleFactor = 1;
  64442. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  64443. _this._deviceToWorld = BABYLON.Matrix.Identity();
  64444. _this._workingMatrix = BABYLON.Matrix.Identity();
  64445. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  64446. _this.controllerType = PoseEnabledControllerType.GENERIC;
  64447. _this.position = BABYLON.Vector3.Zero();
  64448. _this.rotationQuaternion = new BABYLON.Quaternion();
  64449. _this._calculatedPosition = BABYLON.Vector3.Zero();
  64450. _this._calculatedRotation = new BABYLON.Quaternion();
  64451. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  64452. return _this;
  64453. }
  64454. PoseEnabledController.prototype.update = function () {
  64455. _super.prototype.update.call(this);
  64456. var pose = this.browserGamepad.pose;
  64457. this.updateFromDevice(pose);
  64458. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  64459. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  64460. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  64461. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  64462. if (this._mesh) {
  64463. this._mesh.position.copyFrom(this.devicePosition);
  64464. if (this._mesh.rotationQuaternion) {
  64465. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  64466. }
  64467. }
  64468. };
  64469. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  64470. if (poseData) {
  64471. this.rawPose = poseData;
  64472. if (poseData.position) {
  64473. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  64474. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  64475. this._deviceRoomPosition.z *= -1;
  64476. }
  64477. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  64478. this._calculatedPosition.addInPlace(this.position);
  64479. }
  64480. var pose = this.rawPose;
  64481. if (poseData.orientation && pose.orientation) {
  64482. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  64483. if (this._mesh) {
  64484. if (this._mesh.getScene().useRightHandedSystem) {
  64485. this._deviceRoomRotationQuaternion.z *= -1;
  64486. this._deviceRoomRotationQuaternion.w *= -1;
  64487. }
  64488. else {
  64489. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  64490. }
  64491. }
  64492. // if the camera is set, rotate to the camera's rotation
  64493. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  64494. }
  64495. }
  64496. };
  64497. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  64498. if (this._mesh) {
  64499. this._mesh.parent = null;
  64500. }
  64501. this._mesh = mesh;
  64502. if (this._poseControlledCamera) {
  64503. this._mesh.parent = this._poseControlledCamera;
  64504. }
  64505. if (!this._mesh.rotationQuaternion) {
  64506. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  64507. }
  64508. };
  64509. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  64510. this._poseControlledCamera = camera;
  64511. if (this._mesh) {
  64512. this._mesh.parent = this._poseControlledCamera;
  64513. }
  64514. };
  64515. PoseEnabledController.prototype.dispose = function () {
  64516. if (this._mesh) {
  64517. this._mesh.dispose();
  64518. }
  64519. this._mesh = null;
  64520. _super.prototype.dispose.call(this);
  64521. };
  64522. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  64523. get: function () {
  64524. return this._mesh;
  64525. },
  64526. enumerable: true,
  64527. configurable: true
  64528. });
  64529. PoseEnabledController.prototype.getForwardRay = function (length) {
  64530. if (length === void 0) { length = 100; }
  64531. if (!this.mesh) {
  64532. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  64533. }
  64534. var m = this.mesh.getWorldMatrix();
  64535. var origin = m.getTranslation();
  64536. var forward = new BABYLON.Vector3(0, 0, -1);
  64537. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  64538. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  64539. return new BABYLON.Ray(origin, direction, length);
  64540. };
  64541. return PoseEnabledController;
  64542. }(BABYLON.Gamepad));
  64543. BABYLON.PoseEnabledController = PoseEnabledController;
  64544. })(BABYLON || (BABYLON = {}));
  64545. //# sourceMappingURL=babylon.poseEnabledController.js.map
  64546. var BABYLON;
  64547. (function (BABYLON) {
  64548. var WebVRController = /** @class */ (function (_super) {
  64549. __extends(WebVRController, _super);
  64550. function WebVRController(vrGamepad) {
  64551. var _this = _super.call(this, vrGamepad) || this;
  64552. // Observables
  64553. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  64554. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  64555. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  64556. _this.onPadStateChangedObservable = new BABYLON.Observable();
  64557. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  64558. _this.pad = { x: 0, y: 0 };
  64559. // avoid GC, store state in a tmp object
  64560. _this._changes = {
  64561. pressChanged: false,
  64562. touchChanged: false,
  64563. valueChanged: false,
  64564. changed: false
  64565. };
  64566. _this._buttons = new Array(vrGamepad.buttons.length);
  64567. _this.hand = vrGamepad.hand;
  64568. return _this;
  64569. }
  64570. WebVRController.prototype.onButtonStateChange = function (callback) {
  64571. this._onButtonStateChange = callback;
  64572. };
  64573. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  64574. get: function () {
  64575. return this._defaultModel;
  64576. },
  64577. enumerable: true,
  64578. configurable: true
  64579. });
  64580. WebVRController.prototype.update = function () {
  64581. _super.prototype.update.call(this);
  64582. for (var index = 0; index < this._buttons.length; index++) {
  64583. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  64584. }
  64585. ;
  64586. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  64587. this.pad.x = this.leftStick.x;
  64588. this.pad.y = this.leftStick.y;
  64589. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  64590. }
  64591. };
  64592. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  64593. if (!newState) {
  64594. newState = {
  64595. pressed: false,
  64596. touched: false,
  64597. value: 0
  64598. };
  64599. }
  64600. if (!currentState) {
  64601. this._buttons[buttonIndex] = {
  64602. pressed: newState.pressed,
  64603. touched: newState.touched,
  64604. value: newState.value
  64605. };
  64606. return;
  64607. }
  64608. this._checkChanges(newState, currentState);
  64609. if (this._changes.changed) {
  64610. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  64611. this.handleButtonChange(buttonIndex, newState, this._changes);
  64612. }
  64613. this._buttons[buttonIndex].pressed = newState.pressed;
  64614. this._buttons[buttonIndex].touched = newState.touched;
  64615. // oculus triggers are never 0, thou not touched.
  64616. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  64617. };
  64618. WebVRController.prototype._checkChanges = function (newState, currentState) {
  64619. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  64620. this._changes.touchChanged = newState.touched !== currentState.touched;
  64621. this._changes.valueChanged = newState.value !== currentState.value;
  64622. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  64623. return this._changes;
  64624. };
  64625. WebVRController.prototype.dispose = function () {
  64626. _super.prototype.dispose.call(this);
  64627. this.onTriggerStateChangedObservable.clear();
  64628. this.onMainButtonStateChangedObservable.clear();
  64629. this.onSecondaryButtonStateChangedObservable.clear();
  64630. this.onPadStateChangedObservable.clear();
  64631. this.onPadValuesChangedObservable.clear();
  64632. };
  64633. return WebVRController;
  64634. }(BABYLON.PoseEnabledController));
  64635. BABYLON.WebVRController = WebVRController;
  64636. })(BABYLON || (BABYLON = {}));
  64637. //# sourceMappingURL=babylon.webVRController.js.map
  64638. var BABYLON;
  64639. (function (BABYLON) {
  64640. var OculusTouchController = /** @class */ (function (_super) {
  64641. __extends(OculusTouchController, _super);
  64642. function OculusTouchController(vrGamepad) {
  64643. var _this = _super.call(this, vrGamepad) || this;
  64644. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  64645. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  64646. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  64647. return _this;
  64648. }
  64649. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64650. var _this = this;
  64651. var meshName;
  64652. // Hand
  64653. if (this.hand === 'left') {
  64654. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  64655. }
  64656. else {
  64657. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  64658. }
  64659. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  64660. /*
  64661. Parent Mesh name: oculus_touch_left
  64662. - body
  64663. - trigger
  64664. - thumbstick
  64665. - grip
  64666. - button_y
  64667. - button_x
  64668. - button_enter
  64669. */
  64670. _this._defaultModel = newMeshes[1];
  64671. _this.attachToMesh(_this._defaultModel);
  64672. if (meshLoaded) {
  64673. meshLoaded(_this._defaultModel);
  64674. }
  64675. });
  64676. };
  64677. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  64678. // helper getters for left and right hand.
  64679. get: function () {
  64680. if (this.hand === 'right') {
  64681. return this.onMainButtonStateChangedObservable;
  64682. }
  64683. else {
  64684. throw new Error('No A button on left hand');
  64685. }
  64686. },
  64687. enumerable: true,
  64688. configurable: true
  64689. });
  64690. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  64691. get: function () {
  64692. if (this.hand === 'right') {
  64693. return this.onSecondaryButtonStateChangedObservable;
  64694. }
  64695. else {
  64696. throw new Error('No B button on left hand');
  64697. }
  64698. },
  64699. enumerable: true,
  64700. configurable: true
  64701. });
  64702. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  64703. get: function () {
  64704. if (this.hand === 'left') {
  64705. return this.onMainButtonStateChangedObservable;
  64706. }
  64707. else {
  64708. throw new Error('No X button on right hand');
  64709. }
  64710. },
  64711. enumerable: true,
  64712. configurable: true
  64713. });
  64714. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  64715. get: function () {
  64716. if (this.hand === 'left') {
  64717. return this.onSecondaryButtonStateChangedObservable;
  64718. }
  64719. else {
  64720. throw new Error('No Y button on right hand');
  64721. }
  64722. },
  64723. enumerable: true,
  64724. configurable: true
  64725. });
  64726. /*
  64727. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  64728. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  64729. 2) secondary trigger (same)
  64730. 3) A (right) X (left), touch, pressed = value
  64731. 4) B / Y
  64732. 5) thumb rest
  64733. */
  64734. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64735. var notifyObject = state; //{ state: state, changes: changes };
  64736. var triggerDirection = this.hand === 'right' ? -1 : 1;
  64737. switch (buttonIdx) {
  64738. case 0:
  64739. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64740. return;
  64741. case 1:// index trigger
  64742. if (this._defaultModel) {
  64743. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  64744. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  64745. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  64746. }
  64747. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64748. return;
  64749. case 2:// secondary trigger
  64750. if (this._defaultModel) {
  64751. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  64752. }
  64753. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  64754. return;
  64755. case 3:
  64756. if (this._defaultModel) {
  64757. if (notifyObject.pressed) {
  64758. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  64759. }
  64760. else {
  64761. (this._defaultModel.getChildren()[1]).position.y = 0;
  64762. }
  64763. }
  64764. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  64765. return;
  64766. case 4:
  64767. if (this._defaultModel) {
  64768. if (notifyObject.pressed) {
  64769. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  64770. }
  64771. else {
  64772. (this._defaultModel.getChildren()[2]).position.y = 0;
  64773. }
  64774. }
  64775. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  64776. return;
  64777. case 5:
  64778. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  64779. return;
  64780. }
  64781. };
  64782. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  64783. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  64784. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  64785. return OculusTouchController;
  64786. }(BABYLON.WebVRController));
  64787. BABYLON.OculusTouchController = OculusTouchController;
  64788. })(BABYLON || (BABYLON = {}));
  64789. //# sourceMappingURL=babylon.oculusTouchController.js.map
  64790. var BABYLON;
  64791. (function (BABYLON) {
  64792. var ViveController = /** @class */ (function (_super) {
  64793. __extends(ViveController, _super);
  64794. function ViveController(vrGamepad) {
  64795. var _this = _super.call(this, vrGamepad) || this;
  64796. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  64797. _this._invertLeftStickY = true;
  64798. return _this;
  64799. }
  64800. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64801. var _this = this;
  64802. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  64803. /*
  64804. Parent Mesh name: ViveWand
  64805. - body
  64806. - r_gripper
  64807. - l_gripper
  64808. - menu_button
  64809. - system_button
  64810. - trackpad
  64811. - trigger
  64812. - LED
  64813. */
  64814. _this._defaultModel = newMeshes[1];
  64815. _this.attachToMesh(_this._defaultModel);
  64816. if (meshLoaded) {
  64817. meshLoaded(_this._defaultModel);
  64818. }
  64819. });
  64820. };
  64821. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  64822. get: function () {
  64823. return this.onMainButtonStateChangedObservable;
  64824. },
  64825. enumerable: true,
  64826. configurable: true
  64827. });
  64828. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  64829. get: function () {
  64830. return this.onMainButtonStateChangedObservable;
  64831. },
  64832. enumerable: true,
  64833. configurable: true
  64834. });
  64835. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  64836. get: function () {
  64837. return this.onSecondaryButtonStateChangedObservable;
  64838. },
  64839. enumerable: true,
  64840. configurable: true
  64841. });
  64842. /**
  64843. * Vive mapping:
  64844. * 0: touchpad
  64845. * 1: trigger
  64846. * 2: left AND right buttons
  64847. * 3: menu button
  64848. */
  64849. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64850. var notifyObject = state; //{ state: state, changes: changes };
  64851. switch (buttonIdx) {
  64852. case 0:
  64853. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  64854. return;
  64855. case 1:// index trigger
  64856. if (this._defaultModel) {
  64857. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  64858. }
  64859. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  64860. return;
  64861. case 2:// left AND right button
  64862. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  64863. return;
  64864. case 3:
  64865. if (this._defaultModel) {
  64866. if (notifyObject.pressed) {
  64867. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  64868. }
  64869. else {
  64870. (this._defaultModel.getChildren()[2]).position.y = 0;
  64871. }
  64872. }
  64873. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  64874. return;
  64875. }
  64876. };
  64877. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  64878. ViveController.MODEL_FILENAME = 'wand.babylon';
  64879. return ViveController;
  64880. }(BABYLON.WebVRController));
  64881. BABYLON.ViveController = ViveController;
  64882. })(BABYLON || (BABYLON = {}));
  64883. //# sourceMappingURL=babylon.viveController.js.map
  64884. var BABYLON;
  64885. (function (BABYLON) {
  64886. var GenericController = /** @class */ (function (_super) {
  64887. __extends(GenericController, _super);
  64888. function GenericController(vrGamepad) {
  64889. return _super.call(this, vrGamepad) || this;
  64890. }
  64891. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  64892. var _this = this;
  64893. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  64894. _this._defaultModel = newMeshes[1];
  64895. _this.attachToMesh(_this._defaultModel);
  64896. if (meshLoaded) {
  64897. meshLoaded(_this._defaultModel);
  64898. }
  64899. });
  64900. };
  64901. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  64902. console.log("Button id: " + buttonIdx + "state: ");
  64903. console.dir(state);
  64904. };
  64905. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  64906. GenericController.MODEL_FILENAME = 'generic.babylon';
  64907. return GenericController;
  64908. }(BABYLON.WebVRController));
  64909. BABYLON.GenericController = GenericController;
  64910. })(BABYLON || (BABYLON = {}));
  64911. //# sourceMappingURL=babylon.genericController.js.map
  64912. var BABYLON;
  64913. (function (BABYLON) {
  64914. var LoadedMeshInfo = /** @class */ (function () {
  64915. function LoadedMeshInfo() {
  64916. this.buttonMeshes = {};
  64917. this.axisMeshes = {};
  64918. }
  64919. return LoadedMeshInfo;
  64920. }());
  64921. var WindowsMotionController = /** @class */ (function (_super) {
  64922. __extends(WindowsMotionController, _super);
  64923. function WindowsMotionController(vrGamepad) {
  64924. var _this = _super.call(this, vrGamepad) || this;
  64925. _this._mapping = {
  64926. // Semantic button names
  64927. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  64928. // A mapping of the button name to glTF model node name
  64929. // that should be transformed by button value.
  64930. buttonMeshNames: {
  64931. 'trigger': 'SELECT',
  64932. 'menu': 'MENU',
  64933. 'grip': 'GRASP',
  64934. 'thumbstick': 'THUMBSTICK_PRESS',
  64935. 'trackpad': 'TOUCHPAD_PRESS'
  64936. },
  64937. // This mapping is used to translate from the Motion Controller to Babylon semantics
  64938. buttonObservableNames: {
  64939. 'trigger': 'onTriggerStateChangedObservable',
  64940. 'menu': 'onSecondaryButtonStateChangedObservable',
  64941. 'grip': 'onMainButtonStateChangedObservable',
  64942. 'thumbstick': 'onPadStateChangedObservable',
  64943. 'trackpad': 'onTrackpadChangedObservable'
  64944. },
  64945. // A mapping of the axis name to glTF model node name
  64946. // that should be transformed by axis value.
  64947. // This array mirrors the browserGamepad.axes array, such that
  64948. // the mesh corresponding to axis 0 is in this array index 0.
  64949. axisMeshNames: [
  64950. 'THUMBSTICK_X',
  64951. 'THUMBSTICK_Y',
  64952. 'TOUCHPAD_TOUCH_X',
  64953. 'TOUCHPAD_TOUCH_Y'
  64954. ],
  64955. pointingPoseMeshName: 'POINTING_POSE'
  64956. };
  64957. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  64958. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  64959. _this.trackpad = { x: 0, y: 0 };
  64960. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  64961. _this._loadedMeshInfo = null;
  64962. return _this;
  64963. }
  64964. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  64965. get: function () {
  64966. return this.onTriggerStateChangedObservable;
  64967. },
  64968. enumerable: true,
  64969. configurable: true
  64970. });
  64971. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  64972. get: function () {
  64973. return this.onSecondaryButtonStateChangedObservable;
  64974. },
  64975. enumerable: true,
  64976. configurable: true
  64977. });
  64978. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  64979. get: function () {
  64980. return this.onMainButtonStateChangedObservable;
  64981. },
  64982. enumerable: true,
  64983. configurable: true
  64984. });
  64985. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  64986. get: function () {
  64987. return this.onPadStateChangedObservable;
  64988. },
  64989. enumerable: true,
  64990. configurable: true
  64991. });
  64992. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  64993. get: function () {
  64994. return this.onTrackpadChangedObservable;
  64995. },
  64996. enumerable: true,
  64997. configurable: true
  64998. });
  64999. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  65000. get: function () {
  65001. return this.onTrackpadValuesChangedObservable;
  65002. },
  65003. enumerable: true,
  65004. configurable: true
  65005. });
  65006. /**
  65007. * Called once per frame by the engine.
  65008. */
  65009. WindowsMotionController.prototype.update = function () {
  65010. _super.prototype.update.call(this);
  65011. // Only need to animate axes if there is a loaded mesh
  65012. if (this._loadedMeshInfo) {
  65013. if (this.browserGamepad.axes) {
  65014. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  65015. this.trackpad.x = this.browserGamepad["axes"][2];
  65016. this.trackpad.y = this.browserGamepad["axes"][3];
  65017. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  65018. }
  65019. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  65020. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  65021. }
  65022. }
  65023. }
  65024. };
  65025. /**
  65026. * Called once for each button that changed state since the last frame
  65027. * @param buttonIdx Which button index changed
  65028. * @param state New state of the button
  65029. * @param changes Which properties on the state changed since last frame
  65030. */
  65031. WindowsMotionController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  65032. var buttonName = this._mapping.buttons[buttonIdx];
  65033. if (!buttonName) {
  65034. return;
  65035. }
  65036. // Only emit events for buttons that we know how to map from index to name
  65037. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  65038. if (observable) {
  65039. observable.notifyObservers(state);
  65040. }
  65041. this.lerpButtonTransform(buttonName, state.value);
  65042. };
  65043. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  65044. // If there is no loaded mesh, there is nothing to transform.
  65045. if (!this._loadedMeshInfo) {
  65046. return;
  65047. }
  65048. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  65049. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65050. return;
  65051. }
  65052. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  65053. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  65054. };
  65055. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  65056. if (!this._loadedMeshInfo) {
  65057. return;
  65058. }
  65059. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  65060. if (!meshInfo) {
  65061. return;
  65062. }
  65063. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  65064. return;
  65065. }
  65066. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  65067. var lerpValue = axisValue * 0.5 + 0.5;
  65068. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  65069. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  65070. };
  65071. /**
  65072. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  65073. * @param scene scene in which to add meshes
  65074. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  65075. */
  65076. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  65077. var _this = this;
  65078. if (forceDefault === void 0) { forceDefault = false; }
  65079. var path;
  65080. var filename;
  65081. // Checking if GLB loader is present
  65082. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  65083. // Determine the device specific folder based on the ID suffix
  65084. var device = 'default';
  65085. if (this.id && !forceDefault) {
  65086. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  65087. device = ((match && match[0]) || device);
  65088. }
  65089. // Hand
  65090. if (this.hand === 'left') {
  65091. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  65092. }
  65093. else {
  65094. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  65095. }
  65096. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  65097. }
  65098. else {
  65099. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  65100. path = BABYLON.GenericController.MODEL_BASE_URL;
  65101. filename = BABYLON.GenericController.MODEL_FILENAME;
  65102. }
  65103. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  65104. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  65105. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  65106. if (!_this._loadedMeshInfo) {
  65107. return;
  65108. }
  65109. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  65110. _this.attachToMesh(_this._defaultModel);
  65111. if (meshLoaded) {
  65112. meshLoaded(_this._defaultModel);
  65113. }
  65114. }, null, function (scene, message) {
  65115. BABYLON.Tools.Log(message);
  65116. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  65117. if (!forceDefault) {
  65118. _this.initControllerMesh(scene, meshLoaded, true);
  65119. }
  65120. });
  65121. };
  65122. /**
  65123. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  65124. * can be transformed by button presses and axes values, based on this._mapping.
  65125. *
  65126. * @param scene scene in which the meshes exist
  65127. * @param meshes list of meshes that make up the controller model to process
  65128. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  65129. */
  65130. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  65131. var loadedMeshInfo = null;
  65132. // Create a new mesh to contain the glTF hierarchy
  65133. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  65134. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  65135. var childMesh = null;
  65136. for (var i = 0; i < meshes.length; i++) {
  65137. var mesh = meshes[i];
  65138. if (!mesh.parent) {
  65139. // Exclude controller meshes from picking results
  65140. mesh.isPickable = false;
  65141. // Handle root node, attach to the new parentMesh
  65142. childMesh = mesh;
  65143. break;
  65144. }
  65145. }
  65146. if (childMesh) {
  65147. childMesh.setParent(parentMesh);
  65148. // Create our mesh info. Note that this method will always return non-null.
  65149. loadedMeshInfo = this.createMeshInfo(parentMesh);
  65150. }
  65151. else {
  65152. BABYLON.Tools.Warn('Could not find root node in model file.');
  65153. }
  65154. return loadedMeshInfo;
  65155. };
  65156. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  65157. var loadedMeshInfo = new LoadedMeshInfo();
  65158. var i;
  65159. loadedMeshInfo.rootNode = rootNode;
  65160. // Reset the caches
  65161. loadedMeshInfo.buttonMeshes = {};
  65162. loadedMeshInfo.axisMeshes = {};
  65163. // Button Meshes
  65164. for (i = 0; i < this._mapping.buttons.length; i++) {
  65165. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  65166. if (!buttonMeshName) {
  65167. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  65168. continue;
  65169. }
  65170. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  65171. if (!buttonMesh) {
  65172. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  65173. continue;
  65174. }
  65175. var buttonMeshInfo = {
  65176. index: i,
  65177. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  65178. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  65179. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  65180. };
  65181. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  65182. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  65183. }
  65184. else {
  65185. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  65186. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  65187. '(VALUE: ' + !!buttonMeshInfo.value +
  65188. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  65189. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  65190. ')');
  65191. }
  65192. }
  65193. // Axis Meshes
  65194. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  65195. var axisMeshName = this._mapping.axisMeshNames[i];
  65196. if (!axisMeshName) {
  65197. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  65198. continue;
  65199. }
  65200. var axisMesh = getChildByName(rootNode, axisMeshName);
  65201. if (!axisMesh) {
  65202. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  65203. continue;
  65204. }
  65205. var axisMeshInfo = {
  65206. index: i,
  65207. value: getImmediateChildByName(axisMesh, 'VALUE'),
  65208. min: getImmediateChildByName(axisMesh, 'MIN'),
  65209. max: getImmediateChildByName(axisMesh, 'MAX')
  65210. };
  65211. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  65212. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  65213. }
  65214. else {
  65215. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  65216. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  65217. '(VALUE: ' + !!axisMeshInfo.value +
  65218. ', MIN: ' + !!axisMeshInfo.min +
  65219. ', MAX:' + !!axisMeshInfo.max +
  65220. ')');
  65221. }
  65222. }
  65223. // Pointing Ray
  65224. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  65225. if (!loadedMeshInfo.pointingPoseNode) {
  65226. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  65227. }
  65228. return loadedMeshInfo;
  65229. // Look through all children recursively. This will return null if no mesh exists with the given name.
  65230. function getChildByName(node, name) {
  65231. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  65232. }
  65233. // Look through only immediate children. This will return null if no mesh exists with the given name.
  65234. function getImmediateChildByName(node, name) {
  65235. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  65236. }
  65237. };
  65238. WindowsMotionController.prototype.getForwardRay = function (length) {
  65239. if (length === void 0) { length = 100; }
  65240. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  65241. return _super.prototype.getForwardRay.call(this, length);
  65242. }
  65243. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  65244. var origin = m.getTranslation();
  65245. var forward = new BABYLON.Vector3(0, 0, -1);
  65246. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  65247. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  65248. return new BABYLON.Ray(origin, direction, length);
  65249. };
  65250. WindowsMotionController.prototype.dispose = function () {
  65251. _super.prototype.dispose.call(this);
  65252. this.onTrackpadChangedObservable.clear();
  65253. };
  65254. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  65255. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  65256. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  65257. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  65258. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  65259. return WindowsMotionController;
  65260. }(BABYLON.WebVRController));
  65261. BABYLON.WindowsMotionController = WindowsMotionController;
  65262. })(BABYLON || (BABYLON = {}));
  65263. //# sourceMappingURL=babylon.windowsMotionController.js.map
  65264. var BABYLON;
  65265. (function (BABYLON) {
  65266. var GearVRController = /** @class */ (function (_super) {
  65267. __extends(GearVRController, _super);
  65268. function GearVRController(vrGamepad) {
  65269. var _this = _super.call(this, vrGamepad) || this;
  65270. _this._buttonIndexToObservableNameMap = [
  65271. 'onTrackpadChangedObservable',
  65272. 'onTriggerStateChangedObservable' // Trigger
  65273. ];
  65274. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  65275. return _this;
  65276. }
  65277. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  65278. var _this = this;
  65279. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  65280. _this._defaultModel = newMeshes[1];
  65281. _this.attachToMesh(_this._defaultModel);
  65282. if (meshLoaded) {
  65283. meshLoaded(_this._defaultModel);
  65284. }
  65285. });
  65286. };
  65287. GearVRController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  65288. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  65289. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  65290. // Only emit events for buttons that we know how to map from index to observable
  65291. var observable = this[observableName];
  65292. if (observable) {
  65293. observable.notifyObservers(state);
  65294. }
  65295. }
  65296. };
  65297. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  65298. GearVRController.MODEL_FILENAME = 'generic.babylon';
  65299. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  65300. return GearVRController;
  65301. }(BABYLON.WebVRController));
  65302. BABYLON.GearVRController = GearVRController;
  65303. })(BABYLON || (BABYLON = {}));
  65304. //# sourceMappingURL=babylon.gearVRController.js.map
  65305. var BABYLON;
  65306. (function (BABYLON) {
  65307. var FollowCamera = /** @class */ (function (_super) {
  65308. __extends(FollowCamera, _super);
  65309. function FollowCamera(name, position, scene, lockedTarget) {
  65310. if (lockedTarget === void 0) { lockedTarget = null; }
  65311. var _this = _super.call(this, name, position, scene) || this;
  65312. _this.radius = 12;
  65313. _this.rotationOffset = 0;
  65314. _this.heightOffset = 4;
  65315. _this.cameraAcceleration = 0.05;
  65316. _this.maxCameraSpeed = 20;
  65317. _this.lockedTarget = lockedTarget;
  65318. return _this;
  65319. }
  65320. FollowCamera.prototype.getRadians = function (degrees) {
  65321. return degrees * Math.PI / 180;
  65322. };
  65323. FollowCamera.prototype.follow = function (cameraTarget) {
  65324. if (!cameraTarget)
  65325. return;
  65326. var yRotation;
  65327. if (cameraTarget.rotationQuaternion) {
  65328. var rotMatrix = new BABYLON.Matrix();
  65329. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  65330. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  65331. }
  65332. else {
  65333. yRotation = cameraTarget.rotation.y;
  65334. }
  65335. var radians = this.getRadians(this.rotationOffset) + yRotation;
  65336. var targetPosition = cameraTarget.getAbsolutePosition();
  65337. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  65338. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  65339. var dx = targetX - this.position.x;
  65340. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  65341. var dz = (targetZ) - this.position.z;
  65342. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  65343. var vy = dy * this.cameraAcceleration;
  65344. var vz = dz * this.cameraAcceleration * 2;
  65345. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  65346. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65347. }
  65348. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  65349. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65350. }
  65351. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  65352. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  65353. }
  65354. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  65355. this.setTarget(targetPosition);
  65356. };
  65357. FollowCamera.prototype._checkInputs = function () {
  65358. _super.prototype._checkInputs.call(this);
  65359. if (this.lockedTarget) {
  65360. this.follow(this.lockedTarget);
  65361. }
  65362. };
  65363. FollowCamera.prototype.getClassName = function () {
  65364. return "FollowCamera";
  65365. };
  65366. __decorate([
  65367. BABYLON.serialize()
  65368. ], FollowCamera.prototype, "radius", void 0);
  65369. __decorate([
  65370. BABYLON.serialize()
  65371. ], FollowCamera.prototype, "rotationOffset", void 0);
  65372. __decorate([
  65373. BABYLON.serialize()
  65374. ], FollowCamera.prototype, "heightOffset", void 0);
  65375. __decorate([
  65376. BABYLON.serialize()
  65377. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  65378. __decorate([
  65379. BABYLON.serialize()
  65380. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  65381. __decorate([
  65382. BABYLON.serializeAsMeshReference("lockedTargetId")
  65383. ], FollowCamera.prototype, "lockedTarget", void 0);
  65384. return FollowCamera;
  65385. }(BABYLON.TargetCamera));
  65386. BABYLON.FollowCamera = FollowCamera;
  65387. var ArcFollowCamera = /** @class */ (function (_super) {
  65388. __extends(ArcFollowCamera, _super);
  65389. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  65390. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  65391. _this.alpha = alpha;
  65392. _this.beta = beta;
  65393. _this.radius = radius;
  65394. _this.target = target;
  65395. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  65396. _this.follow();
  65397. return _this;
  65398. }
  65399. ArcFollowCamera.prototype.follow = function () {
  65400. if (!this.target) {
  65401. return;
  65402. }
  65403. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  65404. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  65405. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  65406. var targetPosition = this.target.getAbsolutePosition();
  65407. this.position = targetPosition.add(this._cartesianCoordinates);
  65408. this.setTarget(targetPosition);
  65409. };
  65410. ArcFollowCamera.prototype._checkInputs = function () {
  65411. _super.prototype._checkInputs.call(this);
  65412. this.follow();
  65413. };
  65414. ArcFollowCamera.prototype.getClassName = function () {
  65415. return "ArcFollowCamera";
  65416. };
  65417. return ArcFollowCamera;
  65418. }(BABYLON.TargetCamera));
  65419. BABYLON.ArcFollowCamera = ArcFollowCamera;
  65420. })(BABYLON || (BABYLON = {}));
  65421. //# sourceMappingURL=babylon.followCamera.js.map
  65422. var BABYLON;
  65423. (function (BABYLON) {
  65424. // We're mainly based on the logic defined into the FreeCamera code
  65425. var UniversalCamera = /** @class */ (function (_super) {
  65426. __extends(UniversalCamera, _super);
  65427. //-- end properties for backward compatibility for inputs
  65428. function UniversalCamera(name, position, scene) {
  65429. var _this = _super.call(this, name, position, scene) || this;
  65430. _this.inputs.addGamepad();
  65431. return _this;
  65432. }
  65433. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  65434. //-- Begin properties for backward compatibility for inputs
  65435. get: function () {
  65436. var gamepad = this.inputs.attached["gamepad"];
  65437. if (gamepad)
  65438. return gamepad.gamepadAngularSensibility;
  65439. return 0;
  65440. },
  65441. set: function (value) {
  65442. var gamepad = this.inputs.attached["gamepad"];
  65443. if (gamepad)
  65444. gamepad.gamepadAngularSensibility = value;
  65445. },
  65446. enumerable: true,
  65447. configurable: true
  65448. });
  65449. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  65450. get: function () {
  65451. var gamepad = this.inputs.attached["gamepad"];
  65452. if (gamepad)
  65453. return gamepad.gamepadMoveSensibility;
  65454. return 0;
  65455. },
  65456. set: function (value) {
  65457. var gamepad = this.inputs.attached["gamepad"];
  65458. if (gamepad)
  65459. gamepad.gamepadMoveSensibility = value;
  65460. },
  65461. enumerable: true,
  65462. configurable: true
  65463. });
  65464. UniversalCamera.prototype.getClassName = function () {
  65465. return "UniversalCamera";
  65466. };
  65467. return UniversalCamera;
  65468. }(BABYLON.TouchCamera));
  65469. BABYLON.UniversalCamera = UniversalCamera;
  65470. })(BABYLON || (BABYLON = {}));
  65471. //# sourceMappingURL=babylon.universalCamera.js.map
  65472. var BABYLON;
  65473. (function (BABYLON) {
  65474. // We're mainly based on the logic defined into the FreeCamera code
  65475. var GamepadCamera = /** @class */ (function (_super) {
  65476. __extends(GamepadCamera, _super);
  65477. //-- end properties for backward compatibility for inputs
  65478. function GamepadCamera(name, position, scene) {
  65479. return _super.call(this, name, position, scene) || this;
  65480. }
  65481. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  65482. //-- Begin properties for backward compatibility for inputs
  65483. get: function () {
  65484. var gamepad = this.inputs.attached["gamepad"];
  65485. if (gamepad)
  65486. return gamepad.gamepadAngularSensibility;
  65487. return 0;
  65488. },
  65489. set: function (value) {
  65490. var gamepad = this.inputs.attached["gamepad"];
  65491. if (gamepad)
  65492. gamepad.gamepadAngularSensibility = value;
  65493. },
  65494. enumerable: true,
  65495. configurable: true
  65496. });
  65497. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  65498. get: function () {
  65499. var gamepad = this.inputs.attached["gamepad"];
  65500. if (gamepad)
  65501. return gamepad.gamepadMoveSensibility;
  65502. return 0;
  65503. },
  65504. set: function (value) {
  65505. var gamepad = this.inputs.attached["gamepad"];
  65506. if (gamepad)
  65507. gamepad.gamepadMoveSensibility = value;
  65508. },
  65509. enumerable: true,
  65510. configurable: true
  65511. });
  65512. GamepadCamera.prototype.getClassName = function () {
  65513. return "GamepadCamera";
  65514. };
  65515. return GamepadCamera;
  65516. }(BABYLON.UniversalCamera));
  65517. BABYLON.GamepadCamera = GamepadCamera;
  65518. })(BABYLON || (BABYLON = {}));
  65519. //# sourceMappingURL=babylon.gamepadCamera.js.map
  65520. var BABYLON;
  65521. (function (BABYLON) {
  65522. var PostProcessRenderPipelineManager = /** @class */ (function () {
  65523. function PostProcessRenderPipelineManager() {
  65524. this._renderPipelines = {};
  65525. }
  65526. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  65527. this._renderPipelines[renderPipeline._name] = renderPipeline;
  65528. };
  65529. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  65530. if (unique === void 0) { unique = false; }
  65531. var renderPipeline = this._renderPipelines[renderPipelineName];
  65532. if (!renderPipeline) {
  65533. return;
  65534. }
  65535. renderPipeline._attachCameras(cameras, unique);
  65536. };
  65537. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  65538. var renderPipeline = this._renderPipelines[renderPipelineName];
  65539. if (!renderPipeline) {
  65540. return;
  65541. }
  65542. renderPipeline._detachCameras(cameras);
  65543. };
  65544. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65545. var renderPipeline = this._renderPipelines[renderPipelineName];
  65546. if (!renderPipeline) {
  65547. return;
  65548. }
  65549. renderPipeline._enableEffect(renderEffectName, cameras);
  65550. };
  65551. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  65552. var renderPipeline = this._renderPipelines[renderPipelineName];
  65553. if (!renderPipeline) {
  65554. return;
  65555. }
  65556. renderPipeline._disableEffect(renderEffectName, cameras);
  65557. };
  65558. PostProcessRenderPipelineManager.prototype.update = function () {
  65559. for (var renderPipelineName in this._renderPipelines) {
  65560. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65561. var pipeline = this._renderPipelines[renderPipelineName];
  65562. if (!pipeline.isSupported) {
  65563. pipeline.dispose();
  65564. delete this._renderPipelines[renderPipelineName];
  65565. }
  65566. else {
  65567. pipeline._update();
  65568. }
  65569. }
  65570. }
  65571. };
  65572. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  65573. for (var renderPipelineName in this._renderPipelines) {
  65574. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65575. var pipeline = this._renderPipelines[renderPipelineName];
  65576. pipeline._rebuild();
  65577. }
  65578. }
  65579. };
  65580. PostProcessRenderPipelineManager.prototype.dispose = function () {
  65581. for (var renderPipelineName in this._renderPipelines) {
  65582. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  65583. var pipeline = this._renderPipelines[renderPipelineName];
  65584. pipeline.dispose();
  65585. }
  65586. }
  65587. };
  65588. return PostProcessRenderPipelineManager;
  65589. }());
  65590. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  65591. })(BABYLON || (BABYLON = {}));
  65592. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  65593. var BABYLON;
  65594. (function (BABYLON) {
  65595. /**
  65596. * This represents a set of one or more post processes in Babylon.
  65597. * A post process can be used to apply a shader to a texture after it is rendered.
  65598. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  65599. */
  65600. var PostProcessRenderEffect = /** @class */ (function () {
  65601. /**
  65602. * Instantiates a post process render effect.
  65603. * A post process can be used to apply a shader to a texture after it is rendered.
  65604. * @param engine The engine the effect is tied to
  65605. * @param name The name of the effect
  65606. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  65607. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  65608. */
  65609. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  65610. this._name = name;
  65611. this._singleInstance = singleInstance || true;
  65612. this._getPostProcesses = getPostProcesses;
  65613. this._cameras = {};
  65614. this._indicesForCamera = {};
  65615. this._postProcesses = {};
  65616. }
  65617. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  65618. /**
  65619. * Checks if all the post processes in the effect are supported.
  65620. */
  65621. get: function () {
  65622. for (var index in this._postProcesses) {
  65623. for (var ppIndex in this._postProcesses[index]) {
  65624. if (!this._postProcesses[index][ppIndex].isSupported) {
  65625. return false;
  65626. }
  65627. }
  65628. }
  65629. return true;
  65630. },
  65631. enumerable: true,
  65632. configurable: true
  65633. });
  65634. /**
  65635. * Updates the current state of the effect
  65636. */
  65637. PostProcessRenderEffect.prototype._update = function () {
  65638. };
  65639. /**
  65640. * Attaches the effect on cameras
  65641. * @param cameras The camera to attach to.
  65642. */
  65643. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  65644. var _this = this;
  65645. var cameraKey;
  65646. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65647. if (!cams) {
  65648. return;
  65649. }
  65650. for (var i = 0; i < cams.length; i++) {
  65651. var camera = cams[i];
  65652. var cameraName = camera.name;
  65653. if (this._singleInstance) {
  65654. cameraKey = 0;
  65655. }
  65656. else {
  65657. cameraKey = cameraName;
  65658. }
  65659. if (!this._postProcesses[cameraKey]) {
  65660. var postProcess = this._getPostProcesses();
  65661. if (postProcess) {
  65662. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  65663. }
  65664. }
  65665. if (!this._indicesForCamera[cameraName]) {
  65666. this._indicesForCamera[cameraName] = [];
  65667. }
  65668. this._postProcesses[cameraKey].forEach(function (postProcess) {
  65669. var index = camera.attachPostProcess(postProcess);
  65670. _this._indicesForCamera[cameraName].push(index);
  65671. });
  65672. if (!this._cameras[cameraName]) {
  65673. this._cameras[cameraName] = camera;
  65674. }
  65675. }
  65676. };
  65677. /**
  65678. * Detatches the effect on cameras
  65679. * @param cameras The camera to detatch from.
  65680. */
  65681. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  65682. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65683. if (!cams) {
  65684. return;
  65685. }
  65686. for (var i = 0; i < cams.length; i++) {
  65687. var camera = cams[i];
  65688. var cameraName = camera.name;
  65689. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65690. camera.detachPostProcess(postProcess);
  65691. });
  65692. if (this._cameras[cameraName]) {
  65693. //this._indicesForCamera.splice(index, 1);
  65694. this._cameras[cameraName] = null;
  65695. }
  65696. }
  65697. };
  65698. /**
  65699. * Enables the effect on given cameras
  65700. * @param cameras The camera to enable.
  65701. */
  65702. PostProcessRenderEffect.prototype._enable = function (cameras) {
  65703. var _this = this;
  65704. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65705. if (!cams) {
  65706. return;
  65707. }
  65708. for (var i = 0; i < cams.length; i++) {
  65709. var camera = cams[i];
  65710. var cameraName = camera.name;
  65711. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  65712. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  65713. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65714. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  65715. });
  65716. }
  65717. }
  65718. }
  65719. };
  65720. /**
  65721. * Disables the effect on the given cameras
  65722. * @param cameras The camera to disable.
  65723. */
  65724. PostProcessRenderEffect.prototype._disable = function (cameras) {
  65725. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65726. if (!cams) {
  65727. return;
  65728. }
  65729. for (var i = 0; i < cams.length; i++) {
  65730. var camera = cams[i];
  65731. var cameraName = camera.name;
  65732. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  65733. camera.detachPostProcess(postProcess);
  65734. });
  65735. }
  65736. };
  65737. /**
  65738. * Gets a list of the post processes contained in the effect.
  65739. * @param camera The camera to get the post processes on.
  65740. * @returns The list of the post processes in the effect.
  65741. */
  65742. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  65743. if (this._singleInstance) {
  65744. return this._postProcesses[0];
  65745. }
  65746. else {
  65747. if (!camera) {
  65748. return null;
  65749. }
  65750. return this._postProcesses[camera.name];
  65751. }
  65752. };
  65753. return PostProcessRenderEffect;
  65754. }());
  65755. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  65756. })(BABYLON || (BABYLON = {}));
  65757. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  65758. var BABYLON;
  65759. (function (BABYLON) {
  65760. var PostProcessRenderPipeline = /** @class */ (function () {
  65761. function PostProcessRenderPipeline(engine, name) {
  65762. this._name = name;
  65763. this._renderEffects = {};
  65764. this._renderEffectsForIsolatedPass = new Array();
  65765. this._cameras = [];
  65766. }
  65767. PostProcessRenderPipeline.prototype.getClassName = function () {
  65768. return "PostProcessRenderPipeline";
  65769. };
  65770. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  65771. get: function () {
  65772. for (var renderEffectName in this._renderEffects) {
  65773. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65774. if (!this._renderEffects[renderEffectName].isSupported) {
  65775. return false;
  65776. }
  65777. }
  65778. }
  65779. return true;
  65780. },
  65781. enumerable: true,
  65782. configurable: true
  65783. });
  65784. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  65785. this._renderEffects[renderEffect._name] = renderEffect;
  65786. };
  65787. // private
  65788. PostProcessRenderPipeline.prototype._rebuild = function () {
  65789. };
  65790. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  65791. var renderEffects = this._renderEffects[renderEffectName];
  65792. if (!renderEffects) {
  65793. return;
  65794. }
  65795. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  65796. };
  65797. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  65798. var renderEffects = this._renderEffects[renderEffectName];
  65799. if (!renderEffects) {
  65800. return;
  65801. }
  65802. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  65803. };
  65804. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  65805. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65806. if (!cams) {
  65807. return;
  65808. }
  65809. var indicesToDelete = [];
  65810. var i;
  65811. for (i = 0; i < cams.length; i++) {
  65812. var camera = cams[i];
  65813. var cameraName = camera.name;
  65814. if (this._cameras.indexOf(camera) === -1) {
  65815. this._cameras[cameraName] = camera;
  65816. }
  65817. else if (unique) {
  65818. indicesToDelete.push(i);
  65819. }
  65820. }
  65821. for (i = 0; i < indicesToDelete.length; i++) {
  65822. cameras.splice(indicesToDelete[i], 1);
  65823. }
  65824. for (var renderEffectName in this._renderEffects) {
  65825. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65826. this._renderEffects[renderEffectName]._attachCameras(cams);
  65827. }
  65828. }
  65829. };
  65830. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  65831. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  65832. if (!cams) {
  65833. return;
  65834. }
  65835. for (var renderEffectName in this._renderEffects) {
  65836. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65837. this._renderEffects[renderEffectName]._detachCameras(cams);
  65838. }
  65839. }
  65840. for (var i = 0; i < cams.length; i++) {
  65841. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  65842. }
  65843. };
  65844. PostProcessRenderPipeline.prototype._update = function () {
  65845. for (var renderEffectName in this._renderEffects) {
  65846. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  65847. this._renderEffects[renderEffectName]._update();
  65848. }
  65849. }
  65850. for (var i = 0; i < this._cameras.length; i++) {
  65851. var cameraName = this._cameras[i].name;
  65852. if (this._renderEffectsForIsolatedPass[cameraName]) {
  65853. this._renderEffectsForIsolatedPass[cameraName]._update();
  65854. }
  65855. }
  65856. };
  65857. PostProcessRenderPipeline.prototype._reset = function () {
  65858. this._renderEffects = {};
  65859. this._renderEffectsForIsolatedPass = new Array();
  65860. };
  65861. PostProcessRenderPipeline.prototype.dispose = function () {
  65862. // Must be implemented by children
  65863. };
  65864. __decorate([
  65865. BABYLON.serialize()
  65866. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  65867. return PostProcessRenderPipeline;
  65868. }());
  65869. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  65870. })(BABYLON || (BABYLON = {}));
  65871. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  65872. var BABYLON;
  65873. (function (BABYLON) {
  65874. var DepthRenderer = /** @class */ (function () {
  65875. function DepthRenderer(scene, type) {
  65876. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  65877. var _this = this;
  65878. this._scene = scene;
  65879. var engine = scene.getEngine();
  65880. // Render target
  65881. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  65882. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65883. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65884. this._depthMap.refreshRate = 1;
  65885. this._depthMap.renderParticles = false;
  65886. this._depthMap.renderList = null;
  65887. // set default depth value to 1.0 (far away)
  65888. this._depthMap.onClearObservable.add(function (engine) {
  65889. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  65890. });
  65891. // Custom render function
  65892. var renderSubMesh = function (subMesh) {
  65893. var mesh = subMesh.getRenderingMesh();
  65894. var scene = _this._scene;
  65895. var engine = scene.getEngine();
  65896. var material = subMesh.getMaterial();
  65897. if (!material) {
  65898. return;
  65899. }
  65900. // Culling and reverse (right handed system)
  65901. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  65902. // Managing instances
  65903. var batch = mesh._getInstancesRenderList(subMesh._id);
  65904. if (batch.mustReturn) {
  65905. return;
  65906. }
  65907. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  65908. if (_this.isReady(subMesh, hardwareInstancedRendering) && scene.activeCamera) {
  65909. engine.enableEffect(_this._effect);
  65910. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  65911. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  65912. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  65913. // Alpha test
  65914. if (material && material.needAlphaTesting()) {
  65915. var alphaTexture = material.getAlphaTestTexture();
  65916. if (alphaTexture) {
  65917. _this._effect.setTexture("diffuseSampler", alphaTexture);
  65918. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  65919. }
  65920. }
  65921. // Bones
  65922. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  65923. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  65924. }
  65925. // Draw
  65926. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  65927. }
  65928. };
  65929. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  65930. var index;
  65931. if (depthOnlySubMeshes.length) {
  65932. engine.setColorWrite(false);
  65933. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  65934. renderSubMesh(depthOnlySubMeshes.data[index]);
  65935. }
  65936. engine.setColorWrite(true);
  65937. }
  65938. for (index = 0; index < opaqueSubMeshes.length; index++) {
  65939. renderSubMesh(opaqueSubMeshes.data[index]);
  65940. }
  65941. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  65942. renderSubMesh(alphaTestSubMeshes.data[index]);
  65943. }
  65944. };
  65945. }
  65946. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  65947. var material = subMesh.getMaterial();
  65948. if (material.disableDepthWrite) {
  65949. return false;
  65950. }
  65951. var defines = [];
  65952. var attribs = [BABYLON.VertexBuffer.PositionKind];
  65953. var mesh = subMesh.getMesh();
  65954. // Alpha test
  65955. if (material && material.needAlphaTesting()) {
  65956. defines.push("#define ALPHATEST");
  65957. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  65958. attribs.push(BABYLON.VertexBuffer.UVKind);
  65959. defines.push("#define UV1");
  65960. }
  65961. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  65962. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  65963. defines.push("#define UV2");
  65964. }
  65965. }
  65966. // Bones
  65967. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  65968. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  65969. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  65970. if (mesh.numBoneInfluencers > 4) {
  65971. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  65972. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  65973. }
  65974. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  65975. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  65976. }
  65977. else {
  65978. defines.push("#define NUM_BONE_INFLUENCERS 0");
  65979. }
  65980. // Instances
  65981. if (useInstances) {
  65982. defines.push("#define INSTANCES");
  65983. attribs.push("world0");
  65984. attribs.push("world1");
  65985. attribs.push("world2");
  65986. attribs.push("world3");
  65987. }
  65988. // Get correct effect
  65989. var join = defines.join("\n");
  65990. if (this._cachedDefines !== join) {
  65991. this._cachedDefines = join;
  65992. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  65993. }
  65994. return this._effect.isReady();
  65995. };
  65996. DepthRenderer.prototype.getDepthMap = function () {
  65997. return this._depthMap;
  65998. };
  65999. // Methods
  66000. DepthRenderer.prototype.dispose = function () {
  66001. this._depthMap.dispose();
  66002. };
  66003. return DepthRenderer;
  66004. }());
  66005. BABYLON.DepthRenderer = DepthRenderer;
  66006. })(BABYLON || (BABYLON = {}));
  66007. //# sourceMappingURL=babylon.depthRenderer.js.map
  66008. var BABYLON;
  66009. (function (BABYLON) {
  66010. var SSAORenderingPipeline = /** @class */ (function (_super) {
  66011. __extends(SSAORenderingPipeline, _super);
  66012. /**
  66013. * @constructor
  66014. * @param {string} name - The rendering pipeline name
  66015. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66016. * @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 }
  66017. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66018. */
  66019. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  66020. var _this = _super.call(this, scene.getEngine(), name) || this;
  66021. // Members
  66022. /**
  66023. * The PassPostProcess id in the pipeline that contains the original scene color
  66024. * @type {string}
  66025. */
  66026. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66027. /**
  66028. * The SSAO PostProcess id in the pipeline
  66029. * @type {string}
  66030. */
  66031. _this.SSAORenderEffect = "SSAORenderEffect";
  66032. /**
  66033. * The horizontal blur PostProcess id in the pipeline
  66034. * @type {string}
  66035. */
  66036. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66037. /**
  66038. * The vertical blur PostProcess id in the pipeline
  66039. * @type {string}
  66040. */
  66041. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66042. /**
  66043. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66044. * @type {string}
  66045. */
  66046. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66047. /**
  66048. * The output strength of the SSAO post-process. Default value is 1.0.
  66049. * @type {number}
  66050. */
  66051. _this.totalStrength = 1.0;
  66052. /**
  66053. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  66054. * @type {number}
  66055. */
  66056. _this.radius = 0.0001;
  66057. /**
  66058. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  66059. * Must not be equal to fallOff and superior to fallOff.
  66060. * Default value is 0.975
  66061. * @type {number}
  66062. */
  66063. _this.area = 0.0075;
  66064. /**
  66065. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  66066. * Must not be equal to area and inferior to area.
  66067. * Default value is 0.0
  66068. * @type {number}
  66069. */
  66070. _this.fallOff = 0.000001;
  66071. /**
  66072. * The base color of the SSAO post-process
  66073. * The final result is "base + ssao" between [0, 1]
  66074. * @type {number}
  66075. */
  66076. _this.base = 0.5;
  66077. _this._firstUpdate = true;
  66078. _this._scene = scene;
  66079. // Set up assets
  66080. _this._createRandomTexture();
  66081. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66082. var ssaoRatio = ratio.ssaoRatio || ratio;
  66083. var combineRatio = ratio.combineRatio || ratio;
  66084. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66085. _this._createSSAOPostProcess(ssaoRatio);
  66086. _this._createBlurPostProcess(ssaoRatio);
  66087. _this._createSSAOCombinePostProcess(combineRatio);
  66088. // Set up pipeline
  66089. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66090. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66091. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66092. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66093. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66094. // Finish
  66095. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66096. if (cameras)
  66097. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66098. return _this;
  66099. }
  66100. // Public Methods
  66101. /**
  66102. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66103. */
  66104. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66105. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66106. for (var i = 0; i < this._scene.cameras.length; i++) {
  66107. var camera = this._scene.cameras[i];
  66108. this._originalColorPostProcess.dispose(camera);
  66109. this._ssaoPostProcess.dispose(camera);
  66110. this._blurHPostProcess.dispose(camera);
  66111. this._blurVPostProcess.dispose(camera);
  66112. this._ssaoCombinePostProcess.dispose(camera);
  66113. }
  66114. this._randomTexture.dispose();
  66115. if (disableDepthRender)
  66116. this._scene.disableDepthRenderer();
  66117. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66118. _super.prototype.dispose.call(this);
  66119. };
  66120. // Private Methods
  66121. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  66122. var _this = this;
  66123. var size = 16;
  66124. 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);
  66125. 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);
  66126. this._blurHPostProcess.onActivateObservable.add(function () {
  66127. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  66128. _this._blurHPostProcess.kernel = size * dw;
  66129. });
  66130. this._blurVPostProcess.onActivateObservable.add(function () {
  66131. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  66132. _this._blurVPostProcess.kernel = size * dw;
  66133. });
  66134. };
  66135. SSAORenderingPipeline.prototype._rebuild = function () {
  66136. this._firstUpdate = true;
  66137. _super.prototype._rebuild.call(this);
  66138. };
  66139. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66140. var _this = this;
  66141. var numSamples = 16;
  66142. var sampleSphere = [
  66143. 0.5381, 0.1856, -0.4319,
  66144. 0.1379, 0.2486, 0.4430,
  66145. 0.3371, 0.5679, -0.0057,
  66146. -0.6999, -0.0451, -0.0019,
  66147. 0.0689, -0.1598, -0.8547,
  66148. 0.0560, 0.0069, -0.1843,
  66149. -0.0146, 0.1402, 0.0762,
  66150. 0.0100, -0.1924, -0.0344,
  66151. -0.3577, -0.5301, -0.4358,
  66152. -0.3169, 0.1063, 0.0158,
  66153. 0.0103, -0.5869, 0.0046,
  66154. -0.0897, -0.4940, 0.3287,
  66155. 0.7119, -0.0154, -0.0918,
  66156. -0.0533, 0.0596, -0.5411,
  66157. 0.0352, -0.0631, 0.5460,
  66158. -0.4776, 0.2847, -0.0271
  66159. ];
  66160. var samplesFactor = 1.0 / numSamples;
  66161. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  66162. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66163. "area", "fallOff", "base", "range", "viewport"
  66164. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66165. this._ssaoPostProcess.onApply = function (effect) {
  66166. if (_this._firstUpdate) {
  66167. effect.setArray3("sampleSphere", sampleSphere);
  66168. effect.setFloat("samplesFactor", samplesFactor);
  66169. effect.setFloat("randTextureTiles", 4.0);
  66170. }
  66171. effect.setFloat("totalStrength", _this.totalStrength);
  66172. effect.setFloat("radius", _this.radius);
  66173. effect.setFloat("area", _this.area);
  66174. effect.setFloat("fallOff", _this.fallOff);
  66175. effect.setFloat("base", _this.base);
  66176. effect.setTexture("textureSampler", _this._depthTexture);
  66177. effect.setTexture("randomSampler", _this._randomTexture);
  66178. };
  66179. };
  66180. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66181. var _this = this;
  66182. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66183. this._ssaoCombinePostProcess.onApply = function (effect) {
  66184. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66185. };
  66186. };
  66187. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  66188. var size = 512;
  66189. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66190. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66191. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66192. var context = this._randomTexture.getContext();
  66193. var rand = function (min, max) {
  66194. return Math.random() * (max - min) + min;
  66195. };
  66196. var randVector = BABYLON.Vector3.Zero();
  66197. for (var x = 0; x < size; x++) {
  66198. for (var y = 0; y < size; y++) {
  66199. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  66200. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  66201. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  66202. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66203. context.fillRect(x, y, 1, 1);
  66204. }
  66205. }
  66206. this._randomTexture.update(false);
  66207. };
  66208. __decorate([
  66209. BABYLON.serialize()
  66210. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  66211. __decorate([
  66212. BABYLON.serialize()
  66213. ], SSAORenderingPipeline.prototype, "radius", void 0);
  66214. __decorate([
  66215. BABYLON.serialize()
  66216. ], SSAORenderingPipeline.prototype, "area", void 0);
  66217. __decorate([
  66218. BABYLON.serialize()
  66219. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  66220. __decorate([
  66221. BABYLON.serialize()
  66222. ], SSAORenderingPipeline.prototype, "base", void 0);
  66223. return SSAORenderingPipeline;
  66224. }(BABYLON.PostProcessRenderPipeline));
  66225. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  66226. })(BABYLON || (BABYLON = {}));
  66227. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  66228. var BABYLON;
  66229. (function (BABYLON) {
  66230. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  66231. __extends(SSAO2RenderingPipeline, _super);
  66232. /**
  66233. * @constructor
  66234. * @param {string} name - The rendering pipeline name
  66235. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66236. * @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 }
  66237. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66238. */
  66239. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  66240. var _this = _super.call(this, scene.getEngine(), name) || this;
  66241. // Members
  66242. /**
  66243. * The PassPostProcess id in the pipeline that contains the original scene color
  66244. * @type {string}
  66245. */
  66246. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  66247. /**
  66248. * The SSAO PostProcess id in the pipeline
  66249. * @type {string}
  66250. */
  66251. _this.SSAORenderEffect = "SSAORenderEffect";
  66252. /**
  66253. * The horizontal blur PostProcess id in the pipeline
  66254. * @type {string}
  66255. */
  66256. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  66257. /**
  66258. * The vertical blur PostProcess id in the pipeline
  66259. * @type {string}
  66260. */
  66261. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  66262. /**
  66263. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  66264. * @type {string}
  66265. */
  66266. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  66267. /**
  66268. * The output strength of the SSAO post-process. Default value is 1.0.
  66269. * @type {number}
  66270. */
  66271. _this.totalStrength = 1.0;
  66272. /**
  66273. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  66274. * @type {number}
  66275. */
  66276. _this.maxZ = 100.0;
  66277. /**
  66278. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  66279. * @type {number}
  66280. */
  66281. _this.minZAspect = 0.2;
  66282. /**
  66283. * Number of samples used for the SSAO calculations. Default value is 8
  66284. * @type {number}
  66285. */
  66286. _this._samples = 8;
  66287. /**
  66288. * Are we using bilateral blur ?
  66289. * @type {boolean}
  66290. */
  66291. _this._expensiveBlur = true;
  66292. /**
  66293. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  66294. * @type {number}
  66295. */
  66296. _this.radius = 2.0;
  66297. /**
  66298. * The base color of the SSAO post-process
  66299. * The final result is "base + ssao" between [0, 1]
  66300. * @type {number}
  66301. */
  66302. _this.base = 0.1;
  66303. _this._firstUpdate = true;
  66304. _this._scene = scene;
  66305. if (!_this.isSupported) {
  66306. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  66307. return _this;
  66308. }
  66309. var ssaoRatio = ratio.ssaoRatio || ratio;
  66310. var blurRatio = ratio.blurRatio || ratio;
  66311. // Set up assets
  66312. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  66313. _this._createRandomTexture();
  66314. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  66315. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  66316. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  66317. _this._createSSAOPostProcess(1.0);
  66318. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  66319. _this._createSSAOCombinePostProcess(blurRatio);
  66320. // Set up pipeline
  66321. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  66322. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  66323. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  66324. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  66325. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  66326. // Finish
  66327. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66328. if (cameras)
  66329. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66330. return _this;
  66331. }
  66332. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  66333. get: function () {
  66334. return this._samples;
  66335. },
  66336. set: function (n) {
  66337. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  66338. this._samples = n;
  66339. this._sampleSphere = this._generateHemisphere();
  66340. this._firstUpdate = true;
  66341. },
  66342. enumerable: true,
  66343. configurable: true
  66344. });
  66345. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  66346. get: function () {
  66347. return this._expensiveBlur;
  66348. },
  66349. set: function (b) {
  66350. 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"]);
  66351. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  66352. this._expensiveBlur = b;
  66353. this._firstUpdate = true;
  66354. },
  66355. enumerable: true,
  66356. configurable: true
  66357. });
  66358. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  66359. /**
  66360. * Support test.
  66361. * @type {boolean}
  66362. */
  66363. get: function () {
  66364. var engine = BABYLON.Engine.LastCreatedEngine;
  66365. if (!engine) {
  66366. return false;
  66367. }
  66368. return engine.getCaps().drawBuffersExtension;
  66369. },
  66370. enumerable: true,
  66371. configurable: true
  66372. });
  66373. // Public Methods
  66374. /**
  66375. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  66376. */
  66377. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  66378. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  66379. for (var i = 0; i < this._scene.cameras.length; i++) {
  66380. var camera = this._scene.cameras[i];
  66381. this._originalColorPostProcess.dispose(camera);
  66382. this._ssaoPostProcess.dispose(camera);
  66383. this._blurHPostProcess.dispose(camera);
  66384. this._blurVPostProcess.dispose(camera);
  66385. this._ssaoCombinePostProcess.dispose(camera);
  66386. }
  66387. this._randomTexture.dispose();
  66388. if (disableGeometryBufferRenderer)
  66389. this._scene.disableGeometryBufferRenderer();
  66390. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66391. _super.prototype.dispose.call(this);
  66392. };
  66393. // Private Methods
  66394. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  66395. var _this = this;
  66396. this._samplerOffsets = [];
  66397. var expensive = this.expensiveBlur;
  66398. for (var i = -8; i < 8; i++) {
  66399. this._samplerOffsets.push(i * 2 + 0.5);
  66400. }
  66401. 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");
  66402. this._blurHPostProcess.onApply = function (effect) {
  66403. if (!_this._scene.activeCamera) {
  66404. return;
  66405. }
  66406. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  66407. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66408. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66409. effect.setFloat("radius", _this.radius);
  66410. effect.setTexture("depthSampler", _this._depthTexture);
  66411. if (_this._firstUpdate) {
  66412. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66413. }
  66414. };
  66415. 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");
  66416. this._blurVPostProcess.onApply = function (effect) {
  66417. if (!_this._scene.activeCamera) {
  66418. return;
  66419. }
  66420. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  66421. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66422. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66423. effect.setFloat("radius", _this.radius);
  66424. effect.setTexture("depthSampler", _this._depthTexture);
  66425. if (_this._firstUpdate) {
  66426. effect.setArray("samplerOffsets", _this._samplerOffsets);
  66427. _this._firstUpdate = false;
  66428. }
  66429. };
  66430. };
  66431. SSAO2RenderingPipeline.prototype._rebuild = function () {
  66432. this._firstUpdate = true;
  66433. _super.prototype._rebuild.call(this);
  66434. };
  66435. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  66436. var numSamples = this.samples;
  66437. var result = [];
  66438. var vector, scale;
  66439. var rand = function (min, max) {
  66440. return Math.random() * (max - min) + min;
  66441. };
  66442. var i = 0;
  66443. while (i < numSamples) {
  66444. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  66445. vector.normalize();
  66446. scale = i / numSamples;
  66447. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  66448. vector.scaleInPlace(scale);
  66449. result.push(vector.x, vector.y, vector.z);
  66450. i++;
  66451. }
  66452. return result;
  66453. };
  66454. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  66455. var _this = this;
  66456. var numSamples = this.samples;
  66457. this._sampleSphere = this._generateHemisphere();
  66458. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  66459. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  66460. "base", "range", "projection", "near", "far", "texelSize",
  66461. "xViewport", "yViewport", "maxZ", "minZAspect"
  66462. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  66463. this._ssaoPostProcess.onApply = function (effect) {
  66464. if (_this._firstUpdate) {
  66465. effect.setArray3("sampleSphere", _this._sampleSphere);
  66466. effect.setFloat("randTextureTiles", 4.0);
  66467. }
  66468. if (!_this._scene.activeCamera) {
  66469. return;
  66470. }
  66471. effect.setFloat("samplesFactor", 1 / _this.samples);
  66472. effect.setFloat("totalStrength", _this.totalStrength);
  66473. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  66474. effect.setFloat("radius", _this.radius);
  66475. effect.setFloat("maxZ", _this.maxZ);
  66476. effect.setFloat("minZAspect", _this.minZAspect);
  66477. effect.setFloat("base", _this.base);
  66478. effect.setFloat("near", _this._scene.activeCamera.minZ);
  66479. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  66480. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  66481. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  66482. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  66483. effect.setTexture("textureSampler", _this._depthTexture);
  66484. effect.setTexture("normalSampler", _this._normalTexture);
  66485. effect.setTexture("randomSampler", _this._randomTexture);
  66486. };
  66487. };
  66488. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  66489. var _this = this;
  66490. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66491. this._ssaoCombinePostProcess.onApply = function (effect) {
  66492. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  66493. };
  66494. };
  66495. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  66496. var size = 512;
  66497. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  66498. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66499. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66500. var context = this._randomTexture.getContext();
  66501. var rand = function (min, max) {
  66502. return Math.random() * (max - min) + min;
  66503. };
  66504. var randVector = BABYLON.Vector3.Zero();
  66505. for (var x = 0; x < size; x++) {
  66506. for (var y = 0; y < size; y++) {
  66507. randVector.x = rand(0.0, 1.0);
  66508. randVector.y = rand(0.0, 1.0);
  66509. randVector.z = 0.0;
  66510. randVector.normalize();
  66511. randVector.scaleInPlace(255);
  66512. randVector.x = Math.floor(randVector.x);
  66513. randVector.y = Math.floor(randVector.y);
  66514. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  66515. context.fillRect(x, y, 1, 1);
  66516. }
  66517. }
  66518. this._randomTexture.update(false);
  66519. };
  66520. __decorate([
  66521. BABYLON.serialize()
  66522. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  66523. __decorate([
  66524. BABYLON.serialize()
  66525. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  66526. __decorate([
  66527. BABYLON.serialize()
  66528. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  66529. __decorate([
  66530. BABYLON.serialize("samples")
  66531. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  66532. __decorate([
  66533. BABYLON.serialize("expensiveBlur")
  66534. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  66535. __decorate([
  66536. BABYLON.serialize()
  66537. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  66538. __decorate([
  66539. BABYLON.serialize()
  66540. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  66541. return SSAO2RenderingPipeline;
  66542. }(BABYLON.PostProcessRenderPipeline));
  66543. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  66544. })(BABYLON || (BABYLON = {}));
  66545. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  66546. // BABYLON.JS Chromatic Aberration GLSL Shader
  66547. // Author: Olivier Guyot
  66548. // Separates very slightly R, G and B colors on the edges of the screen
  66549. // Inspired by Francois Tarlier & Martins Upitis
  66550. var BABYLON;
  66551. (function (BABYLON) {
  66552. var LensRenderingPipeline = /** @class */ (function (_super) {
  66553. __extends(LensRenderingPipeline, _super);
  66554. /**
  66555. * @constructor
  66556. *
  66557. * Effect parameters are as follow:
  66558. * {
  66559. * chromatic_aberration: number; // from 0 to x (1 for realism)
  66560. * edge_blur: number; // from 0 to x (1 for realism)
  66561. * distortion: number; // from 0 to x (1 for realism)
  66562. * grain_amount: number; // from 0 to 1
  66563. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  66564. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  66565. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  66566. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  66567. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  66568. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  66569. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  66570. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  66571. * }
  66572. * Note: if an effect parameter is unset, effect is disabled
  66573. *
  66574. * @param {string} name - The rendering pipeline name
  66575. * @param {object} parameters - An object containing all parameters (see above)
  66576. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66577. * @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)
  66578. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66579. */
  66580. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  66581. if (ratio === void 0) { ratio = 1.0; }
  66582. var _this = _super.call(this, scene.getEngine(), name) || this;
  66583. // Lens effects can be of the following:
  66584. // - chromatic aberration (slight shift of RGB colors)
  66585. // - blur on the edge of the lens
  66586. // - lens distortion
  66587. // - depth-of-field blur & highlights enhancing
  66588. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  66589. // - grain effect (noise or custom texture)
  66590. // Two additional texture samplers are needed:
  66591. // - depth map (for depth-of-field)
  66592. // - grain texture
  66593. /**
  66594. * The chromatic aberration PostProcess id in the pipeline
  66595. * @type {string}
  66596. */
  66597. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  66598. /**
  66599. * The highlights enhancing PostProcess id in the pipeline
  66600. * @type {string}
  66601. */
  66602. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  66603. /**
  66604. * The depth-of-field PostProcess id in the pipeline
  66605. * @type {string}
  66606. */
  66607. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  66608. _this._scene = scene;
  66609. // Fetch texture samplers
  66610. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  66611. if (parameters.grain_texture) {
  66612. _this._grainTexture = parameters.grain_texture;
  66613. }
  66614. else {
  66615. _this._createGrainTexture();
  66616. }
  66617. // save parameters
  66618. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  66619. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  66620. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  66621. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  66622. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  66623. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  66624. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  66625. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  66626. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  66627. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  66628. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  66629. // Create effects
  66630. _this._createChromaticAberrationPostProcess(ratio);
  66631. _this._createHighlightsPostProcess(ratio);
  66632. _this._createDepthOfFieldPostProcess(ratio / 4);
  66633. // Set up pipeline
  66634. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  66635. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  66636. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  66637. if (_this._highlightsGain === -1) {
  66638. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  66639. }
  66640. // Finish
  66641. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66642. if (cameras) {
  66643. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  66644. }
  66645. return _this;
  66646. }
  66647. // public methods (self explanatory)
  66648. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  66649. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  66650. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  66651. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  66652. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  66653. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  66654. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  66655. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  66656. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  66657. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  66658. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  66659. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  66660. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  66661. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  66662. };
  66663. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  66664. this._highlightsPostProcess.updateEffect();
  66665. };
  66666. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  66667. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  66668. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  66669. this._highlightsGain = amount;
  66670. };
  66671. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  66672. if (this._highlightsGain === -1) {
  66673. this._highlightsGain = 1.0;
  66674. }
  66675. this._highlightsThreshold = amount;
  66676. };
  66677. LensRenderingPipeline.prototype.disableHighlights = function () {
  66678. this._highlightsGain = -1;
  66679. };
  66680. /**
  66681. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  66682. */
  66683. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  66684. if (disableDepthRender === void 0) { disableDepthRender = false; }
  66685. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  66686. this._chromaticAberrationPostProcess = null;
  66687. this._highlightsPostProcess = null;
  66688. this._depthOfFieldPostProcess = null;
  66689. this._grainTexture.dispose();
  66690. if (disableDepthRender)
  66691. this._scene.disableDepthRenderer();
  66692. };
  66693. // colors shifting and distortion
  66694. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  66695. var _this = this;
  66696. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  66697. [], // samplers
  66698. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66699. this._chromaticAberrationPostProcess.onApply = function (effect) {
  66700. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  66701. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66702. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66703. };
  66704. };
  66705. // highlights enhancing
  66706. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  66707. var _this = this;
  66708. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  66709. [], // samplers
  66710. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  66711. this._highlightsPostProcess.onApply = function (effect) {
  66712. effect.setFloat('gain', _this._highlightsGain);
  66713. effect.setFloat('threshold', _this._highlightsThreshold);
  66714. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  66715. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66716. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66717. };
  66718. };
  66719. // colors shifting and distortion
  66720. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  66721. var _this = this;
  66722. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  66723. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  66724. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  66725. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  66726. this._depthOfFieldPostProcess.onApply = function (effect) {
  66727. effect.setTexture("depthSampler", _this._depthTexture);
  66728. effect.setTexture("grainSampler", _this._grainTexture);
  66729. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  66730. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  66731. effect.setFloat('grain_amount', _this._grainAmount);
  66732. effect.setBool('blur_noise', _this._blurNoise);
  66733. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  66734. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  66735. effect.setFloat('distortion', _this._distortion);
  66736. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  66737. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  66738. effect.setFloat('aperture', _this._dofAperture);
  66739. effect.setFloat('darken', _this._dofDarken);
  66740. effect.setFloat('edge_blur', _this._edgeBlur);
  66741. effect.setBool('highlights', (_this._highlightsGain !== -1));
  66742. if (_this._scene.activeCamera) {
  66743. effect.setFloat('near', _this._scene.activeCamera.minZ);
  66744. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  66745. }
  66746. };
  66747. };
  66748. // creates a black and white random noise texture, 512x512
  66749. LensRenderingPipeline.prototype._createGrainTexture = function () {
  66750. var size = 512;
  66751. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66752. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  66753. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  66754. var context = this._grainTexture.getContext();
  66755. var rand = function (min, max) {
  66756. return Math.random() * (max - min) + min;
  66757. };
  66758. var value;
  66759. for (var x = 0; x < size; x++) {
  66760. for (var y = 0; y < size; y++) {
  66761. value = Math.floor(rand(0.42, 0.58) * 255);
  66762. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  66763. context.fillRect(x, y, 1, 1);
  66764. }
  66765. }
  66766. this._grainTexture.update(false);
  66767. };
  66768. return LensRenderingPipeline;
  66769. }(BABYLON.PostProcessRenderPipeline));
  66770. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  66771. })(BABYLON || (BABYLON = {}));
  66772. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  66773. var BABYLON;
  66774. (function (BABYLON) {
  66775. var StandardRenderingPipeline = /** @class */ (function (_super) {
  66776. __extends(StandardRenderingPipeline, _super);
  66777. /**
  66778. * @constructor
  66779. * @param {string} name - The rendering pipeline name
  66780. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  66781. * @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)
  66782. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  66783. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  66784. */
  66785. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  66786. if (originalPostProcess === void 0) { originalPostProcess = null; }
  66787. var _this = _super.call(this, scene.getEngine(), name) || this;
  66788. _this.downSampleX4PostProcess = null;
  66789. _this.brightPassPostProcess = null;
  66790. _this.blurHPostProcesses = [];
  66791. _this.blurVPostProcesses = [];
  66792. _this.textureAdderPostProcess = null;
  66793. _this.volumetricLightPostProcess = null;
  66794. _this.volumetricLightSmoothXPostProcess = null;
  66795. _this.volumetricLightSmoothYPostProcess = null;
  66796. _this.volumetricLightMergePostProces = null;
  66797. _this.volumetricLightFinalPostProcess = null;
  66798. _this.luminancePostProcess = null;
  66799. _this.luminanceDownSamplePostProcesses = [];
  66800. _this.hdrPostProcess = null;
  66801. _this.textureAdderFinalPostProcess = null;
  66802. _this.lensFlareFinalPostProcess = null;
  66803. _this.hdrFinalPostProcess = null;
  66804. _this.lensFlarePostProcess = null;
  66805. _this.lensFlareComposePostProcess = null;
  66806. _this.motionBlurPostProcess = null;
  66807. _this.depthOfFieldPostProcess = null;
  66808. // Values
  66809. _this.brightThreshold = 1.0;
  66810. _this.blurWidth = 512.0;
  66811. _this.horizontalBlur = false;
  66812. _this.exposure = 1.0;
  66813. _this.lensTexture = null;
  66814. _this.volumetricLightCoefficient = 0.2;
  66815. _this.volumetricLightPower = 4.0;
  66816. _this.volumetricLightBlurScale = 64.0;
  66817. _this.sourceLight = null;
  66818. _this.hdrMinimumLuminance = 1.0;
  66819. _this.hdrDecreaseRate = 0.5;
  66820. _this.hdrIncreaseRate = 0.5;
  66821. _this.lensColorTexture = null;
  66822. _this.lensFlareStrength = 20.0;
  66823. _this.lensFlareGhostDispersal = 1.4;
  66824. _this.lensFlareHaloWidth = 0.7;
  66825. _this.lensFlareDistortionStrength = 16.0;
  66826. _this.lensStarTexture = null;
  66827. _this.lensFlareDirtTexture = null;
  66828. _this.depthOfFieldDistance = 10.0;
  66829. _this.depthOfFieldBlurWidth = 64.0;
  66830. _this.motionStrength = 1.0;
  66831. // IAnimatable
  66832. _this.animations = [];
  66833. _this._currentDepthOfFieldSource = null;
  66834. _this._hdrCurrentLuminance = 1.0;
  66835. // Getters and setters
  66836. _this._bloomEnabled = true;
  66837. _this._depthOfFieldEnabled = false;
  66838. _this._vlsEnabled = false;
  66839. _this._lensFlareEnabled = false;
  66840. _this._hdrEnabled = false;
  66841. _this._motionBlurEnabled = false;
  66842. _this._motionBlurSamples = 64.0;
  66843. _this._volumetricLightStepsCount = 50.0;
  66844. _this._cameras = cameras || [];
  66845. // Initialize
  66846. _this._scene = scene;
  66847. _this._basePostProcess = originalPostProcess;
  66848. _this._ratio = ratio;
  66849. // Misc
  66850. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66851. // Finish
  66852. scene.postProcessRenderPipelineManager.addPipeline(_this);
  66853. _this._buildPipeline();
  66854. return _this;
  66855. }
  66856. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  66857. get: function () {
  66858. return this._bloomEnabled;
  66859. },
  66860. set: function (enabled) {
  66861. if (this._bloomEnabled === enabled) {
  66862. return;
  66863. }
  66864. this._bloomEnabled = enabled;
  66865. this._buildPipeline();
  66866. },
  66867. enumerable: true,
  66868. configurable: true
  66869. });
  66870. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  66871. get: function () {
  66872. return this._depthOfFieldEnabled;
  66873. },
  66874. set: function (enabled) {
  66875. if (this._depthOfFieldEnabled === enabled) {
  66876. return;
  66877. }
  66878. this._depthOfFieldEnabled = enabled;
  66879. this._buildPipeline();
  66880. },
  66881. enumerable: true,
  66882. configurable: true
  66883. });
  66884. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  66885. get: function () {
  66886. return this._lensFlareEnabled;
  66887. },
  66888. set: function (enabled) {
  66889. if (this._lensFlareEnabled === enabled) {
  66890. return;
  66891. }
  66892. this._lensFlareEnabled = enabled;
  66893. this._buildPipeline();
  66894. },
  66895. enumerable: true,
  66896. configurable: true
  66897. });
  66898. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  66899. get: function () {
  66900. return this._hdrEnabled;
  66901. },
  66902. set: function (enabled) {
  66903. if (this._hdrEnabled === enabled) {
  66904. return;
  66905. }
  66906. this._hdrEnabled = enabled;
  66907. this._buildPipeline();
  66908. },
  66909. enumerable: true,
  66910. configurable: true
  66911. });
  66912. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  66913. get: function () {
  66914. return this._vlsEnabled;
  66915. },
  66916. set: function (enabled) {
  66917. if (this._vlsEnabled === enabled) {
  66918. return;
  66919. }
  66920. if (enabled) {
  66921. var geometry = this._scene.enableGeometryBufferRenderer();
  66922. if (!geometry) {
  66923. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  66924. return;
  66925. }
  66926. }
  66927. this._vlsEnabled = enabled;
  66928. this._buildPipeline();
  66929. },
  66930. enumerable: true,
  66931. configurable: true
  66932. });
  66933. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  66934. get: function () {
  66935. return this._motionBlurEnabled;
  66936. },
  66937. set: function (enabled) {
  66938. if (this._motionBlurEnabled === enabled) {
  66939. return;
  66940. }
  66941. this._motionBlurEnabled = enabled;
  66942. this._buildPipeline();
  66943. },
  66944. enumerable: true,
  66945. configurable: true
  66946. });
  66947. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  66948. get: function () {
  66949. return this._volumetricLightStepsCount;
  66950. },
  66951. set: function (count) {
  66952. if (this.volumetricLightPostProcess) {
  66953. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  66954. }
  66955. this._volumetricLightStepsCount = count;
  66956. },
  66957. enumerable: true,
  66958. configurable: true
  66959. });
  66960. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  66961. get: function () {
  66962. return this._motionBlurSamples;
  66963. },
  66964. set: function (samples) {
  66965. if (this.motionBlurPostProcess) {
  66966. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  66967. }
  66968. this._motionBlurSamples = samples;
  66969. },
  66970. enumerable: true,
  66971. configurable: true
  66972. });
  66973. StandardRenderingPipeline.prototype._buildPipeline = function () {
  66974. var _this = this;
  66975. var ratio = this._ratio;
  66976. var scene = this._scene;
  66977. this._disposePostProcesses();
  66978. this._reset();
  66979. // Create pass post-process
  66980. if (!this._basePostProcess) {
  66981. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  66982. this.originalPostProcess.onApply = function (effect) {
  66983. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  66984. };
  66985. }
  66986. else {
  66987. this.originalPostProcess = this._basePostProcess;
  66988. }
  66989. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  66990. this._currentDepthOfFieldSource = this.originalPostProcess;
  66991. if (this._vlsEnabled) {
  66992. // Create volumetric light
  66993. this._createVolumetricLightPostProcess(scene, ratio);
  66994. // Create volumetric light final post-process
  66995. 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);
  66996. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  66997. }
  66998. if (this._bloomEnabled) {
  66999. // Create down sample X4 post-process
  67000. this._createDownSampleX4PostProcess(scene, ratio / 2);
  67001. // Create bright pass post-process
  67002. this._createBrightPassPostProcess(scene, ratio / 2);
  67003. // Create gaussian blur post-processes (down sampling blurs)
  67004. this._createBlurPostProcesses(scene, ratio / 4, 1);
  67005. // Create texture adder post-process
  67006. this._createTextureAdderPostProcess(scene, ratio);
  67007. // Create depth-of-field source post-process
  67008. 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);
  67009. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  67010. }
  67011. if (this._lensFlareEnabled) {
  67012. // Create lens flare post-process
  67013. this._createLensFlarePostProcess(scene, ratio);
  67014. // Create depth-of-field source post-process post lens-flare and disable it now
  67015. 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);
  67016. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  67017. }
  67018. if (this._hdrEnabled) {
  67019. // Create luminance
  67020. this._createLuminancePostProcesses(scene, this._floatTextureType);
  67021. // Create HDR
  67022. this._createHdrPostProcess(scene, ratio);
  67023. // Create depth-of-field source post-process post hdr and disable it now
  67024. 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);
  67025. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  67026. }
  67027. if (this._depthOfFieldEnabled) {
  67028. // Create gaussian blur used by depth-of-field
  67029. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  67030. // Create depth-of-field post-process
  67031. this._createDepthOfFieldPostProcess(scene, ratio);
  67032. }
  67033. if (this._motionBlurEnabled) {
  67034. // Create motion blur post-process
  67035. this._createMotionBlurPostProcess(scene, ratio);
  67036. }
  67037. if (this._cameras !== null) {
  67038. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  67039. }
  67040. };
  67041. // Down Sample X4 Post-Processs
  67042. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  67043. var _this = this;
  67044. var downSampleX4Offsets = new Array(32);
  67045. 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);
  67046. this.downSampleX4PostProcess.onApply = function (effect) {
  67047. var id = 0;
  67048. var width = _this.downSampleX4PostProcess.width;
  67049. var height = _this.downSampleX4PostProcess.height;
  67050. for (var i = -2; i < 2; i++) {
  67051. for (var j = -2; j < 2; j++) {
  67052. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  67053. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  67054. id += 2;
  67055. }
  67056. }
  67057. effect.setArray2("dsOffsets", downSampleX4Offsets);
  67058. };
  67059. // Add to pipeline
  67060. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  67061. };
  67062. // Brightpass Post-Process
  67063. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  67064. var _this = this;
  67065. var brightOffsets = new Array(8);
  67066. 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);
  67067. this.brightPassPostProcess.onApply = function (effect) {
  67068. var sU = (1.0 / _this.brightPassPostProcess.width);
  67069. var sV = (1.0 / _this.brightPassPostProcess.height);
  67070. brightOffsets[0] = -0.5 * sU;
  67071. brightOffsets[1] = 0.5 * sV;
  67072. brightOffsets[2] = 0.5 * sU;
  67073. brightOffsets[3] = 0.5 * sV;
  67074. brightOffsets[4] = -0.5 * sU;
  67075. brightOffsets[5] = -0.5 * sV;
  67076. brightOffsets[6] = 0.5 * sU;
  67077. brightOffsets[7] = -0.5 * sV;
  67078. effect.setArray2("dsOffsets", brightOffsets);
  67079. effect.setFloat("brightThreshold", _this.brightThreshold);
  67080. };
  67081. // Add to pipeline
  67082. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  67083. };
  67084. // Create blur H&V post-processes
  67085. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  67086. var _this = this;
  67087. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  67088. var engine = scene.getEngine();
  67089. 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);
  67090. 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);
  67091. blurX.onActivateObservable.add(function () {
  67092. var dw = blurX.width / engine.getRenderWidth();
  67093. blurX.kernel = _this[blurWidthKey] * dw;
  67094. });
  67095. blurY.onActivateObservable.add(function () {
  67096. var dw = blurY.height / engine.getRenderHeight();
  67097. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  67098. });
  67099. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  67100. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  67101. this.blurHPostProcesses.push(blurX);
  67102. this.blurVPostProcesses.push(blurY);
  67103. };
  67104. // Create texture adder post-process
  67105. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  67106. var _this = this;
  67107. 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);
  67108. this.textureAdderPostProcess.onApply = function (effect) {
  67109. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  67110. effect.setTexture("lensSampler", _this.lensTexture);
  67111. effect.setFloat("exposure", _this.exposure);
  67112. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  67113. };
  67114. // Add to pipeline
  67115. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  67116. };
  67117. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  67118. var _this = this;
  67119. var geometryRenderer = scene.enableGeometryBufferRenderer();
  67120. geometryRenderer.enablePosition = true;
  67121. var geometry = geometryRenderer.getGBuffer();
  67122. // Base post-process
  67123. 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));
  67124. var depthValues = BABYLON.Vector2.Zero();
  67125. this.volumetricLightPostProcess.onApply = function (effect) {
  67126. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  67127. var generator = _this.sourceLight.getShadowGenerator();
  67128. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  67129. effect.setTexture("positionSampler", geometry.textures[2]);
  67130. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  67131. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  67132. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  67133. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  67134. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  67135. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  67136. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  67137. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  67138. effect.setVector2("depthValues", depthValues);
  67139. }
  67140. };
  67141. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  67142. // Smooth
  67143. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  67144. // Merge
  67145. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  67146. this.volumetricLightMergePostProces.onApply = function (effect) {
  67147. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  67148. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  67149. };
  67150. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  67151. };
  67152. // Create luminance
  67153. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  67154. var _this = this;
  67155. // Create luminance
  67156. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  67157. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  67158. var offsets = [];
  67159. this.luminancePostProcess.onApply = function (effect) {
  67160. var sU = (1.0 / _this.luminancePostProcess.width);
  67161. var sV = (1.0 / _this.luminancePostProcess.height);
  67162. offsets[0] = -0.5 * sU;
  67163. offsets[1] = 0.5 * sV;
  67164. offsets[2] = 0.5 * sU;
  67165. offsets[3] = 0.5 * sV;
  67166. offsets[4] = -0.5 * sU;
  67167. offsets[5] = -0.5 * sV;
  67168. offsets[6] = 0.5 * sU;
  67169. offsets[7] = -0.5 * sV;
  67170. effect.setArray2("lumOffsets", offsets);
  67171. };
  67172. // Add to pipeline
  67173. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  67174. // Create down sample luminance
  67175. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  67176. var size = Math.pow(3, i);
  67177. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  67178. if (i === 0) {
  67179. defines += "#define FINAL_DOWN_SAMPLER";
  67180. }
  67181. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  67182. this.luminanceDownSamplePostProcesses.push(postProcess);
  67183. }
  67184. // Create callbacks and add effects
  67185. var lastLuminance = this.luminancePostProcess;
  67186. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  67187. var downSampleOffsets = new Array(18);
  67188. pp.onApply = function (effect) {
  67189. if (!lastLuminance) {
  67190. return;
  67191. }
  67192. var id = 0;
  67193. for (var x = -1; x < 2; x++) {
  67194. for (var y = -1; y < 2; y++) {
  67195. downSampleOffsets[id] = x / lastLuminance.width;
  67196. downSampleOffsets[id + 1] = y / lastLuminance.height;
  67197. id += 2;
  67198. }
  67199. }
  67200. effect.setArray2("dsOffsets", downSampleOffsets);
  67201. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  67202. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67203. lastLuminance = _this.luminancePostProcess;
  67204. }
  67205. else {
  67206. lastLuminance = pp;
  67207. }
  67208. };
  67209. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  67210. pp.onAfterRender = function (effect) {
  67211. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  67212. 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);
  67213. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  67214. };
  67215. }
  67216. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  67217. });
  67218. };
  67219. // Create HDR post-process
  67220. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  67221. var _this = this;
  67222. 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);
  67223. var outputLiminance = 1;
  67224. var time = 0;
  67225. var lastTime = 0;
  67226. this.hdrPostProcess.onApply = function (effect) {
  67227. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  67228. time += scene.getEngine().getDeltaTime();
  67229. if (outputLiminance < 0) {
  67230. outputLiminance = _this._hdrCurrentLuminance;
  67231. }
  67232. else {
  67233. var dt = (lastTime - time) / 1000.0;
  67234. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  67235. outputLiminance += _this.hdrDecreaseRate * dt;
  67236. }
  67237. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  67238. outputLiminance -= _this.hdrIncreaseRate * dt;
  67239. }
  67240. else {
  67241. outputLiminance = _this._hdrCurrentLuminance;
  67242. }
  67243. }
  67244. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  67245. effect.setFloat("averageLuminance", outputLiminance);
  67246. lastTime = time;
  67247. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  67248. };
  67249. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  67250. };
  67251. // Create lens flare post-process
  67252. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  67253. var _this = this;
  67254. 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);
  67255. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  67256. this._createBlurPostProcesses(scene, ratio / 4, 2);
  67257. 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);
  67258. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  67259. var resolution = new BABYLON.Vector2(0, 0);
  67260. // Lens flare
  67261. this.lensFlarePostProcess.onApply = function (effect) {
  67262. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  67263. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  67264. effect.setFloat("strength", _this.lensFlareStrength);
  67265. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  67266. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  67267. // Shift
  67268. resolution.x = _this.lensFlarePostProcess.width;
  67269. resolution.y = _this.lensFlarePostProcess.height;
  67270. effect.setVector2("resolution", resolution);
  67271. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  67272. };
  67273. // Compose
  67274. 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);
  67275. 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);
  67276. this.lensFlareComposePostProcess.onApply = function (effect) {
  67277. if (!_this._scene.activeCamera) {
  67278. return;
  67279. }
  67280. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67281. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  67282. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  67283. // Lens start rotation matrix
  67284. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  67285. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  67286. 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));
  67287. camRot *= 4.0;
  67288. 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);
  67289. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  67290. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  67291. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  67292. };
  67293. };
  67294. // Create depth-of-field post-process
  67295. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  67296. var _this = this;
  67297. 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);
  67298. this.depthOfFieldPostProcess.onApply = function (effect) {
  67299. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  67300. effect.setTexture("depthSampler", _this._getDepthTexture());
  67301. effect.setFloat("distance", _this.depthOfFieldDistance);
  67302. };
  67303. // Add to pipeline
  67304. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  67305. };
  67306. // Create motion blur post-process
  67307. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  67308. var _this = this;
  67309. 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);
  67310. var motionScale = 0;
  67311. var prevViewProjection = BABYLON.Matrix.Identity();
  67312. var invViewProjection = BABYLON.Matrix.Identity();
  67313. var viewProjection = BABYLON.Matrix.Identity();
  67314. var screenSize = BABYLON.Vector2.Zero();
  67315. this.motionBlurPostProcess.onApply = function (effect) {
  67316. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  67317. viewProjection.invertToRef(invViewProjection);
  67318. effect.setMatrix("inverseViewProjection", invViewProjection);
  67319. effect.setMatrix("prevViewProjection", prevViewProjection);
  67320. prevViewProjection = viewProjection;
  67321. screenSize.x = _this.motionBlurPostProcess.width;
  67322. screenSize.y = _this.motionBlurPostProcess.height;
  67323. effect.setVector2("screenSize", screenSize);
  67324. motionScale = scene.getEngine().getFps() / 60.0;
  67325. effect.setFloat("motionScale", motionScale);
  67326. effect.setFloat("motionStrength", _this.motionStrength);
  67327. effect.setTexture("depthSampler", _this._getDepthTexture());
  67328. };
  67329. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  67330. };
  67331. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  67332. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  67333. var renderer = this._scene.enableGeometryBufferRenderer();
  67334. return renderer.getGBuffer().textures[0];
  67335. }
  67336. return this._scene.enableDepthRenderer().getDepthMap();
  67337. };
  67338. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  67339. for (var i = 0; i < this._cameras.length; i++) {
  67340. var camera = this._cameras[i];
  67341. if (this.originalPostProcess) {
  67342. this.originalPostProcess.dispose(camera);
  67343. }
  67344. if (this.downSampleX4PostProcess) {
  67345. this.downSampleX4PostProcess.dispose(camera);
  67346. }
  67347. if (this.brightPassPostProcess) {
  67348. this.brightPassPostProcess.dispose(camera);
  67349. }
  67350. if (this.textureAdderPostProcess) {
  67351. this.textureAdderPostProcess.dispose(camera);
  67352. }
  67353. if (this.textureAdderFinalPostProcess) {
  67354. this.textureAdderFinalPostProcess.dispose(camera);
  67355. }
  67356. if (this.volumetricLightPostProcess) {
  67357. this.volumetricLightPostProcess.dispose(camera);
  67358. }
  67359. if (this.volumetricLightSmoothXPostProcess) {
  67360. this.volumetricLightSmoothXPostProcess.dispose(camera);
  67361. }
  67362. if (this.volumetricLightSmoothYPostProcess) {
  67363. this.volumetricLightSmoothYPostProcess.dispose(camera);
  67364. }
  67365. if (this.volumetricLightMergePostProces) {
  67366. this.volumetricLightMergePostProces.dispose(camera);
  67367. }
  67368. if (this.volumetricLightFinalPostProcess) {
  67369. this.volumetricLightFinalPostProcess.dispose(camera);
  67370. }
  67371. if (this.lensFlarePostProcess) {
  67372. this.lensFlarePostProcess.dispose(camera);
  67373. }
  67374. if (this.lensFlareComposePostProcess) {
  67375. this.lensFlareComposePostProcess.dispose(camera);
  67376. }
  67377. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  67378. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  67379. }
  67380. if (this.luminancePostProcess) {
  67381. this.luminancePostProcess.dispose(camera);
  67382. }
  67383. if (this.hdrPostProcess) {
  67384. this.hdrPostProcess.dispose(camera);
  67385. }
  67386. if (this.hdrFinalPostProcess) {
  67387. this.hdrFinalPostProcess.dispose(camera);
  67388. }
  67389. if (this.depthOfFieldPostProcess) {
  67390. this.depthOfFieldPostProcess.dispose(camera);
  67391. }
  67392. if (this.motionBlurPostProcess) {
  67393. this.motionBlurPostProcess.dispose(camera);
  67394. }
  67395. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  67396. this.blurHPostProcesses[j].dispose(camera);
  67397. }
  67398. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  67399. this.blurVPostProcesses[j].dispose(camera);
  67400. }
  67401. }
  67402. this.originalPostProcess = null;
  67403. this.downSampleX4PostProcess = null;
  67404. this.brightPassPostProcess = null;
  67405. this.textureAdderPostProcess = null;
  67406. this.textureAdderFinalPostProcess = null;
  67407. this.volumetricLightPostProcess = null;
  67408. this.volumetricLightSmoothXPostProcess = null;
  67409. this.volumetricLightSmoothYPostProcess = null;
  67410. this.volumetricLightMergePostProces = null;
  67411. this.volumetricLightFinalPostProcess = null;
  67412. this.lensFlarePostProcess = null;
  67413. this.lensFlareComposePostProcess = null;
  67414. this.luminancePostProcess = null;
  67415. this.hdrPostProcess = null;
  67416. this.hdrFinalPostProcess = null;
  67417. this.depthOfFieldPostProcess = null;
  67418. this.motionBlurPostProcess = null;
  67419. this.luminanceDownSamplePostProcesses = [];
  67420. this.blurHPostProcesses = [];
  67421. this.blurVPostProcesses = [];
  67422. };
  67423. // Dispose
  67424. StandardRenderingPipeline.prototype.dispose = function () {
  67425. this._disposePostProcesses();
  67426. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  67427. _super.prototype.dispose.call(this);
  67428. };
  67429. // Serialize rendering pipeline
  67430. StandardRenderingPipeline.prototype.serialize = function () {
  67431. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  67432. serializationObject.customType = "StandardRenderingPipeline";
  67433. return serializationObject;
  67434. };
  67435. /**
  67436. * Static members
  67437. */
  67438. // Parse serialized pipeline
  67439. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  67440. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  67441. };
  67442. // Luminance steps
  67443. StandardRenderingPipeline.LuminanceSteps = 6;
  67444. __decorate([
  67445. BABYLON.serialize()
  67446. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  67447. __decorate([
  67448. BABYLON.serialize()
  67449. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  67450. __decorate([
  67451. BABYLON.serialize()
  67452. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  67453. __decorate([
  67454. BABYLON.serialize()
  67455. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  67456. __decorate([
  67457. BABYLON.serializeAsTexture("lensTexture")
  67458. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  67459. __decorate([
  67460. BABYLON.serialize()
  67461. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  67462. __decorate([
  67463. BABYLON.serialize()
  67464. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  67465. __decorate([
  67466. BABYLON.serialize()
  67467. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  67468. __decorate([
  67469. BABYLON.serialize()
  67470. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  67471. __decorate([
  67472. BABYLON.serialize()
  67473. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  67474. __decorate([
  67475. BABYLON.serialize()
  67476. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  67477. __decorate([
  67478. BABYLON.serializeAsTexture("lensColorTexture")
  67479. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  67480. __decorate([
  67481. BABYLON.serialize()
  67482. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  67483. __decorate([
  67484. BABYLON.serialize()
  67485. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  67486. __decorate([
  67487. BABYLON.serialize()
  67488. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  67489. __decorate([
  67490. BABYLON.serialize()
  67491. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  67492. __decorate([
  67493. BABYLON.serializeAsTexture("lensStarTexture")
  67494. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  67495. __decorate([
  67496. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  67497. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  67498. __decorate([
  67499. BABYLON.serialize()
  67500. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  67501. __decorate([
  67502. BABYLON.serialize()
  67503. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  67504. __decorate([
  67505. BABYLON.serialize()
  67506. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  67507. __decorate([
  67508. BABYLON.serialize()
  67509. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  67510. __decorate([
  67511. BABYLON.serialize()
  67512. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  67513. __decorate([
  67514. BABYLON.serialize()
  67515. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  67516. __decorate([
  67517. BABYLON.serialize()
  67518. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  67519. __decorate([
  67520. BABYLON.serialize()
  67521. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  67522. __decorate([
  67523. BABYLON.serialize()
  67524. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  67525. __decorate([
  67526. BABYLON.serialize()
  67527. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  67528. __decorate([
  67529. BABYLON.serialize()
  67530. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  67531. __decorate([
  67532. BABYLON.serialize()
  67533. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  67534. return StandardRenderingPipeline;
  67535. }(BABYLON.PostProcessRenderPipeline));
  67536. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  67537. })(BABYLON || (BABYLON = {}));
  67538. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  67539. var BABYLON;
  67540. (function (BABYLON) {
  67541. var FxaaPostProcess = /** @class */ (function (_super) {
  67542. __extends(FxaaPostProcess, _super);
  67543. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  67544. if (camera === void 0) { camera = null; }
  67545. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67546. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  67547. _this.onApplyObservable.add(function (effect) {
  67548. var texelSize = _this.texelSize;
  67549. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  67550. });
  67551. return _this;
  67552. }
  67553. return FxaaPostProcess;
  67554. }(BABYLON.PostProcess));
  67555. BABYLON.FxaaPostProcess = FxaaPostProcess;
  67556. })(BABYLON || (BABYLON = {}));
  67557. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  67558. var BABYLON;
  67559. (function (BABYLON) {
  67560. /**
  67561. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  67562. */
  67563. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  67564. __extends(CircleOfConfusionPostProcess, _super);
  67565. /**
  67566. * Creates a new instance of @see CircleOfConfusionPostProcess
  67567. * @param name The name of the effect.
  67568. * @param scene The scene the effect belongs to.
  67569. * @param depthTexture The depth texture of the scene to compute the circle of confusion.
  67570. * @param options The required width/height ratio to downsize to before computing the render pass.
  67571. * @param camera The camera to apply the render pass to.
  67572. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67573. * @param engine The engine which the post process will be applied. (default: current engine)
  67574. * @param reusable If the post process can be reused on the same frame. (default: false)
  67575. * @param textureType Type of textures used when performing the post process. (default: 0)
  67576. */
  67577. function CircleOfConfusionPostProcess(name, scene, depthTexture, options, camera, samplingMode, engine, reusable, textureType) {
  67578. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67579. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType) || this;
  67580. /**
  67581. * 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.
  67582. */
  67583. _this.lensSize = 50;
  67584. /**
  67585. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  67586. */
  67587. _this.fStop = 1.4;
  67588. /**
  67589. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  67590. */
  67591. _this.focusDistance = 2000;
  67592. /**
  67593. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  67594. */
  67595. _this.focalLength = 50;
  67596. _this.onApplyObservable.add(function (effect) {
  67597. effect.setTexture("depthSampler", depthTexture);
  67598. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  67599. var aperture = _this.lensSize / _this.fStop;
  67600. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  67601. effect.setFloat('focusDistance', _this.focusDistance);
  67602. effect.setFloat('cocPrecalculation', cocPrecalculation);
  67603. if (scene.activeCamera) {
  67604. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  67605. }
  67606. });
  67607. return _this;
  67608. }
  67609. return CircleOfConfusionPostProcess;
  67610. }(BABYLON.PostProcess));
  67611. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  67612. })(BABYLON || (BABYLON = {}));
  67613. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  67614. var BABYLON;
  67615. (function (BABYLON) {
  67616. /**
  67617. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  67618. */
  67619. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  67620. __extends(DepthOfFieldMergePostProcess, _super);
  67621. /**
  67622. * Creates a new instance of @see CircleOfConfusionPostProcess
  67623. * @param name The name of the effect.
  67624. * @param original The non-blurred image to be modified
  67625. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  67626. * @param blurSteps Incrimental bluring post processes.
  67627. * @param options The required width/height ratio to downsize to before computing the render pass.
  67628. * @param camera The camera to apply the render pass to.
  67629. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  67630. * @param engine The engine which the post process will be applied. (default: current engine)
  67631. * @param reusable If the post process can be reused on the same frame. (default: false)
  67632. * @param textureType Type of textures used when performing the post process. (default: 0)
  67633. */
  67634. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType) {
  67635. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  67636. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "originalSampler", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, "#define BLUR_LEVEL " + blurSteps.length + "\n", textureType) || this;
  67637. _this.onApplyObservable.add(function (effect) {
  67638. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  67639. effect.setTextureFromPostProcess("originalSampler", original);
  67640. blurSteps.forEach(function (step, index) {
  67641. effect.setTextureFromPostProcess("blurStep" + (index + 1), step);
  67642. });
  67643. });
  67644. return _this;
  67645. }
  67646. return DepthOfFieldMergePostProcess;
  67647. }(BABYLON.PostProcess));
  67648. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  67649. })(BABYLON || (BABYLON = {}));
  67650. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  67651. var BABYLON;
  67652. (function (BABYLON) {
  67653. /**
  67654. * Specifies the level of max blur that should be applied when using the depth of field effect
  67655. */
  67656. var DepthOfFieldEffectBlurLevel;
  67657. (function (DepthOfFieldEffectBlurLevel) {
  67658. /**
  67659. * Subtle blur
  67660. */
  67661. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  67662. /**
  67663. * Medium blur
  67664. */
  67665. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  67666. /**
  67667. * Large blur
  67668. */
  67669. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  67670. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  67671. ;
  67672. /**
  67673. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  67674. */
  67675. var DepthOfFieldEffect = /** @class */ (function (_super) {
  67676. __extends(DepthOfFieldEffect, _super);
  67677. /**
  67678. * Creates a new instance of @see DepthOfFieldEffect
  67679. * @param scene The scene the effect belongs to.
  67680. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  67681. */
  67682. function DepthOfFieldEffect(scene, blurLevel, pipelineTextureType) {
  67683. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  67684. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  67685. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  67686. // Enable and get current depth map
  67687. var depthMap = scene.enableDepthRenderer().getDepthMap();
  67688. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  67689. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", scene, depthMap, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67690. // Capture circle of confusion texture
  67691. _this._depthOfFieldPass = new BABYLON.PassPostProcess("depthOfFieldPass", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67692. _this._depthOfFieldPass.autoClear = false;
  67693. // 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)
  67694. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  67695. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  67696. _this._depthOfFieldBlurY = [];
  67697. _this._depthOfFieldBlurX = [];
  67698. var blurCount = 1;
  67699. var kernelSize = 15;
  67700. switch (blurLevel) {
  67701. case DepthOfFieldEffectBlurLevel.High: {
  67702. blurCount = 3;
  67703. kernelSize = 51;
  67704. break;
  67705. }
  67706. case DepthOfFieldEffectBlurLevel.Medium: {
  67707. blurCount = 2;
  67708. kernelSize = 31;
  67709. break;
  67710. }
  67711. default: {
  67712. kernelSize = 15;
  67713. blurCount = 1;
  67714. break;
  67715. }
  67716. }
  67717. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  67718. for (var i = 0; i < blurCount; i++) {
  67719. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67720. blurY.autoClear = false;
  67721. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._depthOfFieldPass, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67722. blurX.autoClear = false;
  67723. _this._depthOfFieldBlurY.push(blurY);
  67724. _this._depthOfFieldBlurX.push(blurX);
  67725. }
  67726. // Merge blurred images with original image based on circleOfConfusion
  67727. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._depthOfFieldPass, _this._depthOfFieldBlurY.slice(1), 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType);
  67728. _this._depthOfFieldMerge.autoClear = false;
  67729. // Set all post processes on the effect.
  67730. var effects = [_this._circleOfConfusion, _this._depthOfFieldPass];
  67731. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  67732. effects.push(_this._depthOfFieldBlurY[i]);
  67733. effects.push(_this._depthOfFieldBlurX[i]);
  67734. }
  67735. effects.push(_this._depthOfFieldMerge);
  67736. return effects;
  67737. }, true) || this;
  67738. return _this;
  67739. }
  67740. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  67741. get: function () {
  67742. return this._circleOfConfusion.focalLength;
  67743. },
  67744. /**
  67745. * The focal the length of the camera used in the effect
  67746. */
  67747. set: function (value) {
  67748. this._circleOfConfusion.focalLength = value;
  67749. },
  67750. enumerable: true,
  67751. configurable: true
  67752. });
  67753. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  67754. get: function () {
  67755. return this._circleOfConfusion.fStop;
  67756. },
  67757. /**
  67758. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  67759. */
  67760. set: function (value) {
  67761. this._circleOfConfusion.fStop = value;
  67762. },
  67763. enumerable: true,
  67764. configurable: true
  67765. });
  67766. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  67767. get: function () {
  67768. return this._circleOfConfusion.focusDistance;
  67769. },
  67770. /**
  67771. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  67772. */
  67773. set: function (value) {
  67774. this._circleOfConfusion.focusDistance = value;
  67775. },
  67776. enumerable: true,
  67777. configurable: true
  67778. });
  67779. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  67780. get: function () {
  67781. return this._circleOfConfusion.lensSize;
  67782. },
  67783. /**
  67784. * 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.
  67785. */
  67786. set: function (value) {
  67787. this._circleOfConfusion.lensSize = value;
  67788. },
  67789. enumerable: true,
  67790. configurable: true
  67791. });
  67792. /**
  67793. * Disposes each of the internal effects for a given camera.
  67794. * @param camera The camera to dispose the effect on.
  67795. */
  67796. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  67797. this._depthOfFieldPass.dispose(camera);
  67798. this._circleOfConfusion.dispose(camera);
  67799. this._depthOfFieldBlurX.forEach(function (element) {
  67800. element.dispose(camera);
  67801. });
  67802. this._depthOfFieldBlurY.forEach(function (element) {
  67803. element.dispose(camera);
  67804. });
  67805. this._depthOfFieldMerge.dispose(camera);
  67806. };
  67807. return DepthOfFieldEffect;
  67808. }(BABYLON.PostProcessRenderEffect));
  67809. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  67810. })(BABYLON || (BABYLON = {}));
  67811. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  67812. var BABYLON;
  67813. (function (BABYLON) {
  67814. /**
  67815. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  67816. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  67817. */
  67818. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  67819. __extends(DefaultRenderingPipeline, _super);
  67820. /**
  67821. * @constructor
  67822. * @param {string} name - The rendering pipeline name
  67823. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67824. * @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)
  67825. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67826. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  67827. */
  67828. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  67829. if (automaticBuild === void 0) { automaticBuild = true; }
  67830. var _this = _super.call(this, scene.getEngine(), name) || this;
  67831. /**
  67832. * ID of the pass post process used for bloom,
  67833. */
  67834. _this.PassPostProcessId = "PassPostProcessEffect";
  67835. /**
  67836. * ID of the highlight post process used for bloom,
  67837. */
  67838. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  67839. /**
  67840. * ID of the blurX post process used for bloom,
  67841. */
  67842. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  67843. /**
  67844. * ID of the blurY post process used for bloom,
  67845. */
  67846. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  67847. /**
  67848. * ID of the copy back post process used for bloom,
  67849. */
  67850. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  67851. /**
  67852. * ID of the image processing post process;
  67853. */
  67854. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  67855. /**
  67856. * ID of the Fast Approximate Anti-Aliasing post process;
  67857. */
  67858. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  67859. /**
  67860. * ID of the final merge post process;
  67861. */
  67862. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  67863. /**
  67864. * Animations which can be used to tweak settings over a period of time
  67865. */
  67866. _this.animations = [];
  67867. // Values
  67868. _this._bloomEnabled = false;
  67869. _this._depthOfFieldEnabled = false;
  67870. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  67871. _this._fxaaEnabled = false;
  67872. _this._imageProcessingEnabled = true;
  67873. _this._bloomScale = 0.6;
  67874. _this._buildAllowed = true;
  67875. /**
  67876. * Specifies the size of the bloom blur kernel, relative to the final output size
  67877. */
  67878. _this.bloomKernel = 64;
  67879. /**
  67880. * Specifies the weight of the bloom in the final rendering
  67881. */
  67882. _this._bloomWeight = 0.15;
  67883. _this._cameras = cameras || [];
  67884. _this._buildAllowed = automaticBuild;
  67885. // Initialize
  67886. _this._scene = scene;
  67887. var caps = _this._scene.getEngine().getCaps();
  67888. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  67889. // Misc
  67890. if (_this._hdr) {
  67891. if (caps.textureHalfFloatRender) {
  67892. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  67893. }
  67894. else if (caps.textureFloatRender) {
  67895. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  67896. }
  67897. }
  67898. else {
  67899. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  67900. }
  67901. // Attach
  67902. scene.postProcessRenderPipelineManager.addPipeline(_this);
  67903. _this._buildPipeline();
  67904. return _this;
  67905. }
  67906. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  67907. get: function () {
  67908. return this._bloomWeight;
  67909. },
  67910. /**
  67911. * The strength of the bloom.
  67912. */
  67913. set: function (value) {
  67914. if (this._bloomWeight === value) {
  67915. return;
  67916. }
  67917. this._bloomWeight = value;
  67918. if (this._hdr && this.copyBack) {
  67919. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  67920. }
  67921. },
  67922. enumerable: true,
  67923. configurable: true
  67924. });
  67925. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  67926. get: function () {
  67927. return this._bloomScale;
  67928. },
  67929. /**
  67930. * The scale of the bloom, lower value will provide better performance.
  67931. */
  67932. set: function (value) {
  67933. if (this._bloomScale === value) {
  67934. return;
  67935. }
  67936. this._bloomScale = value;
  67937. this._buildPipeline();
  67938. },
  67939. enumerable: true,
  67940. configurable: true
  67941. });
  67942. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  67943. get: function () {
  67944. return this._bloomEnabled;
  67945. },
  67946. /**
  67947. * Enable or disable the bloom from the pipeline
  67948. */
  67949. set: function (enabled) {
  67950. if (this._bloomEnabled === enabled) {
  67951. return;
  67952. }
  67953. this._bloomEnabled = enabled;
  67954. this._buildPipeline();
  67955. },
  67956. enumerable: true,
  67957. configurable: true
  67958. });
  67959. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  67960. /**
  67961. * If the depth of field is enabled.
  67962. */
  67963. get: function () {
  67964. return this._depthOfFieldEnabled;
  67965. },
  67966. set: function (enabled) {
  67967. if (this._depthOfFieldEnabled === enabled) {
  67968. return;
  67969. }
  67970. this._depthOfFieldEnabled = enabled;
  67971. this._buildPipeline();
  67972. },
  67973. enumerable: true,
  67974. configurable: true
  67975. });
  67976. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  67977. /**
  67978. * Blur level of the depth of field effect. (Higher blur will effect performance)
  67979. */
  67980. get: function () {
  67981. return this._depthOfFieldBlurLevel;
  67982. },
  67983. set: function (value) {
  67984. if (this._depthOfFieldBlurLevel === value) {
  67985. return;
  67986. }
  67987. this._depthOfFieldBlurLevel = value;
  67988. this._buildPipeline();
  67989. },
  67990. enumerable: true,
  67991. configurable: true
  67992. });
  67993. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  67994. get: function () {
  67995. return this._fxaaEnabled;
  67996. },
  67997. /**
  67998. * If the anti aliasing is enabled.
  67999. */
  68000. set: function (enabled) {
  68001. if (this._fxaaEnabled === enabled) {
  68002. return;
  68003. }
  68004. this._fxaaEnabled = enabled;
  68005. this._buildPipeline();
  68006. },
  68007. enumerable: true,
  68008. configurable: true
  68009. });
  68010. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  68011. get: function () {
  68012. return this._imageProcessingEnabled;
  68013. },
  68014. /**
  68015. * If image processing is enabled.
  68016. */
  68017. set: function (enabled) {
  68018. if (this._imageProcessingEnabled === enabled) {
  68019. return;
  68020. }
  68021. this._imageProcessingEnabled = enabled;
  68022. this._buildPipeline();
  68023. },
  68024. enumerable: true,
  68025. configurable: true
  68026. });
  68027. /**
  68028. * Force the compilation of the entire pipeline.
  68029. */
  68030. DefaultRenderingPipeline.prototype.prepare = function () {
  68031. var previousState = this._buildAllowed;
  68032. this._buildAllowed = true;
  68033. this._buildPipeline();
  68034. this._buildAllowed = previousState;
  68035. };
  68036. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  68037. var _this = this;
  68038. if (!this._buildAllowed) {
  68039. return;
  68040. }
  68041. var engine = this._scene.getEngine();
  68042. this._disposePostProcesses();
  68043. this._reset();
  68044. if (this.depthOfFieldEnabled) {
  68045. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  68046. this.addEffect(this.depthOfField);
  68047. }
  68048. if (this.bloomEnabled) {
  68049. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68050. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  68051. if (!this._hdr) {
  68052. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68053. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  68054. this.highlights.autoClear = false;
  68055. this.highlights.alwaysForcePOT = true;
  68056. }
  68057. this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68058. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  68059. this.blurX.alwaysForcePOT = true;
  68060. this.blurX.autoClear = false;
  68061. this.blurX.onActivateObservable.add(function () {
  68062. var dw = _this.blurX.width / engine.getRenderWidth(true);
  68063. _this.blurX.kernel = _this.bloomKernel * dw;
  68064. });
  68065. this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68066. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  68067. this.blurY.alwaysForcePOT = true;
  68068. this.blurY.autoClear = false;
  68069. this.blurY.onActivateObservable.add(function () {
  68070. var dh = _this.blurY.height / engine.getRenderHeight(true);
  68071. _this.blurY.kernel = _this.bloomKernel * dh;
  68072. });
  68073. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68074. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  68075. this.copyBack.alwaysForcePOT = true;
  68076. if (this._hdr) {
  68077. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  68078. var w = this.bloomWeight;
  68079. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  68080. }
  68081. else {
  68082. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  68083. }
  68084. this.copyBack.autoClear = false;
  68085. }
  68086. if (this._imageProcessingEnabled) {
  68087. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68088. if (this._hdr) {
  68089. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  68090. }
  68091. else {
  68092. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  68093. }
  68094. }
  68095. if (this.fxaaEnabled) {
  68096. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68097. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  68098. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  68099. }
  68100. else if (this._hdr && this.imageProcessing) {
  68101. this.finalMerge = this.imageProcessing;
  68102. }
  68103. else {
  68104. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  68105. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  68106. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  68107. }
  68108. if (this.bloomEnabled) {
  68109. if (this._hdr) {
  68110. this.copyBack.shareOutputWith(this.blurX);
  68111. if (this.imageProcessing) {
  68112. this.imageProcessing.shareOutputWith(this.pass);
  68113. this.imageProcessing.autoClear = false;
  68114. }
  68115. else if (this.fxaa) {
  68116. this.fxaa.shareOutputWith(this.pass);
  68117. }
  68118. else {
  68119. this.finalMerge.shareOutputWith(this.pass);
  68120. }
  68121. }
  68122. else {
  68123. if (this.fxaa) {
  68124. this.fxaa.shareOutputWith(this.pass);
  68125. }
  68126. else {
  68127. this.finalMerge.shareOutputWith(this.pass);
  68128. }
  68129. }
  68130. }
  68131. if (this._cameras !== null) {
  68132. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68133. }
  68134. };
  68135. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  68136. for (var i = 0; i < this._cameras.length; i++) {
  68137. var camera = this._cameras[i];
  68138. if (this.pass) {
  68139. this.pass.dispose(camera);
  68140. }
  68141. if (this.highlights) {
  68142. this.highlights.dispose(camera);
  68143. }
  68144. if (this.blurX) {
  68145. this.blurX.dispose(camera);
  68146. }
  68147. if (this.blurY) {
  68148. this.blurY.dispose(camera);
  68149. }
  68150. if (this.copyBack) {
  68151. this.copyBack.dispose(camera);
  68152. }
  68153. if (this.imageProcessing) {
  68154. this.imageProcessing.dispose(camera);
  68155. }
  68156. if (this.fxaa) {
  68157. this.fxaa.dispose(camera);
  68158. }
  68159. if (this.finalMerge) {
  68160. this.finalMerge.dispose(camera);
  68161. }
  68162. if (this.depthOfField) {
  68163. this.depthOfField.disposeEffects(camera);
  68164. }
  68165. }
  68166. this.pass = null;
  68167. this.highlights = null;
  68168. this.blurX = null;
  68169. this.blurY = null;
  68170. this.copyBack = null;
  68171. this.imageProcessing = null;
  68172. this.fxaa = null;
  68173. this.finalMerge = null;
  68174. this.depthOfField = null;
  68175. };
  68176. /**
  68177. * Dispose of the pipeline and stop all post processes
  68178. */
  68179. DefaultRenderingPipeline.prototype.dispose = function () {
  68180. this._disposePostProcesses();
  68181. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  68182. _super.prototype.dispose.call(this);
  68183. };
  68184. /**
  68185. * Serialize the rendering pipeline (Used when exporting)
  68186. * @returns the serialized object
  68187. */
  68188. DefaultRenderingPipeline.prototype.serialize = function () {
  68189. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  68190. serializationObject.customType = "DefaultRenderingPipeline";
  68191. return serializationObject;
  68192. };
  68193. /**
  68194. * Parse the serialized pipeline
  68195. * @param source Source pipeline.
  68196. * @param scene The scene to load the pipeline to.
  68197. * @param rootUrl The URL of the serialized pipeline.
  68198. * @returns An instantiated pipeline from the serialized object.
  68199. */
  68200. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  68201. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  68202. };
  68203. __decorate([
  68204. BABYLON.serialize()
  68205. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  68206. __decorate([
  68207. BABYLON.serialize()
  68208. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  68209. __decorate([
  68210. BABYLON.serialize()
  68211. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  68212. __decorate([
  68213. BABYLON.serialize()
  68214. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  68215. __decorate([
  68216. BABYLON.serialize()
  68217. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  68218. __decorate([
  68219. BABYLON.serialize()
  68220. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  68221. __decorate([
  68222. BABYLON.serialize()
  68223. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  68224. __decorate([
  68225. BABYLON.serialize()
  68226. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  68227. __decorate([
  68228. BABYLON.serialize()
  68229. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  68230. __decorate([
  68231. BABYLON.serialize()
  68232. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  68233. return DefaultRenderingPipeline;
  68234. }(BABYLON.PostProcessRenderPipeline));
  68235. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  68236. })(BABYLON || (BABYLON = {}));
  68237. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  68238. var BABYLON;
  68239. (function (BABYLON) {
  68240. /**
  68241. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  68242. */
  68243. var GeometryBufferRenderer = /** @class */ (function () {
  68244. /**
  68245. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  68246. * @param scene The scene the buffer belongs to
  68247. * @param ratio How big is the buffer related to the main canvas.
  68248. */
  68249. function GeometryBufferRenderer(scene, ratio) {
  68250. if (ratio === void 0) { ratio = 1; }
  68251. this._enablePosition = false;
  68252. this._scene = scene;
  68253. this._ratio = ratio;
  68254. // Render target
  68255. this._createRenderTargets();
  68256. }
  68257. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  68258. /**
  68259. * Set the render list (meshes to be rendered) used in the G buffer.
  68260. */
  68261. set: function (meshes) {
  68262. this._multiRenderTarget.renderList = meshes;
  68263. },
  68264. enumerable: true,
  68265. configurable: true
  68266. });
  68267. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  68268. /**
  68269. * Gets wether or not G buffer are supported by the running hardware.
  68270. * This requires draw buffer supports
  68271. */
  68272. get: function () {
  68273. return this._multiRenderTarget.isSupported;
  68274. },
  68275. enumerable: true,
  68276. configurable: true
  68277. });
  68278. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  68279. /**
  68280. * Gets wether or not position are enabled for the G buffer.
  68281. */
  68282. get: function () {
  68283. return this._enablePosition;
  68284. },
  68285. /**
  68286. * Sets wether or not position are enabled for the G buffer.
  68287. */
  68288. set: function (enable) {
  68289. this._enablePosition = enable;
  68290. this.dispose();
  68291. this._createRenderTargets();
  68292. },
  68293. enumerable: true,
  68294. configurable: true
  68295. });
  68296. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  68297. /**
  68298. * Gets the scene associated with the buffer.
  68299. */
  68300. get: function () {
  68301. return this._scene;
  68302. },
  68303. enumerable: true,
  68304. configurable: true
  68305. });
  68306. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  68307. /**
  68308. * Gets the ratio used by the buffer during its creation.
  68309. * How big is the buffer related to the main canvas.
  68310. */
  68311. get: function () {
  68312. return this._ratio;
  68313. },
  68314. enumerable: true,
  68315. configurable: true
  68316. });
  68317. /**
  68318. * Checks wether everything is ready to render a submesh to the G buffer.
  68319. * @param subMesh the submesh to check readiness for
  68320. * @param useInstances is the mesh drawn using instance or not
  68321. * @returns true if ready otherwise false
  68322. */
  68323. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  68324. var material = subMesh.getMaterial();
  68325. if (material && material.disableDepthWrite) {
  68326. return false;
  68327. }
  68328. var defines = [];
  68329. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  68330. var mesh = subMesh.getMesh();
  68331. // Alpha test
  68332. if (material && material.needAlphaTesting()) {
  68333. defines.push("#define ALPHATEST");
  68334. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68335. attribs.push(BABYLON.VertexBuffer.UVKind);
  68336. defines.push("#define UV1");
  68337. }
  68338. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68339. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68340. defines.push("#define UV2");
  68341. }
  68342. }
  68343. // Buffers
  68344. if (this._enablePosition) {
  68345. defines.push("#define POSITION");
  68346. }
  68347. // Bones
  68348. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68349. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68350. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68351. if (mesh.numBoneInfluencers > 4) {
  68352. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  68353. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  68354. }
  68355. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68356. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  68357. }
  68358. else {
  68359. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68360. }
  68361. // Instances
  68362. if (useInstances) {
  68363. defines.push("#define INSTANCES");
  68364. attribs.push("world0");
  68365. attribs.push("world1");
  68366. attribs.push("world2");
  68367. attribs.push("world3");
  68368. }
  68369. // Get correct effect
  68370. var join = defines.join("\n");
  68371. if (this._cachedDefines !== join) {
  68372. this._cachedDefines = join;
  68373. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  68374. }
  68375. return this._effect.isReady();
  68376. };
  68377. /**
  68378. * Gets the current underlying G Buffer.
  68379. * @returns the buffer
  68380. */
  68381. GeometryBufferRenderer.prototype.getGBuffer = function () {
  68382. return this._multiRenderTarget;
  68383. };
  68384. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  68385. /**
  68386. * Gets the number of samples used to render the buffer (anti aliasing).
  68387. */
  68388. get: function () {
  68389. return this._multiRenderTarget.samples;
  68390. },
  68391. /**
  68392. * Sets the number of samples used to render the buffer (anti aliasing).
  68393. */
  68394. set: function (value) {
  68395. this._multiRenderTarget.samples = value;
  68396. },
  68397. enumerable: true,
  68398. configurable: true
  68399. });
  68400. /**
  68401. * Disposes the renderer and frees up associated resources.
  68402. */
  68403. GeometryBufferRenderer.prototype.dispose = function () {
  68404. this.getGBuffer().dispose();
  68405. };
  68406. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  68407. var _this = this;
  68408. var engine = this._scene.getEngine();
  68409. var count = this._enablePosition ? 3 : 2;
  68410. 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 });
  68411. if (!this.isSupported) {
  68412. return;
  68413. }
  68414. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68415. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68416. this._multiRenderTarget.refreshRate = 1;
  68417. this._multiRenderTarget.renderParticles = false;
  68418. this._multiRenderTarget.renderList = null;
  68419. // set default depth value to 1.0 (far away)
  68420. this._multiRenderTarget.onClearObservable.add(function (engine) {
  68421. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  68422. });
  68423. // Custom render function
  68424. var renderSubMesh = function (subMesh) {
  68425. var mesh = subMesh.getRenderingMesh();
  68426. var scene = _this._scene;
  68427. var engine = scene.getEngine();
  68428. var material = subMesh.getMaterial();
  68429. if (!material) {
  68430. return;
  68431. }
  68432. // Culling
  68433. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  68434. // Managing instances
  68435. var batch = mesh._getInstancesRenderList(subMesh._id);
  68436. if (batch.mustReturn) {
  68437. return;
  68438. }
  68439. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68440. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  68441. engine.enableEffect(_this._effect);
  68442. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  68443. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  68444. _this._effect.setMatrix("view", scene.getViewMatrix());
  68445. // Alpha test
  68446. if (material && material.needAlphaTesting()) {
  68447. var alphaTexture = material.getAlphaTestTexture();
  68448. if (alphaTexture) {
  68449. _this._effect.setTexture("diffuseSampler", alphaTexture);
  68450. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68451. }
  68452. }
  68453. // Bones
  68454. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68455. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68456. }
  68457. // Draw
  68458. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  68459. }
  68460. };
  68461. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68462. var index;
  68463. if (depthOnlySubMeshes.length) {
  68464. engine.setColorWrite(false);
  68465. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68466. renderSubMesh(depthOnlySubMeshes.data[index]);
  68467. }
  68468. engine.setColorWrite(true);
  68469. }
  68470. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68471. renderSubMesh(opaqueSubMeshes.data[index]);
  68472. }
  68473. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68474. renderSubMesh(alphaTestSubMeshes.data[index]);
  68475. }
  68476. };
  68477. };
  68478. return GeometryBufferRenderer;
  68479. }());
  68480. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  68481. })(BABYLON || (BABYLON = {}));
  68482. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  68483. var BABYLON;
  68484. (function (BABYLON) {
  68485. var RefractionPostProcess = /** @class */ (function (_super) {
  68486. __extends(RefractionPostProcess, _super);
  68487. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  68488. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  68489. _this.color = color;
  68490. _this.depth = depth;
  68491. _this.colorLevel = colorLevel;
  68492. _this._ownRefractionTexture = true;
  68493. _this.onActivateObservable.add(function (cam) {
  68494. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  68495. });
  68496. _this.onApplyObservable.add(function (effect) {
  68497. effect.setColor3("baseColor", _this.color);
  68498. effect.setFloat("depth", _this.depth);
  68499. effect.setFloat("colorLevel", _this.colorLevel);
  68500. effect.setTexture("refractionSampler", _this._refTexture);
  68501. });
  68502. return _this;
  68503. }
  68504. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  68505. /**
  68506. * Gets or sets the refraction texture
  68507. * Please note that you are responsible for disposing the texture if you set it manually
  68508. */
  68509. get: function () {
  68510. return this._refTexture;
  68511. },
  68512. set: function (value) {
  68513. if (this._refTexture && this._ownRefractionTexture) {
  68514. this._refTexture.dispose();
  68515. }
  68516. this._refTexture = value;
  68517. this._ownRefractionTexture = false;
  68518. },
  68519. enumerable: true,
  68520. configurable: true
  68521. });
  68522. // Methods
  68523. RefractionPostProcess.prototype.dispose = function (camera) {
  68524. if (this._refTexture && this._ownRefractionTexture) {
  68525. this._refTexture.dispose();
  68526. this._refTexture = null;
  68527. }
  68528. _super.prototype.dispose.call(this, camera);
  68529. };
  68530. return RefractionPostProcess;
  68531. }(BABYLON.PostProcess));
  68532. BABYLON.RefractionPostProcess = RefractionPostProcess;
  68533. })(BABYLON || (BABYLON = {}));
  68534. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  68535. var BABYLON;
  68536. (function (BABYLON) {
  68537. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  68538. __extends(BlackAndWhitePostProcess, _super);
  68539. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  68540. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  68541. _this.degree = 1;
  68542. _this.onApplyObservable.add(function (effect) {
  68543. effect.setFloat("degree", _this.degree);
  68544. });
  68545. return _this;
  68546. }
  68547. return BlackAndWhitePostProcess;
  68548. }(BABYLON.PostProcess));
  68549. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  68550. })(BABYLON || (BABYLON = {}));
  68551. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  68552. var BABYLON;
  68553. (function (BABYLON) {
  68554. var ConvolutionPostProcess = /** @class */ (function (_super) {
  68555. __extends(ConvolutionPostProcess, _super);
  68556. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  68557. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  68558. _this.kernel = kernel;
  68559. _this.onApply = function (effect) {
  68560. effect.setFloat2("screenSize", _this.width, _this.height);
  68561. effect.setArray("kernel", _this.kernel);
  68562. };
  68563. return _this;
  68564. }
  68565. // Statics
  68566. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  68567. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  68568. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  68569. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  68570. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  68571. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  68572. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  68573. return ConvolutionPostProcess;
  68574. }(BABYLON.PostProcess));
  68575. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  68576. })(BABYLON || (BABYLON = {}));
  68577. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  68578. var BABYLON;
  68579. (function (BABYLON) {
  68580. var FilterPostProcess = /** @class */ (function (_super) {
  68581. __extends(FilterPostProcess, _super);
  68582. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  68583. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  68584. _this.kernelMatrix = kernelMatrix;
  68585. _this.onApply = function (effect) {
  68586. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  68587. };
  68588. return _this;
  68589. }
  68590. return FilterPostProcess;
  68591. }(BABYLON.PostProcess));
  68592. BABYLON.FilterPostProcess = FilterPostProcess;
  68593. })(BABYLON || (BABYLON = {}));
  68594. //# sourceMappingURL=babylon.filterPostProcess.js.map
  68595. var BABYLON;
  68596. (function (BABYLON) {
  68597. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  68598. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  68599. __extends(VolumetricLightScatteringPostProcess, _super);
  68600. /**
  68601. * @constructor
  68602. * @param {string} name - The post-process name
  68603. * @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)
  68604. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  68605. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  68606. * @param {number} samples - The post-process quality, default 100
  68607. * @param {number} samplingMode - The post-process filtering mode
  68608. * @param {BABYLON.Engine} engine - The babylon engine
  68609. * @param {boolean} reusable - If the post-process is reusable
  68610. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  68611. */
  68612. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  68613. if (samples === void 0) { samples = 100; }
  68614. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  68615. 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;
  68616. _this._screenCoordinates = BABYLON.Vector2.Zero();
  68617. /**
  68618. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  68619. * @type {Vector3}
  68620. */
  68621. _this.customMeshPosition = BABYLON.Vector3.Zero();
  68622. /**
  68623. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  68624. * @type {boolean}
  68625. */
  68626. _this.useCustomMeshPosition = false;
  68627. /**
  68628. * If the post-process should inverse the light scattering direction
  68629. * @type {boolean}
  68630. */
  68631. _this.invert = true;
  68632. /**
  68633. * Array containing the excluded meshes not rendered in the internal pass
  68634. */
  68635. _this.excludedMeshes = new Array();
  68636. /**
  68637. * Controls the overall intensity of the post-process
  68638. * @type {number}
  68639. */
  68640. _this.exposure = 0.3;
  68641. /**
  68642. * Dissipates each sample's contribution in range [0, 1]
  68643. * @type {number}
  68644. */
  68645. _this.decay = 0.96815;
  68646. /**
  68647. * Controls the overall intensity of each sample
  68648. * @type {number}
  68649. */
  68650. _this.weight = 0.58767;
  68651. /**
  68652. * Controls the density of each sample
  68653. * @type {number}
  68654. */
  68655. _this.density = 0.926;
  68656. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  68657. engine = scene.getEngine();
  68658. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  68659. // Configure mesh
  68660. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  68661. // Configure
  68662. _this._createPass(scene, ratio.passRatio || ratio);
  68663. _this.onActivate = function (camera) {
  68664. if (!_this.isSupported) {
  68665. _this.dispose(camera);
  68666. }
  68667. _this.onActivate = null;
  68668. };
  68669. _this.onApplyObservable.add(function (effect) {
  68670. _this._updateMeshScreenCoordinates(scene);
  68671. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  68672. effect.setFloat("exposure", _this.exposure);
  68673. effect.setFloat("decay", _this.decay);
  68674. effect.setFloat("weight", _this.weight);
  68675. effect.setFloat("density", _this.density);
  68676. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  68677. });
  68678. return _this;
  68679. }
  68680. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  68681. get: function () {
  68682. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  68683. return false;
  68684. },
  68685. set: function (useDiffuseColor) {
  68686. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  68687. },
  68688. enumerable: true,
  68689. configurable: true
  68690. });
  68691. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  68692. return "VolumetricLightScatteringPostProcess";
  68693. };
  68694. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  68695. var mesh = subMesh.getMesh();
  68696. // Render this.mesh as default
  68697. if (mesh === this.mesh && mesh.material) {
  68698. return mesh.material.isReady(mesh);
  68699. }
  68700. var defines = [];
  68701. var attribs = [BABYLON.VertexBuffer.PositionKind];
  68702. var material = subMesh.getMaterial();
  68703. // Alpha test
  68704. if (material) {
  68705. if (material.needAlphaTesting()) {
  68706. defines.push("#define ALPHATEST");
  68707. }
  68708. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  68709. attribs.push(BABYLON.VertexBuffer.UVKind);
  68710. defines.push("#define UV1");
  68711. }
  68712. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  68713. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  68714. defines.push("#define UV2");
  68715. }
  68716. }
  68717. // Bones
  68718. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  68719. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  68720. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  68721. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  68722. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  68723. }
  68724. else {
  68725. defines.push("#define NUM_BONE_INFLUENCERS 0");
  68726. }
  68727. // Instances
  68728. if (useInstances) {
  68729. defines.push("#define INSTANCES");
  68730. attribs.push("world0");
  68731. attribs.push("world1");
  68732. attribs.push("world2");
  68733. attribs.push("world3");
  68734. }
  68735. // Get correct effect
  68736. var join = defines.join("\n");
  68737. if (this._cachedDefines !== join) {
  68738. this._cachedDefines = join;
  68739. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  68740. }
  68741. return this._volumetricLightScatteringPass.isReady();
  68742. };
  68743. /**
  68744. * Sets the new light position for light scattering effect
  68745. * @param {BABYLON.Vector3} The new custom light position
  68746. */
  68747. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  68748. this.customMeshPosition = position;
  68749. };
  68750. /**
  68751. * Returns the light position for light scattering effect
  68752. * @return {BABYLON.Vector3} The custom light position
  68753. */
  68754. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  68755. return this.customMeshPosition;
  68756. };
  68757. /**
  68758. * Disposes the internal assets and detaches the post-process from the camera
  68759. */
  68760. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  68761. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  68762. if (rttIndex !== -1) {
  68763. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  68764. }
  68765. this._volumetricLightScatteringRTT.dispose();
  68766. _super.prototype.dispose.call(this, camera);
  68767. };
  68768. /**
  68769. * Returns the render target texture used by the post-process
  68770. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  68771. */
  68772. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  68773. return this._volumetricLightScatteringRTT;
  68774. };
  68775. // Private methods
  68776. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  68777. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  68778. return true;
  68779. }
  68780. return false;
  68781. };
  68782. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  68783. var _this = this;
  68784. var engine = scene.getEngine();
  68785. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  68786. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68787. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68788. this._volumetricLightScatteringRTT.renderList = null;
  68789. this._volumetricLightScatteringRTT.renderParticles = false;
  68790. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  68791. var camera = this.getCamera();
  68792. if (camera) {
  68793. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  68794. }
  68795. else {
  68796. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  68797. }
  68798. // Custom render function for submeshes
  68799. var renderSubMesh = function (subMesh) {
  68800. var mesh = subMesh.getRenderingMesh();
  68801. if (_this._meshExcluded(mesh)) {
  68802. return;
  68803. }
  68804. var material = subMesh.getMaterial();
  68805. if (!material) {
  68806. return;
  68807. }
  68808. var scene = mesh.getScene();
  68809. var engine = scene.getEngine();
  68810. // Culling
  68811. engine.setState(material.backFaceCulling);
  68812. // Managing instances
  68813. var batch = mesh._getInstancesRenderList(subMesh._id);
  68814. if (batch.mustReturn) {
  68815. return;
  68816. }
  68817. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  68818. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  68819. var effect = _this._volumetricLightScatteringPass;
  68820. if (mesh === _this.mesh) {
  68821. if (subMesh.effect) {
  68822. effect = subMesh.effect;
  68823. }
  68824. else {
  68825. effect = material.getEffect();
  68826. }
  68827. }
  68828. engine.enableEffect(effect);
  68829. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  68830. if (mesh === _this.mesh) {
  68831. material.bind(mesh.getWorldMatrix(), mesh);
  68832. }
  68833. else {
  68834. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  68835. // Alpha test
  68836. if (material && material.needAlphaTesting()) {
  68837. var alphaTexture = material.getAlphaTestTexture();
  68838. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  68839. if (alphaTexture) {
  68840. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  68841. }
  68842. }
  68843. // Bones
  68844. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  68845. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  68846. }
  68847. }
  68848. // Draw
  68849. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  68850. }
  68851. };
  68852. // Render target texture callbacks
  68853. var savedSceneClearColor;
  68854. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  68855. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  68856. savedSceneClearColor = scene.clearColor;
  68857. scene.clearColor = sceneClearColor;
  68858. });
  68859. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  68860. scene.clearColor = savedSceneClearColor;
  68861. });
  68862. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  68863. var engine = scene.getEngine();
  68864. var index;
  68865. if (depthOnlySubMeshes.length) {
  68866. engine.setColorWrite(false);
  68867. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  68868. renderSubMesh(depthOnlySubMeshes.data[index]);
  68869. }
  68870. engine.setColorWrite(true);
  68871. }
  68872. for (index = 0; index < opaqueSubMeshes.length; index++) {
  68873. renderSubMesh(opaqueSubMeshes.data[index]);
  68874. }
  68875. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  68876. renderSubMesh(alphaTestSubMeshes.data[index]);
  68877. }
  68878. if (transparentSubMeshes.length) {
  68879. // Sort sub meshes
  68880. for (index = 0; index < transparentSubMeshes.length; index++) {
  68881. var submesh = transparentSubMeshes.data[index];
  68882. var boundingInfo = submesh.getBoundingInfo();
  68883. if (boundingInfo && scene.activeCamera) {
  68884. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  68885. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  68886. }
  68887. }
  68888. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  68889. sortedArray.sort(function (a, b) {
  68890. // Alpha index first
  68891. if (a._alphaIndex > b._alphaIndex) {
  68892. return 1;
  68893. }
  68894. if (a._alphaIndex < b._alphaIndex) {
  68895. return -1;
  68896. }
  68897. // Then distance to camera
  68898. if (a._distanceToCamera < b._distanceToCamera) {
  68899. return 1;
  68900. }
  68901. if (a._distanceToCamera > b._distanceToCamera) {
  68902. return -1;
  68903. }
  68904. return 0;
  68905. });
  68906. // Render sub meshes
  68907. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  68908. for (index = 0; index < sortedArray.length; index++) {
  68909. renderSubMesh(sortedArray[index]);
  68910. }
  68911. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  68912. }
  68913. };
  68914. };
  68915. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  68916. var transform = scene.getTransformMatrix();
  68917. var meshPosition;
  68918. if (this.useCustomMeshPosition) {
  68919. meshPosition = this.customMeshPosition;
  68920. }
  68921. else if (this.attachedNode) {
  68922. meshPosition = this.attachedNode.position;
  68923. }
  68924. else {
  68925. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  68926. }
  68927. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  68928. this._screenCoordinates.x = pos.x / this._viewPort.width;
  68929. this._screenCoordinates.y = pos.y / this._viewPort.height;
  68930. if (this.invert)
  68931. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  68932. };
  68933. // Static methods
  68934. /**
  68935. * Creates a default mesh for the Volumeric Light Scattering post-process
  68936. * @param {string} The mesh name
  68937. * @param {BABYLON.Scene} The scene where to create the mesh
  68938. * @return {BABYLON.Mesh} the default mesh
  68939. */
  68940. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  68941. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  68942. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  68943. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  68944. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  68945. mesh.material = material;
  68946. return mesh;
  68947. };
  68948. __decorate([
  68949. BABYLON.serializeAsVector3()
  68950. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  68951. __decorate([
  68952. BABYLON.serialize()
  68953. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  68954. __decorate([
  68955. BABYLON.serialize()
  68956. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  68957. __decorate([
  68958. BABYLON.serializeAsMeshReference()
  68959. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  68960. __decorate([
  68961. BABYLON.serialize()
  68962. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  68963. __decorate([
  68964. BABYLON.serialize()
  68965. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  68966. __decorate([
  68967. BABYLON.serialize()
  68968. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  68969. __decorate([
  68970. BABYLON.serialize()
  68971. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  68972. __decorate([
  68973. BABYLON.serialize()
  68974. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  68975. return VolumetricLightScatteringPostProcess;
  68976. }(BABYLON.PostProcess));
  68977. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  68978. })(BABYLON || (BABYLON = {}));
  68979. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  68980. //
  68981. // This post-process allows the modification of rendered colors by using
  68982. // a 'look-up table' (LUT). This effect is also called Color Grading.
  68983. //
  68984. // The object needs to be provided an url to a texture containing the color
  68985. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  68986. // Use an image editing software to tweak the LUT to match your needs.
  68987. //
  68988. // For an example of a color LUT, see here:
  68989. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  68990. // For explanations on color grading, see here:
  68991. // http://udn.epicgames.com/Three/ColorGrading.html
  68992. //
  68993. var BABYLON;
  68994. (function (BABYLON) {
  68995. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  68996. __extends(ColorCorrectionPostProcess, _super);
  68997. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  68998. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  68999. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  69000. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  69001. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69002. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69003. _this.onApply = function (effect) {
  69004. effect.setTexture("colorTable", _this._colorTableTexture);
  69005. };
  69006. return _this;
  69007. }
  69008. return ColorCorrectionPostProcess;
  69009. }(BABYLON.PostProcess));
  69010. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  69011. })(BABYLON || (BABYLON = {}));
  69012. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  69013. var BABYLON;
  69014. (function (BABYLON) {
  69015. var TonemappingOperator;
  69016. (function (TonemappingOperator) {
  69017. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  69018. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  69019. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  69020. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  69021. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  69022. ;
  69023. var TonemapPostProcess = /** @class */ (function (_super) {
  69024. __extends(TonemapPostProcess, _super);
  69025. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  69026. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69027. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69028. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  69029. _this._operator = _operator;
  69030. _this.exposureAdjustment = exposureAdjustment;
  69031. var defines = "#define ";
  69032. if (_this._operator === TonemappingOperator.Hable)
  69033. defines += "HABLE_TONEMAPPING";
  69034. else if (_this._operator === TonemappingOperator.Reinhard)
  69035. defines += "REINHARD_TONEMAPPING";
  69036. else if (_this._operator === TonemappingOperator.HejiDawson)
  69037. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  69038. else if (_this._operator === TonemappingOperator.Photographic)
  69039. defines += "PHOTOGRAPHIC_TONEMAPPING";
  69040. //sadly a second call to create the effect.
  69041. _this.updateEffect(defines);
  69042. _this.onApply = function (effect) {
  69043. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  69044. };
  69045. return _this;
  69046. }
  69047. return TonemapPostProcess;
  69048. }(BABYLON.PostProcess));
  69049. BABYLON.TonemapPostProcess = TonemapPostProcess;
  69050. })(BABYLON || (BABYLON = {}));
  69051. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  69052. var BABYLON;
  69053. (function (BABYLON) {
  69054. var DisplayPassPostProcess = /** @class */ (function (_super) {
  69055. __extends(DisplayPassPostProcess, _super);
  69056. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  69057. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  69058. }
  69059. return DisplayPassPostProcess;
  69060. }(BABYLON.PostProcess));
  69061. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  69062. })(BABYLON || (BABYLON = {}));
  69063. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  69064. var BABYLON;
  69065. (function (BABYLON) {
  69066. var HighlightsPostProcess = /** @class */ (function (_super) {
  69067. __extends(HighlightsPostProcess, _super);
  69068. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69069. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69070. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  69071. }
  69072. return HighlightsPostProcess;
  69073. }(BABYLON.PostProcess));
  69074. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  69075. })(BABYLON || (BABYLON = {}));
  69076. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  69077. var BABYLON;
  69078. (function (BABYLON) {
  69079. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  69080. __extends(ImageProcessingPostProcess, _super);
  69081. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  69082. if (camera === void 0) { camera = null; }
  69083. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69084. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  69085. _this._fromLinearSpace = true;
  69086. /**
  69087. * Defines cache preventing GC.
  69088. */
  69089. _this._defines = {
  69090. IMAGEPROCESSING: false,
  69091. VIGNETTE: false,
  69092. VIGNETTEBLENDMODEMULTIPLY: false,
  69093. VIGNETTEBLENDMODEOPAQUE: false,
  69094. TONEMAPPING: false,
  69095. CONTRAST: false,
  69096. COLORCURVES: false,
  69097. COLORGRADING: false,
  69098. COLORGRADING3D: false,
  69099. FROMLINEARSPACE: false,
  69100. SAMPLER3DGREENDEPTH: false,
  69101. SAMPLER3DBGRMAP: false,
  69102. IMAGEPROCESSINGPOSTPROCESS: false,
  69103. EXPOSURE: false,
  69104. };
  69105. // Setup the configuration as forced by the constructor. This would then not force the
  69106. // scene materials output in linear space and let untouched the default forward pass.
  69107. if (imageProcessingConfiguration) {
  69108. imageProcessingConfiguration.applyByPostProcess = true;
  69109. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  69110. // This will cause the shader to be compiled
  69111. _this.fromLinearSpace = false;
  69112. }
  69113. else {
  69114. _this._attachImageProcessingConfiguration(null, true);
  69115. _this.imageProcessingConfiguration.applyByPostProcess = true;
  69116. }
  69117. _this.onApply = function (effect) {
  69118. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  69119. };
  69120. return _this;
  69121. }
  69122. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  69123. /**
  69124. * Gets the image processing configuration used either in this material.
  69125. */
  69126. get: function () {
  69127. return this._imageProcessingConfiguration;
  69128. },
  69129. /**
  69130. * Sets the Default image processing configuration used either in the this material.
  69131. *
  69132. * If sets to null, the scene one is in use.
  69133. */
  69134. set: function (value) {
  69135. this._attachImageProcessingConfiguration(value);
  69136. },
  69137. enumerable: true,
  69138. configurable: true
  69139. });
  69140. /**
  69141. * Attaches a new image processing configuration to the PBR Material.
  69142. * @param configuration
  69143. */
  69144. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  69145. var _this = this;
  69146. if (doNotBuild === void 0) { doNotBuild = false; }
  69147. if (configuration === this._imageProcessingConfiguration) {
  69148. return;
  69149. }
  69150. // Detaches observer.
  69151. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  69152. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  69153. }
  69154. // Pick the scene configuration if needed.
  69155. if (!configuration) {
  69156. var scene = null;
  69157. var engine = this.getEngine();
  69158. var camera = this.getCamera();
  69159. if (camera) {
  69160. scene = camera.getScene();
  69161. }
  69162. else if (engine && engine.scenes) {
  69163. var scenes = engine.scenes;
  69164. scene = scenes[scenes.length - 1];
  69165. }
  69166. else {
  69167. scene = BABYLON.Engine.LastCreatedScene;
  69168. }
  69169. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  69170. }
  69171. else {
  69172. this._imageProcessingConfiguration = configuration;
  69173. }
  69174. // Attaches observer.
  69175. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  69176. _this._updateParameters();
  69177. });
  69178. // Ensure the effect will be rebuilt.
  69179. if (!doNotBuild) {
  69180. this._updateParameters();
  69181. }
  69182. };
  69183. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  69184. /**
  69185. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69186. */
  69187. get: function () {
  69188. return this.imageProcessingConfiguration.colorCurves;
  69189. },
  69190. /**
  69191. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  69192. */
  69193. set: function (value) {
  69194. this.imageProcessingConfiguration.colorCurves = value;
  69195. },
  69196. enumerable: true,
  69197. configurable: true
  69198. });
  69199. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  69200. /**
  69201. * Gets wether the color curves effect is enabled.
  69202. */
  69203. get: function () {
  69204. return this.imageProcessingConfiguration.colorCurvesEnabled;
  69205. },
  69206. /**
  69207. * Sets wether the color curves effect is enabled.
  69208. */
  69209. set: function (value) {
  69210. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  69211. },
  69212. enumerable: true,
  69213. configurable: true
  69214. });
  69215. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  69216. /**
  69217. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69218. */
  69219. get: function () {
  69220. return this.imageProcessingConfiguration.colorGradingTexture;
  69221. },
  69222. /**
  69223. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  69224. */
  69225. set: function (value) {
  69226. this.imageProcessingConfiguration.colorGradingTexture = value;
  69227. },
  69228. enumerable: true,
  69229. configurable: true
  69230. });
  69231. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  69232. /**
  69233. * Gets wether the color grading effect is enabled.
  69234. */
  69235. get: function () {
  69236. return this.imageProcessingConfiguration.colorGradingEnabled;
  69237. },
  69238. /**
  69239. * Gets wether the color grading effect is enabled.
  69240. */
  69241. set: function (value) {
  69242. this.imageProcessingConfiguration.colorGradingEnabled = value;
  69243. },
  69244. enumerable: true,
  69245. configurable: true
  69246. });
  69247. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  69248. /**
  69249. * Gets exposure used in the effect.
  69250. */
  69251. get: function () {
  69252. return this.imageProcessingConfiguration.exposure;
  69253. },
  69254. /**
  69255. * Sets exposure used in the effect.
  69256. */
  69257. set: function (value) {
  69258. this.imageProcessingConfiguration.exposure = value;
  69259. },
  69260. enumerable: true,
  69261. configurable: true
  69262. });
  69263. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  69264. /**
  69265. * Gets wether tonemapping is enabled or not.
  69266. */
  69267. get: function () {
  69268. return this._imageProcessingConfiguration.toneMappingEnabled;
  69269. },
  69270. /**
  69271. * Sets wether tonemapping is enabled or not
  69272. */
  69273. set: function (value) {
  69274. this._imageProcessingConfiguration.toneMappingEnabled = value;
  69275. },
  69276. enumerable: true,
  69277. configurable: true
  69278. });
  69279. ;
  69280. ;
  69281. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  69282. /**
  69283. * Gets contrast used in the effect.
  69284. */
  69285. get: function () {
  69286. return this.imageProcessingConfiguration.contrast;
  69287. },
  69288. /**
  69289. * Sets contrast used in the effect.
  69290. */
  69291. set: function (value) {
  69292. this.imageProcessingConfiguration.contrast = value;
  69293. },
  69294. enumerable: true,
  69295. configurable: true
  69296. });
  69297. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  69298. /**
  69299. * Gets Vignette stretch size.
  69300. */
  69301. get: function () {
  69302. return this.imageProcessingConfiguration.vignetteStretch;
  69303. },
  69304. /**
  69305. * Sets Vignette stretch size.
  69306. */
  69307. set: function (value) {
  69308. this.imageProcessingConfiguration.vignetteStretch = value;
  69309. },
  69310. enumerable: true,
  69311. configurable: true
  69312. });
  69313. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  69314. /**
  69315. * Gets Vignette centre X Offset.
  69316. */
  69317. get: function () {
  69318. return this.imageProcessingConfiguration.vignetteCentreX;
  69319. },
  69320. /**
  69321. * Sets Vignette centre X Offset.
  69322. */
  69323. set: function (value) {
  69324. this.imageProcessingConfiguration.vignetteCentreX = value;
  69325. },
  69326. enumerable: true,
  69327. configurable: true
  69328. });
  69329. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  69330. /**
  69331. * Gets Vignette centre Y Offset.
  69332. */
  69333. get: function () {
  69334. return this.imageProcessingConfiguration.vignetteCentreY;
  69335. },
  69336. /**
  69337. * Sets Vignette centre Y Offset.
  69338. */
  69339. set: function (value) {
  69340. this.imageProcessingConfiguration.vignetteCentreY = value;
  69341. },
  69342. enumerable: true,
  69343. configurable: true
  69344. });
  69345. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  69346. /**
  69347. * Gets Vignette weight or intensity of the vignette effect.
  69348. */
  69349. get: function () {
  69350. return this.imageProcessingConfiguration.vignetteWeight;
  69351. },
  69352. /**
  69353. * Sets Vignette weight or intensity of the vignette effect.
  69354. */
  69355. set: function (value) {
  69356. this.imageProcessingConfiguration.vignetteWeight = value;
  69357. },
  69358. enumerable: true,
  69359. configurable: true
  69360. });
  69361. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  69362. /**
  69363. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69364. * if vignetteEnabled is set to true.
  69365. */
  69366. get: function () {
  69367. return this.imageProcessingConfiguration.vignetteColor;
  69368. },
  69369. /**
  69370. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  69371. * if vignetteEnabled is set to true.
  69372. */
  69373. set: function (value) {
  69374. this.imageProcessingConfiguration.vignetteColor = value;
  69375. },
  69376. enumerable: true,
  69377. configurable: true
  69378. });
  69379. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  69380. /**
  69381. * Gets Camera field of view used by the Vignette effect.
  69382. */
  69383. get: function () {
  69384. return this.imageProcessingConfiguration.vignetteCameraFov;
  69385. },
  69386. /**
  69387. * Sets Camera field of view used by the Vignette effect.
  69388. */
  69389. set: function (value) {
  69390. this.imageProcessingConfiguration.vignetteCameraFov = value;
  69391. },
  69392. enumerable: true,
  69393. configurable: true
  69394. });
  69395. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  69396. /**
  69397. * Gets the vignette blend mode allowing different kind of effect.
  69398. */
  69399. get: function () {
  69400. return this.imageProcessingConfiguration.vignetteBlendMode;
  69401. },
  69402. /**
  69403. * Sets the vignette blend mode allowing different kind of effect.
  69404. */
  69405. set: function (value) {
  69406. this.imageProcessingConfiguration.vignetteBlendMode = value;
  69407. },
  69408. enumerable: true,
  69409. configurable: true
  69410. });
  69411. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  69412. /**
  69413. * Gets wether the vignette effect is enabled.
  69414. */
  69415. get: function () {
  69416. return this.imageProcessingConfiguration.vignetteEnabled;
  69417. },
  69418. /**
  69419. * Sets wether the vignette effect is enabled.
  69420. */
  69421. set: function (value) {
  69422. this.imageProcessingConfiguration.vignetteEnabled = value;
  69423. },
  69424. enumerable: true,
  69425. configurable: true
  69426. });
  69427. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  69428. /**
  69429. * Gets wether the input of the processing is in Gamma or Linear Space.
  69430. */
  69431. get: function () {
  69432. return this._fromLinearSpace;
  69433. },
  69434. /**
  69435. * Sets wether the input of the processing is in Gamma or Linear Space.
  69436. */
  69437. set: function (value) {
  69438. if (this._fromLinearSpace === value) {
  69439. return;
  69440. }
  69441. this._fromLinearSpace = value;
  69442. this._updateParameters();
  69443. },
  69444. enumerable: true,
  69445. configurable: true
  69446. });
  69447. ImageProcessingPostProcess.prototype.getClassName = function () {
  69448. return "ImageProcessingPostProcess";
  69449. };
  69450. ImageProcessingPostProcess.prototype._updateParameters = function () {
  69451. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  69452. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  69453. var defines = "";
  69454. for (var define in this._defines) {
  69455. if (this._defines[define]) {
  69456. defines += "#define " + define + ";\r\n";
  69457. }
  69458. }
  69459. var samplers = ["textureSampler"];
  69460. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  69461. var uniforms = ["scale"];
  69462. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  69463. this.updateEffect(defines, uniforms, samplers);
  69464. };
  69465. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  69466. _super.prototype.dispose.call(this, camera);
  69467. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  69468. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  69469. }
  69470. this.imageProcessingConfiguration.applyByPostProcess = false;
  69471. };
  69472. __decorate([
  69473. BABYLON.serialize()
  69474. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  69475. return ImageProcessingPostProcess;
  69476. }(BABYLON.PostProcess));
  69477. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  69478. })(BABYLON || (BABYLON = {}));
  69479. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  69480. var BABYLON;
  69481. (function (BABYLON) {
  69482. /**
  69483. * The Blur Post Process which blurs an image based on a kernel and direction.
  69484. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  69485. */
  69486. var BlurPostProcess = /** @class */ (function (_super) {
  69487. __extends(BlurPostProcess, _super);
  69488. /**
  69489. * Creates a new instance of @see BlurPostProcess
  69490. * @param name The name of the effect.
  69491. * @param direction The direction in which to blur the image.
  69492. * @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.
  69493. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69494. * @param camera The camera to apply the render pass to.
  69495. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69496. * @param engine The engine which the post process will be applied. (default: current engine)
  69497. * @param reusable If the post process can be reused on the same frame. (default: false)
  69498. * @param textureType Type of textures used when performing the post process. (default: 0)
  69499. */
  69500. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines) {
  69501. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69502. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69503. if (defines === void 0) { defines = ""; }
  69504. 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;
  69505. _this.direction = direction;
  69506. _this._packedFloat = false;
  69507. _this._staticDefines = "";
  69508. _this._staticDefines = defines;
  69509. _this.onApplyObservable.add(function (effect) {
  69510. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  69511. });
  69512. _this.kernel = kernel;
  69513. return _this;
  69514. }
  69515. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  69516. /**
  69517. * Gets the length in pixels of the blur sample region
  69518. */
  69519. get: function () {
  69520. return this._idealKernel;
  69521. },
  69522. /**
  69523. * Sets the length in pixels of the blur sample region
  69524. */
  69525. set: function (v) {
  69526. if (this._idealKernel === v) {
  69527. return;
  69528. }
  69529. v = Math.max(v, 1);
  69530. this._idealKernel = v;
  69531. this._kernel = this._nearestBestKernel(v);
  69532. this._updateParameters();
  69533. },
  69534. enumerable: true,
  69535. configurable: true
  69536. });
  69537. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  69538. /**
  69539. * Gets wether or not the blur is unpacking/repacking floats
  69540. */
  69541. get: function () {
  69542. return this._packedFloat;
  69543. },
  69544. /**
  69545. * Sets wether or not the blur needs to unpack/repack floats
  69546. */
  69547. set: function (v) {
  69548. if (this._packedFloat === v) {
  69549. return;
  69550. }
  69551. this._packedFloat = v;
  69552. this._updateParameters();
  69553. },
  69554. enumerable: true,
  69555. configurable: true
  69556. });
  69557. BlurPostProcess.prototype._updateParameters = function () {
  69558. // Generate sampling offsets and weights
  69559. var N = this._kernel;
  69560. var centerIndex = (N - 1) / 2;
  69561. // Generate Gaussian sampling weights over kernel
  69562. var offsets = [];
  69563. var weights = [];
  69564. var totalWeight = 0;
  69565. for (var i = 0; i < N; i++) {
  69566. var u = i / (N - 1);
  69567. var w = this._gaussianWeight(u * 2.0 - 1);
  69568. offsets[i] = (i - centerIndex);
  69569. weights[i] = w;
  69570. totalWeight += w;
  69571. }
  69572. // Normalize weights
  69573. for (var i = 0; i < weights.length; i++) {
  69574. weights[i] /= totalWeight;
  69575. }
  69576. // Optimize: combine samples to take advantage of hardware linear sampling
  69577. // Walk from left to center, combining pairs (symmetrically)
  69578. var linearSamplingWeights = [];
  69579. var linearSamplingOffsets = [];
  69580. var linearSamplingMap = [];
  69581. for (var i = 0; i <= centerIndex; i += 2) {
  69582. var j = Math.min(i + 1, Math.floor(centerIndex));
  69583. var singleCenterSample = i === j;
  69584. if (singleCenterSample) {
  69585. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69586. }
  69587. else {
  69588. var sharedCell = j === centerIndex;
  69589. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  69590. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  69591. if (offsetLinear === 0) {
  69592. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69593. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  69594. }
  69595. else {
  69596. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  69597. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  69598. }
  69599. }
  69600. }
  69601. for (var i = 0; i < linearSamplingMap.length; i++) {
  69602. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  69603. linearSamplingWeights[i] = linearSamplingMap[i].w;
  69604. }
  69605. // Replace with optimized
  69606. offsets = linearSamplingOffsets;
  69607. weights = linearSamplingWeights;
  69608. // Generate shaders
  69609. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  69610. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  69611. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  69612. var defines = "";
  69613. defines += this._staticDefines;
  69614. for (var i = 0; i < varyingCount; i++) {
  69615. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  69616. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  69617. }
  69618. var depCount = 0;
  69619. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  69620. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  69621. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  69622. depCount++;
  69623. }
  69624. if (this.packedFloat) {
  69625. defines += "#define PACKEDFLOAT 1";
  69626. }
  69627. this.updateEffect(defines, null, null, {
  69628. varyingCount: varyingCount,
  69629. depCount: depCount
  69630. });
  69631. };
  69632. /**
  69633. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  69634. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  69635. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  69636. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  69637. * The gaps between physical kernels are compensated for in the weighting of the samples
  69638. * @param idealKernel Ideal blur kernel.
  69639. * @return Nearest best kernel.
  69640. */
  69641. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  69642. var v = Math.round(idealKernel);
  69643. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  69644. var k = _a[_i];
  69645. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  69646. return Math.max(k, 3);
  69647. }
  69648. }
  69649. return Math.max(v, 3);
  69650. };
  69651. /**
  69652. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  69653. * @param x The point on the Gaussian distribution to sample.
  69654. * @return the value of the Gaussian function at x.
  69655. */
  69656. BlurPostProcess.prototype._gaussianWeight = function (x) {
  69657. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  69658. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  69659. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  69660. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  69661. // truncated at around 1.3% of peak strength.
  69662. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  69663. var sigma = (1 / 3);
  69664. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  69665. var exponent = -((x * x) / (2.0 * sigma * sigma));
  69666. var weight = (1.0 / denominator) * Math.exp(exponent);
  69667. return weight;
  69668. };
  69669. /**
  69670. * Generates a string that can be used as a floating point number in GLSL.
  69671. * @param x Value to print.
  69672. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  69673. * @return GLSL float string.
  69674. */
  69675. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  69676. if (decimalFigures === void 0) { decimalFigures = 8; }
  69677. return x.toFixed(decimalFigures).replace(/0+$/, '');
  69678. };
  69679. return BlurPostProcess;
  69680. }(BABYLON.PostProcess));
  69681. BABYLON.BlurPostProcess = BlurPostProcess;
  69682. })(BABYLON || (BABYLON = {}));
  69683. //# sourceMappingURL=babylon.blurPostProcess.js.map
  69684. var BABYLON;
  69685. (function (BABYLON) {
  69686. /**
  69687. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  69688. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  69689. * based on samples that have a large difference in distance than the center pixel.
  69690. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69691. */
  69692. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  69693. __extends(DepthOfFieldBlurPostProcess, _super);
  69694. /**
  69695. * Creates a new instance of @see CircleOfConfusionPostProcess
  69696. * @param name The name of the effect.
  69697. * @param scene The scene the effect belongs to.
  69698. * @param direction The direction the blur should be applied.
  69699. * @param kernel The size of the kernel used to blur.
  69700. * @param options The required width/height ratio to downsize to before computing the render pass.
  69701. * @param camera The camera to apply the render pass to.
  69702. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  69703. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  69704. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69705. * @param engine The engine which the post process will be applied. (default: current engine)
  69706. * @param reusable If the post process can be reused on the same frame. (default: false)
  69707. * @param textureType Type of textures used when performing the post process. (default: 0)
  69708. */
  69709. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType) {
  69710. if (imageToBlur === void 0) { imageToBlur = null; }
  69711. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69712. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69713. 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") || this;
  69714. _this.direction = direction;
  69715. _this.onApplyObservable.add(function (effect) {
  69716. if (imageToBlur != null) {
  69717. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  69718. }
  69719. effect.setTextureFromPostProcess("circleOfConfusionSampler", circleOfConfusion);
  69720. if (scene.activeCamera) {
  69721. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  69722. }
  69723. });
  69724. return _this;
  69725. }
  69726. return DepthOfFieldBlurPostProcess;
  69727. }(BABYLON.BlurPostProcess));
  69728. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  69729. })(BABYLON || (BABYLON = {}));
  69730. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  69731. var BABYLON;
  69732. (function (BABYLON) {
  69733. var Bone = /** @class */ (function (_super) {
  69734. __extends(Bone, _super);
  69735. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  69736. if (parentBone === void 0) { parentBone = null; }
  69737. if (localMatrix === void 0) { localMatrix = null; }
  69738. if (restPose === void 0) { restPose = null; }
  69739. if (baseMatrix === void 0) { baseMatrix = null; }
  69740. if (index === void 0) { index = null; }
  69741. var _this = _super.call(this, name, skeleton.getScene()) || this;
  69742. _this.name = name;
  69743. _this.children = new Array();
  69744. _this.animations = new Array();
  69745. // Set this value to map this bone to a different index in the transform matrices.
  69746. // Set this value to -1 to exclude the bone from the transform matrices.
  69747. _this._index = null;
  69748. _this._worldTransform = new BABYLON.Matrix();
  69749. _this._absoluteTransform = new BABYLON.Matrix();
  69750. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  69751. _this._scaleMatrix = BABYLON.Matrix.Identity();
  69752. _this._scaleVector = BABYLON.Vector3.One();
  69753. _this._negateScaleChildren = BABYLON.Vector3.One();
  69754. _this._scalingDeterminant = 1;
  69755. _this._skeleton = skeleton;
  69756. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  69757. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  69758. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  69759. _this._index = index;
  69760. skeleton.bones.push(_this);
  69761. _this.setParent(parentBone, false);
  69762. _this._updateDifferenceMatrix();
  69763. return _this;
  69764. }
  69765. Object.defineProperty(Bone.prototype, "_matrix", {
  69766. get: function () {
  69767. return this._localMatrix;
  69768. },
  69769. set: function (val) {
  69770. if (this._localMatrix) {
  69771. this._localMatrix.copyFrom(val);
  69772. }
  69773. else {
  69774. this._localMatrix = val;
  69775. }
  69776. },
  69777. enumerable: true,
  69778. configurable: true
  69779. });
  69780. // Members
  69781. Bone.prototype.getSkeleton = function () {
  69782. return this._skeleton;
  69783. };
  69784. Bone.prototype.getParent = function () {
  69785. return this._parent;
  69786. };
  69787. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  69788. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  69789. if (this._parent === parent) {
  69790. return;
  69791. }
  69792. if (this._parent) {
  69793. var index = this._parent.children.indexOf(this);
  69794. if (index !== -1) {
  69795. this._parent.children.splice(index, 1);
  69796. }
  69797. }
  69798. this._parent = parent;
  69799. if (this._parent) {
  69800. this._parent.children.push(this);
  69801. }
  69802. if (updateDifferenceMatrix) {
  69803. this._updateDifferenceMatrix();
  69804. }
  69805. };
  69806. Bone.prototype.getLocalMatrix = function () {
  69807. return this._localMatrix;
  69808. };
  69809. Bone.prototype.getBaseMatrix = function () {
  69810. return this._baseMatrix;
  69811. };
  69812. Bone.prototype.getRestPose = function () {
  69813. return this._restPose;
  69814. };
  69815. Bone.prototype.returnToRest = function () {
  69816. this.updateMatrix(this._restPose.clone());
  69817. };
  69818. Bone.prototype.getWorldMatrix = function () {
  69819. return this._worldTransform;
  69820. };
  69821. Bone.prototype.getInvertedAbsoluteTransform = function () {
  69822. return this._invertedAbsoluteTransform;
  69823. };
  69824. Bone.prototype.getAbsoluteTransform = function () {
  69825. return this._absoluteTransform;
  69826. };
  69827. Object.defineProperty(Bone.prototype, "position", {
  69828. // Properties (matches AbstractMesh properties)
  69829. get: function () {
  69830. return this.getPosition();
  69831. },
  69832. set: function (newPosition) {
  69833. this.setPosition(newPosition);
  69834. },
  69835. enumerable: true,
  69836. configurable: true
  69837. });
  69838. Object.defineProperty(Bone.prototype, "rotation", {
  69839. get: function () {
  69840. return this.getRotation();
  69841. },
  69842. set: function (newRotation) {
  69843. this.setRotation(newRotation);
  69844. },
  69845. enumerable: true,
  69846. configurable: true
  69847. });
  69848. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  69849. get: function () {
  69850. return this.getRotationQuaternion();
  69851. },
  69852. set: function (newRotation) {
  69853. this.setRotationQuaternion(newRotation);
  69854. },
  69855. enumerable: true,
  69856. configurable: true
  69857. });
  69858. Object.defineProperty(Bone.prototype, "scaling", {
  69859. get: function () {
  69860. return this.getScale();
  69861. },
  69862. set: function (newScaling) {
  69863. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  69864. },
  69865. enumerable: true,
  69866. configurable: true
  69867. });
  69868. // Methods
  69869. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  69870. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  69871. this._baseMatrix = matrix.clone();
  69872. this._localMatrix = matrix.clone();
  69873. this._skeleton._markAsDirty();
  69874. if (updateDifferenceMatrix) {
  69875. this._updateDifferenceMatrix();
  69876. }
  69877. };
  69878. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  69879. if (!rootMatrix) {
  69880. rootMatrix = this._baseMatrix;
  69881. }
  69882. if (this._parent) {
  69883. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  69884. }
  69885. else {
  69886. this._absoluteTransform.copyFrom(rootMatrix);
  69887. }
  69888. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  69889. for (var index = 0; index < this.children.length; index++) {
  69890. this.children[index]._updateDifferenceMatrix();
  69891. }
  69892. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  69893. };
  69894. Bone.prototype.markAsDirty = function () {
  69895. this._currentRenderId++;
  69896. this._skeleton._markAsDirty();
  69897. };
  69898. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  69899. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  69900. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  69901. // all animation may be coming from a library skeleton, so may need to create animation
  69902. if (this.animations.length === 0) {
  69903. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  69904. this.animations[0].setKeys([]);
  69905. }
  69906. // get animation info / verify there is such a range from the source bone
  69907. var sourceRange = source.animations[0].getRange(rangeName);
  69908. if (!sourceRange) {
  69909. return false;
  69910. }
  69911. var from = sourceRange.from;
  69912. var to = sourceRange.to;
  69913. var sourceKeys = source.animations[0].getKeys();
  69914. // rescaling prep
  69915. var sourceBoneLength = source.length;
  69916. var sourceParent = source.getParent();
  69917. var parent = this.getParent();
  69918. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  69919. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  69920. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  69921. var destKeys = this.animations[0].getKeys();
  69922. // loop vars declaration
  69923. var orig;
  69924. var origTranslation;
  69925. var mat;
  69926. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  69927. orig = sourceKeys[key];
  69928. if (orig.frame >= from && orig.frame <= to) {
  69929. if (rescaleAsRequired) {
  69930. mat = orig.value.clone();
  69931. // scale based on parent ratio, when bone has parent
  69932. if (parentScalingReqd) {
  69933. origTranslation = mat.getTranslation();
  69934. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  69935. // scale based on skeleton dimension ratio when root bone, and value is passed
  69936. }
  69937. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  69938. origTranslation = mat.getTranslation();
  69939. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  69940. // use original when root bone, and no data for skelDimensionsRatio
  69941. }
  69942. else {
  69943. mat = orig.value;
  69944. }
  69945. }
  69946. else {
  69947. mat = orig.value;
  69948. }
  69949. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  69950. }
  69951. }
  69952. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  69953. return true;
  69954. };
  69955. /**
  69956. * Translate the bone in local or world space.
  69957. * @param vec The amount to translate the bone.
  69958. * @param space The space that the translation is in.
  69959. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  69960. */
  69961. Bone.prototype.translate = function (vec, space, mesh) {
  69962. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  69963. var lm = this.getLocalMatrix();
  69964. if (space == BABYLON.Space.LOCAL) {
  69965. lm.m[12] += vec.x;
  69966. lm.m[13] += vec.y;
  69967. lm.m[14] += vec.z;
  69968. }
  69969. else {
  69970. var wm = null;
  69971. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  69972. if (mesh) {
  69973. wm = mesh.getWorldMatrix();
  69974. }
  69975. this._skeleton.computeAbsoluteTransforms();
  69976. var tmat = Bone._tmpMats[0];
  69977. var tvec = Bone._tmpVecs[0];
  69978. if (this._parent) {
  69979. if (mesh && wm) {
  69980. tmat.copyFrom(this._parent.getAbsoluteTransform());
  69981. tmat.multiplyToRef(wm, tmat);
  69982. }
  69983. else {
  69984. tmat.copyFrom(this._parent.getAbsoluteTransform());
  69985. }
  69986. }
  69987. tmat.m[12] = 0;
  69988. tmat.m[13] = 0;
  69989. tmat.m[14] = 0;
  69990. tmat.invert();
  69991. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  69992. lm.m[12] += tvec.x;
  69993. lm.m[13] += tvec.y;
  69994. lm.m[14] += tvec.z;
  69995. }
  69996. this.markAsDirty();
  69997. };
  69998. /**
  69999. * Set the postion of the bone in local or world space.
  70000. * @param position The position to set the bone.
  70001. * @param space The space that the position is in.
  70002. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70003. */
  70004. Bone.prototype.setPosition = function (position, space, mesh) {
  70005. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70006. var lm = this.getLocalMatrix();
  70007. if (space == BABYLON.Space.LOCAL) {
  70008. lm.m[12] = position.x;
  70009. lm.m[13] = position.y;
  70010. lm.m[14] = position.z;
  70011. }
  70012. else {
  70013. var wm = null;
  70014. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70015. if (mesh) {
  70016. wm = mesh.getWorldMatrix();
  70017. }
  70018. this._skeleton.computeAbsoluteTransforms();
  70019. var tmat = Bone._tmpMats[0];
  70020. var vec = Bone._tmpVecs[0];
  70021. if (this._parent) {
  70022. if (mesh && wm) {
  70023. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70024. tmat.multiplyToRef(wm, tmat);
  70025. }
  70026. else {
  70027. tmat.copyFrom(this._parent.getAbsoluteTransform());
  70028. }
  70029. }
  70030. tmat.invert();
  70031. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  70032. lm.m[12] = vec.x;
  70033. lm.m[13] = vec.y;
  70034. lm.m[14] = vec.z;
  70035. }
  70036. this.markAsDirty();
  70037. };
  70038. /**
  70039. * Set the absolute postion of the bone (world space).
  70040. * @param position The position to set the bone.
  70041. * @param mesh The mesh that this bone is attached to.
  70042. */
  70043. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  70044. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  70045. };
  70046. /**
  70047. * Set the scale of the bone on the x, y and z axes.
  70048. * @param x The scale of the bone on the x axis.
  70049. * @param x The scale of the bone on the y axis.
  70050. * @param z The scale of the bone on the z axis.
  70051. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70052. */
  70053. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  70054. if (scaleChildren === void 0) { scaleChildren = false; }
  70055. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  70056. if (!scaleChildren) {
  70057. this._negateScaleChildren.x = 1 / x;
  70058. this._negateScaleChildren.y = 1 / y;
  70059. this._negateScaleChildren.z = 1 / z;
  70060. }
  70061. this._syncScaleVector();
  70062. }
  70063. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  70064. };
  70065. /**
  70066. * Scale the bone on the x, y and z axes.
  70067. * @param x The amount to scale the bone on the x axis.
  70068. * @param x The amount to scale the bone on the y axis.
  70069. * @param z The amount to scale the bone on the z axis.
  70070. * @param scaleChildren Set this to true if children of the bone should be scaled.
  70071. */
  70072. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  70073. if (scaleChildren === void 0) { scaleChildren = false; }
  70074. var locMat = this.getLocalMatrix();
  70075. var origLocMat = Bone._tmpMats[0];
  70076. origLocMat.copyFrom(locMat);
  70077. var origLocMatInv = Bone._tmpMats[1];
  70078. origLocMatInv.copyFrom(origLocMat);
  70079. origLocMatInv.invert();
  70080. var scaleMat = Bone._tmpMats[2];
  70081. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  70082. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  70083. this._scaleVector.x *= x;
  70084. this._scaleVector.y *= y;
  70085. this._scaleVector.z *= z;
  70086. locMat.multiplyToRef(origLocMatInv, locMat);
  70087. locMat.multiplyToRef(scaleMat, locMat);
  70088. locMat.multiplyToRef(origLocMat, locMat);
  70089. var parent = this.getParent();
  70090. if (parent) {
  70091. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  70092. }
  70093. else {
  70094. this.getAbsoluteTransform().copyFrom(locMat);
  70095. }
  70096. var len = this.children.length;
  70097. scaleMat.invert();
  70098. for (var i = 0; i < len; i++) {
  70099. var child = this.children[i];
  70100. var cm = child.getLocalMatrix();
  70101. cm.multiplyToRef(scaleMat, cm);
  70102. var lm = child.getLocalMatrix();
  70103. lm.m[12] *= x;
  70104. lm.m[13] *= y;
  70105. lm.m[14] *= z;
  70106. }
  70107. this.computeAbsoluteTransforms();
  70108. if (scaleChildren) {
  70109. for (var i = 0; i < len; i++) {
  70110. this.children[i].scale(x, y, z, scaleChildren);
  70111. }
  70112. }
  70113. this.markAsDirty();
  70114. };
  70115. /**
  70116. * Set the yaw, pitch, and roll of the bone in local or world space.
  70117. * @param yaw The rotation of the bone on the y axis.
  70118. * @param pitch The rotation of the bone on the x axis.
  70119. * @param roll The rotation of the bone on the z axis.
  70120. * @param space The space that the axes of rotation are in.
  70121. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70122. */
  70123. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  70124. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70125. var rotMat = Bone._tmpMats[0];
  70126. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  70127. var rotMatInv = Bone._tmpMats[1];
  70128. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70129. rotMatInv.multiplyToRef(rotMat, rotMat);
  70130. this._rotateWithMatrix(rotMat, space, mesh);
  70131. };
  70132. /**
  70133. * Rotate the bone on an axis in local or world space.
  70134. * @param axis The axis to rotate the bone on.
  70135. * @param amount The amount to rotate the bone.
  70136. * @param space The space that the axis is in.
  70137. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70138. */
  70139. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  70140. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70141. var rmat = Bone._tmpMats[0];
  70142. rmat.m[12] = 0;
  70143. rmat.m[13] = 0;
  70144. rmat.m[14] = 0;
  70145. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  70146. this._rotateWithMatrix(rmat, space, mesh);
  70147. };
  70148. /**
  70149. * Set the rotation of the bone to a particular axis angle in local or world space.
  70150. * @param axis The axis to rotate the bone on.
  70151. * @param angle The angle that the bone should be rotated to.
  70152. * @param space The space that the axis is in.
  70153. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70154. */
  70155. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  70156. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70157. var rotMat = Bone._tmpMats[0];
  70158. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  70159. var rotMatInv = Bone._tmpMats[1];
  70160. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70161. rotMatInv.multiplyToRef(rotMat, rotMat);
  70162. this._rotateWithMatrix(rotMat, space, mesh);
  70163. };
  70164. /**
  70165. * Set the euler rotation of the bone in local of world space.
  70166. * @param rotation The euler rotation that the bone should be set to.
  70167. * @param space The space that the rotation is in.
  70168. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70169. */
  70170. Bone.prototype.setRotation = function (rotation, space, mesh) {
  70171. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70172. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  70173. };
  70174. /**
  70175. * Set the quaternion rotation of the bone in local of world space.
  70176. * @param quat The quaternion rotation that the bone should be set to.
  70177. * @param space The space that the rotation is in.
  70178. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70179. */
  70180. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  70181. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70182. var rotMatInv = Bone._tmpMats[0];
  70183. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70184. var rotMat = Bone._tmpMats[1];
  70185. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  70186. rotMatInv.multiplyToRef(rotMat, rotMat);
  70187. this._rotateWithMatrix(rotMat, space, mesh);
  70188. };
  70189. /**
  70190. * Set the rotation matrix of the bone in local of world space.
  70191. * @param rotMat The rotation matrix that the bone should be set to.
  70192. * @param space The space that the rotation is in.
  70193. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70194. */
  70195. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  70196. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70197. var rotMatInv = Bone._tmpMats[0];
  70198. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  70199. var rotMat2 = Bone._tmpMats[1];
  70200. rotMat2.copyFrom(rotMat);
  70201. rotMatInv.multiplyToRef(rotMat, rotMat2);
  70202. this._rotateWithMatrix(rotMat2, space, mesh);
  70203. };
  70204. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  70205. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70206. var lmat = this.getLocalMatrix();
  70207. var lx = lmat.m[12];
  70208. var ly = lmat.m[13];
  70209. var lz = lmat.m[14];
  70210. var parent = this.getParent();
  70211. var parentScale = Bone._tmpMats[3];
  70212. var parentScaleInv = Bone._tmpMats[4];
  70213. if (parent) {
  70214. if (space == BABYLON.Space.WORLD) {
  70215. if (mesh) {
  70216. parentScale.copyFrom(mesh.getWorldMatrix());
  70217. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  70218. }
  70219. else {
  70220. parentScale.copyFrom(parent.getAbsoluteTransform());
  70221. }
  70222. }
  70223. else {
  70224. parentScale = parent._scaleMatrix;
  70225. }
  70226. parentScaleInv.copyFrom(parentScale);
  70227. parentScaleInv.invert();
  70228. lmat.multiplyToRef(parentScale, lmat);
  70229. lmat.multiplyToRef(rmat, lmat);
  70230. lmat.multiplyToRef(parentScaleInv, lmat);
  70231. }
  70232. else {
  70233. if (space == BABYLON.Space.WORLD && mesh) {
  70234. parentScale.copyFrom(mesh.getWorldMatrix());
  70235. parentScaleInv.copyFrom(parentScale);
  70236. parentScaleInv.invert();
  70237. lmat.multiplyToRef(parentScale, lmat);
  70238. lmat.multiplyToRef(rmat, lmat);
  70239. lmat.multiplyToRef(parentScaleInv, lmat);
  70240. }
  70241. else {
  70242. lmat.multiplyToRef(rmat, lmat);
  70243. }
  70244. }
  70245. lmat.m[12] = lx;
  70246. lmat.m[13] = ly;
  70247. lmat.m[14] = lz;
  70248. this.computeAbsoluteTransforms();
  70249. this.markAsDirty();
  70250. };
  70251. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  70252. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70253. if (space == BABYLON.Space.WORLD) {
  70254. var scaleMatrix = Bone._tmpMats[2];
  70255. scaleMatrix.copyFrom(this._scaleMatrix);
  70256. rotMatInv.copyFrom(this.getAbsoluteTransform());
  70257. if (mesh) {
  70258. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  70259. var meshScale = Bone._tmpMats[3];
  70260. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  70261. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  70262. }
  70263. rotMatInv.invert();
  70264. scaleMatrix.m[0] *= this._scalingDeterminant;
  70265. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70266. }
  70267. else {
  70268. rotMatInv.copyFrom(this.getLocalMatrix());
  70269. rotMatInv.invert();
  70270. var scaleMatrix = Bone._tmpMats[2];
  70271. scaleMatrix.copyFrom(this._scaleMatrix);
  70272. if (this._parent) {
  70273. var pscaleMatrix = Bone._tmpMats[3];
  70274. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  70275. pscaleMatrix.invert();
  70276. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  70277. }
  70278. else {
  70279. scaleMatrix.m[0] *= this._scalingDeterminant;
  70280. }
  70281. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  70282. }
  70283. };
  70284. /**
  70285. * Get the scale of the bone
  70286. * @returns the scale of the bone
  70287. */
  70288. Bone.prototype.getScale = function () {
  70289. return this._scaleVector.clone();
  70290. };
  70291. /**
  70292. * Copy the scale of the bone to a vector3.
  70293. * @param result The vector3 to copy the scale to
  70294. */
  70295. Bone.prototype.getScaleToRef = function (result) {
  70296. result.copyFrom(this._scaleVector);
  70297. };
  70298. /**
  70299. * Get the position of the bone in local or world space.
  70300. * @param space The space that the returned position is in.
  70301. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70302. * @returns The position of the bone
  70303. */
  70304. Bone.prototype.getPosition = function (space, mesh) {
  70305. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70306. if (mesh === void 0) { mesh = null; }
  70307. var pos = BABYLON.Vector3.Zero();
  70308. this.getPositionToRef(space, mesh, pos);
  70309. return pos;
  70310. };
  70311. /**
  70312. * Copy the position of the bone to a vector3 in local or world space.
  70313. * @param space The space that the returned position is in.
  70314. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70315. * @param result The vector3 to copy the position to.
  70316. */
  70317. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  70318. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70319. if (space == BABYLON.Space.LOCAL) {
  70320. var lm = this.getLocalMatrix();
  70321. result.x = lm.m[12];
  70322. result.y = lm.m[13];
  70323. result.z = lm.m[14];
  70324. }
  70325. else {
  70326. var wm = null;
  70327. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70328. if (mesh) {
  70329. wm = mesh.getWorldMatrix();
  70330. }
  70331. this._skeleton.computeAbsoluteTransforms();
  70332. var tmat = Bone._tmpMats[0];
  70333. if (mesh && wm) {
  70334. tmat.copyFrom(this.getAbsoluteTransform());
  70335. tmat.multiplyToRef(wm, tmat);
  70336. }
  70337. else {
  70338. tmat = this.getAbsoluteTransform();
  70339. }
  70340. result.x = tmat.m[12];
  70341. result.y = tmat.m[13];
  70342. result.z = tmat.m[14];
  70343. }
  70344. };
  70345. /**
  70346. * Get the absolute position of the bone (world space).
  70347. * @param mesh The mesh that this bone is attached to.
  70348. * @returns The absolute position of the bone
  70349. */
  70350. Bone.prototype.getAbsolutePosition = function (mesh) {
  70351. if (mesh === void 0) { mesh = null; }
  70352. var pos = BABYLON.Vector3.Zero();
  70353. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  70354. return pos;
  70355. };
  70356. /**
  70357. * Copy the absolute position of the bone (world space) to the result param.
  70358. * @param mesh The mesh that this bone is attached to.
  70359. * @param result The vector3 to copy the absolute position to.
  70360. */
  70361. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  70362. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  70363. };
  70364. /**
  70365. * Compute the absolute transforms of this bone and its children.
  70366. */
  70367. Bone.prototype.computeAbsoluteTransforms = function () {
  70368. if (this._parent) {
  70369. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  70370. }
  70371. else {
  70372. this._absoluteTransform.copyFrom(this._localMatrix);
  70373. var poseMatrix = this._skeleton.getPoseMatrix();
  70374. if (poseMatrix) {
  70375. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  70376. }
  70377. }
  70378. var children = this.children;
  70379. var len = children.length;
  70380. for (var i = 0; i < len; i++) {
  70381. children[i].computeAbsoluteTransforms();
  70382. }
  70383. };
  70384. Bone.prototype._syncScaleVector = function () {
  70385. var lm = this.getLocalMatrix();
  70386. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  70387. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  70388. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  70389. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  70390. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  70391. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  70392. this._scaleVector.x = xs * Math.sqrt(xsq);
  70393. this._scaleVector.y = ys * Math.sqrt(ysq);
  70394. this._scaleVector.z = zs * Math.sqrt(zsq);
  70395. if (this._parent) {
  70396. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  70397. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  70398. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  70399. }
  70400. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  70401. };
  70402. /**
  70403. * Get the world direction from an axis that is in the local space of the bone.
  70404. * @param localAxis The local direction that is used to compute the world direction.
  70405. * @param mesh The mesh that this bone is attached to.
  70406. * @returns The world direction
  70407. */
  70408. Bone.prototype.getDirection = function (localAxis, mesh) {
  70409. if (mesh === void 0) { mesh = null; }
  70410. var result = BABYLON.Vector3.Zero();
  70411. this.getDirectionToRef(localAxis, mesh, result);
  70412. return result;
  70413. };
  70414. /**
  70415. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  70416. * @param localAxis The local direction that is used to compute the world direction.
  70417. * @param mesh The mesh that this bone is attached to.
  70418. * @param result The vector3 that the world direction will be copied to.
  70419. */
  70420. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  70421. if (mesh === void 0) { mesh = null; }
  70422. var wm = null;
  70423. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70424. if (mesh) {
  70425. wm = mesh.getWorldMatrix();
  70426. }
  70427. this._skeleton.computeAbsoluteTransforms();
  70428. var mat = Bone._tmpMats[0];
  70429. mat.copyFrom(this.getAbsoluteTransform());
  70430. if (mesh && wm) {
  70431. mat.multiplyToRef(wm, mat);
  70432. }
  70433. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  70434. result.normalize();
  70435. };
  70436. /**
  70437. * Get the euler rotation of the bone in local or world space.
  70438. * @param space The space that the rotation should be in.
  70439. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70440. * @returns The euler rotation
  70441. */
  70442. Bone.prototype.getRotation = function (space, mesh) {
  70443. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70444. if (mesh === void 0) { mesh = null; }
  70445. var result = BABYLON.Vector3.Zero();
  70446. this.getRotationToRef(space, mesh, result);
  70447. return result;
  70448. };
  70449. /**
  70450. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  70451. * @param space The space that the rotation should be in.
  70452. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70453. * @param result The vector3 that the rotation should be copied to.
  70454. */
  70455. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  70456. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70457. if (mesh === void 0) { mesh = null; }
  70458. var quat = Bone._tmpQuat;
  70459. this.getRotationQuaternionToRef(space, mesh, quat);
  70460. quat.toEulerAnglesToRef(result);
  70461. };
  70462. /**
  70463. * Get the quaternion rotation of the bone in either local or world space.
  70464. * @param space The space that the rotation should be in.
  70465. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70466. * @returns The quaternion rotation
  70467. */
  70468. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  70469. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70470. if (mesh === void 0) { mesh = null; }
  70471. var result = BABYLON.Quaternion.Identity();
  70472. this.getRotationQuaternionToRef(space, mesh, result);
  70473. return result;
  70474. };
  70475. /**
  70476. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  70477. * @param space The space that the rotation should be in.
  70478. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70479. * @param result The quaternion that the rotation should be copied to.
  70480. */
  70481. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  70482. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70483. if (mesh === void 0) { mesh = null; }
  70484. if (space == BABYLON.Space.LOCAL) {
  70485. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  70486. }
  70487. else {
  70488. var mat = Bone._tmpMats[0];
  70489. var amat = this.getAbsoluteTransform();
  70490. if (mesh) {
  70491. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  70492. }
  70493. else {
  70494. mat.copyFrom(amat);
  70495. }
  70496. mat.m[0] *= this._scalingDeterminant;
  70497. mat.m[1] *= this._scalingDeterminant;
  70498. mat.m[2] *= this._scalingDeterminant;
  70499. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  70500. }
  70501. };
  70502. /**
  70503. * Get the rotation matrix of the bone in local or world space.
  70504. * @param space The space that the rotation should be in.
  70505. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70506. * @returns The rotation matrix
  70507. */
  70508. Bone.prototype.getRotationMatrix = function (space, mesh) {
  70509. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70510. var result = BABYLON.Matrix.Identity();
  70511. this.getRotationMatrixToRef(space, mesh, result);
  70512. return result;
  70513. };
  70514. /**
  70515. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  70516. * @param space The space that the rotation should be in.
  70517. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  70518. * @param result The quaternion that the rotation should be copied to.
  70519. */
  70520. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  70521. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  70522. if (space == BABYLON.Space.LOCAL) {
  70523. this.getLocalMatrix().getRotationMatrixToRef(result);
  70524. }
  70525. else {
  70526. var mat = Bone._tmpMats[0];
  70527. var amat = this.getAbsoluteTransform();
  70528. if (mesh) {
  70529. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  70530. }
  70531. else {
  70532. mat.copyFrom(amat);
  70533. }
  70534. mat.m[0] *= this._scalingDeterminant;
  70535. mat.m[1] *= this._scalingDeterminant;
  70536. mat.m[2] *= this._scalingDeterminant;
  70537. mat.getRotationMatrixToRef(result);
  70538. }
  70539. };
  70540. /**
  70541. * Get the world position of a point that is in the local space of the bone.
  70542. * @param position The local position
  70543. * @param mesh The mesh that this bone is attached to.
  70544. * @returns The world position
  70545. */
  70546. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  70547. if (mesh === void 0) { mesh = null; }
  70548. var result = BABYLON.Vector3.Zero();
  70549. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  70550. return result;
  70551. };
  70552. /**
  70553. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  70554. * @param position The local position
  70555. * @param mesh The mesh that this bone is attached to.
  70556. * @param result The vector3 that the world position should be copied to.
  70557. */
  70558. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  70559. if (mesh === void 0) { mesh = null; }
  70560. var wm = null;
  70561. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70562. if (mesh) {
  70563. wm = mesh.getWorldMatrix();
  70564. }
  70565. this._skeleton.computeAbsoluteTransforms();
  70566. var tmat = Bone._tmpMats[0];
  70567. if (mesh && wm) {
  70568. tmat.copyFrom(this.getAbsoluteTransform());
  70569. tmat.multiplyToRef(wm, tmat);
  70570. }
  70571. else {
  70572. tmat = this.getAbsoluteTransform();
  70573. }
  70574. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  70575. };
  70576. /**
  70577. * Get the local position of a point that is in world space.
  70578. * @param position The world position
  70579. * @param mesh The mesh that this bone is attached to.
  70580. * @returns The local position
  70581. */
  70582. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  70583. if (mesh === void 0) { mesh = null; }
  70584. var result = BABYLON.Vector3.Zero();
  70585. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  70586. return result;
  70587. };
  70588. /**
  70589. * Get the local position of a point that is in world space and copy it to the result param.
  70590. * @param position The world position
  70591. * @param mesh The mesh that this bone is attached to.
  70592. * @param result The vector3 that the local position should be copied to.
  70593. */
  70594. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  70595. if (mesh === void 0) { mesh = null; }
  70596. var wm = null;
  70597. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  70598. if (mesh) {
  70599. wm = mesh.getWorldMatrix();
  70600. }
  70601. this._skeleton.computeAbsoluteTransforms();
  70602. var tmat = Bone._tmpMats[0];
  70603. tmat.copyFrom(this.getAbsoluteTransform());
  70604. if (mesh && wm) {
  70605. tmat.multiplyToRef(wm, tmat);
  70606. }
  70607. tmat.invert();
  70608. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  70609. };
  70610. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70611. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  70612. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70613. return Bone;
  70614. }(BABYLON.Node));
  70615. BABYLON.Bone = Bone;
  70616. })(BABYLON || (BABYLON = {}));
  70617. //# sourceMappingURL=babylon.bone.js.map
  70618. var BABYLON;
  70619. (function (BABYLON) {
  70620. var BoneIKController = /** @class */ (function () {
  70621. function BoneIKController(mesh, bone, options) {
  70622. this.targetPosition = BABYLON.Vector3.Zero();
  70623. this.poleTargetPosition = BABYLON.Vector3.Zero();
  70624. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  70625. this.poleAngle = 0;
  70626. this.slerpAmount = 1;
  70627. this._bone1Quat = BABYLON.Quaternion.Identity();
  70628. this._bone1Mat = BABYLON.Matrix.Identity();
  70629. this._bone2Ang = Math.PI;
  70630. this._maxAngle = Math.PI;
  70631. this._rightHandedSystem = false;
  70632. this._bendAxis = BABYLON.Vector3.Right();
  70633. this._slerping = false;
  70634. this._adjustRoll = 0;
  70635. this._bone2 = bone;
  70636. this._bone1 = bone.getParent();
  70637. if (!this._bone1) {
  70638. return;
  70639. }
  70640. this.mesh = mesh;
  70641. var bonePos = bone.getPosition();
  70642. if (bone.getAbsoluteTransform().determinant() > 0) {
  70643. this._rightHandedSystem = true;
  70644. this._bendAxis.x = 0;
  70645. this._bendAxis.y = 0;
  70646. this._bendAxis.z = -1;
  70647. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  70648. this._adjustRoll = Math.PI * .5;
  70649. this._bendAxis.z = 1;
  70650. }
  70651. }
  70652. if (this._bone1.length) {
  70653. var boneScale1 = this._bone1.getScale();
  70654. var boneScale2 = this._bone2.getScale();
  70655. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  70656. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  70657. }
  70658. else if (this._bone1.children[0]) {
  70659. mesh.computeWorldMatrix(true);
  70660. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  70661. var pos2 = this._bone2.getAbsolutePosition(mesh);
  70662. var pos3 = this._bone1.getAbsolutePosition(mesh);
  70663. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  70664. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  70665. }
  70666. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  70667. this.maxAngle = Math.PI;
  70668. if (options) {
  70669. if (options.targetMesh) {
  70670. this.targetMesh = options.targetMesh;
  70671. this.targetMesh.computeWorldMatrix(true);
  70672. }
  70673. if (options.poleTargetMesh) {
  70674. this.poleTargetMesh = options.poleTargetMesh;
  70675. this.poleTargetMesh.computeWorldMatrix(true);
  70676. }
  70677. else if (options.poleTargetBone) {
  70678. this.poleTargetBone = options.poleTargetBone;
  70679. }
  70680. else if (this._bone1.getParent()) {
  70681. this.poleTargetBone = this._bone1.getParent();
  70682. }
  70683. if (options.poleTargetLocalOffset) {
  70684. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  70685. }
  70686. if (options.poleAngle) {
  70687. this.poleAngle = options.poleAngle;
  70688. }
  70689. if (options.bendAxis) {
  70690. this._bendAxis.copyFrom(options.bendAxis);
  70691. }
  70692. if (options.maxAngle) {
  70693. this.maxAngle = options.maxAngle;
  70694. }
  70695. if (options.slerpAmount) {
  70696. this.slerpAmount = options.slerpAmount;
  70697. }
  70698. }
  70699. }
  70700. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  70701. get: function () {
  70702. return this._maxAngle;
  70703. },
  70704. set: function (value) {
  70705. this._setMaxAngle(value);
  70706. },
  70707. enumerable: true,
  70708. configurable: true
  70709. });
  70710. BoneIKController.prototype._setMaxAngle = function (ang) {
  70711. if (ang < 0) {
  70712. ang = 0;
  70713. }
  70714. if (ang > Math.PI || ang == undefined) {
  70715. ang = Math.PI;
  70716. }
  70717. this._maxAngle = ang;
  70718. var a = this._bone1Length;
  70719. var b = this._bone2Length;
  70720. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  70721. };
  70722. BoneIKController.prototype.update = function () {
  70723. var bone1 = this._bone1;
  70724. if (!bone1) {
  70725. return;
  70726. }
  70727. var target = this.targetPosition;
  70728. var poleTarget = this.poleTargetPosition;
  70729. var mat1 = BoneIKController._tmpMats[0];
  70730. var mat2 = BoneIKController._tmpMats[1];
  70731. if (this.targetMesh) {
  70732. target.copyFrom(this.targetMesh.getAbsolutePosition());
  70733. }
  70734. if (this.poleTargetBone) {
  70735. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  70736. }
  70737. else if (this.poleTargetMesh) {
  70738. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  70739. }
  70740. var bonePos = BoneIKController._tmpVecs[0];
  70741. var zaxis = BoneIKController._tmpVecs[1];
  70742. var xaxis = BoneIKController._tmpVecs[2];
  70743. var yaxis = BoneIKController._tmpVecs[3];
  70744. var upAxis = BoneIKController._tmpVecs[4];
  70745. var _tmpQuat = BoneIKController._tmpQuat;
  70746. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  70747. poleTarget.subtractToRef(bonePos, upAxis);
  70748. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  70749. upAxis.y = 1;
  70750. }
  70751. else {
  70752. upAxis.normalize();
  70753. }
  70754. target.subtractToRef(bonePos, yaxis);
  70755. yaxis.normalize();
  70756. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  70757. zaxis.normalize();
  70758. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  70759. xaxis.normalize();
  70760. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  70761. var a = this._bone1Length;
  70762. var b = this._bone2Length;
  70763. var c = BABYLON.Vector3.Distance(bonePos, target);
  70764. if (this._maxReach > 0) {
  70765. c = Math.min(this._maxReach, c);
  70766. }
  70767. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  70768. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  70769. if (acosa > 1) {
  70770. acosa = 1;
  70771. }
  70772. if (acosb > 1) {
  70773. acosb = 1;
  70774. }
  70775. if (acosa < -1) {
  70776. acosa = -1;
  70777. }
  70778. if (acosb < -1) {
  70779. acosb = -1;
  70780. }
  70781. var angA = Math.acos(acosa);
  70782. var angB = Math.acos(acosb);
  70783. var angC = -angA - angB;
  70784. if (this._rightHandedSystem) {
  70785. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  70786. mat2.multiplyToRef(mat1, mat1);
  70787. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  70788. mat2.multiplyToRef(mat1, mat1);
  70789. }
  70790. else {
  70791. var _tmpVec = BoneIKController._tmpVecs[5];
  70792. _tmpVec.copyFrom(this._bendAxis);
  70793. _tmpVec.x *= -1;
  70794. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  70795. mat2.multiplyToRef(mat1, mat1);
  70796. }
  70797. if (this.poleAngle) {
  70798. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  70799. mat1.multiplyToRef(mat2, mat1);
  70800. }
  70801. if (this._bone1) {
  70802. if (this.slerpAmount < 1) {
  70803. if (!this._slerping) {
  70804. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  70805. }
  70806. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  70807. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  70808. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  70809. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  70810. this._slerping = true;
  70811. }
  70812. else {
  70813. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  70814. this._bone1Mat.copyFrom(mat1);
  70815. this._slerping = false;
  70816. }
  70817. }
  70818. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  70819. this._bone2Ang = angC;
  70820. };
  70821. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  70822. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  70823. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  70824. return BoneIKController;
  70825. }());
  70826. BABYLON.BoneIKController = BoneIKController;
  70827. })(BABYLON || (BABYLON = {}));
  70828. //# sourceMappingURL=babylon.boneIKController.js.map
  70829. var BABYLON;
  70830. (function (BABYLON) {
  70831. var BoneLookController = /** @class */ (function () {
  70832. /**
  70833. * Create a BoneLookController
  70834. * @param mesh the mesh that the bone belongs to
  70835. * @param bone the bone that will be looking to the target
  70836. * @param target the target Vector3 to look at
  70837. * @param settings optional settings:
  70838. * - maxYaw: the maximum angle the bone will yaw to
  70839. * - minYaw: the minimum angle the bone will yaw to
  70840. * - maxPitch: the maximum angle the bone will pitch to
  70841. * - minPitch: the minimum angle the bone will yaw to
  70842. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  70843. * - upAxis: the up axis of the coordinate system
  70844. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  70845. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  70846. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  70847. * - adjustYaw: used to make an adjustment to the yaw of the bone
  70848. * - adjustPitch: used to make an adjustment to the pitch of the bone
  70849. * - adjustRoll: used to make an adjustment to the roll of the bone
  70850. **/
  70851. function BoneLookController(mesh, bone, target, options) {
  70852. /**
  70853. * The up axis of the coordinate system that is used when the bone is rotated.
  70854. */
  70855. this.upAxis = BABYLON.Vector3.Up();
  70856. /**
  70857. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  70858. */
  70859. this.upAxisSpace = BABYLON.Space.LOCAL;
  70860. /**
  70861. * Used to make an adjustment to the yaw of the bone.
  70862. */
  70863. this.adjustYaw = 0;
  70864. /**
  70865. * Used to make an adjustment to the pitch of the bone.
  70866. */
  70867. this.adjustPitch = 0;
  70868. /**
  70869. * Used to make an adjustment to the roll of the bone.
  70870. */
  70871. this.adjustRoll = 0;
  70872. /**
  70873. * 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).
  70874. */
  70875. this.slerpAmount = 1;
  70876. this._boneQuat = BABYLON.Quaternion.Identity();
  70877. this._slerping = false;
  70878. this._firstFrameSkipped = false;
  70879. this._fowardAxis = BABYLON.Vector3.Forward();
  70880. this.mesh = mesh;
  70881. this.bone = bone;
  70882. this.target = target;
  70883. if (options) {
  70884. if (options.adjustYaw) {
  70885. this.adjustYaw = options.adjustYaw;
  70886. }
  70887. if (options.adjustPitch) {
  70888. this.adjustPitch = options.adjustPitch;
  70889. }
  70890. if (options.adjustRoll) {
  70891. this.adjustRoll = options.adjustRoll;
  70892. }
  70893. if (options.maxYaw != null) {
  70894. this.maxYaw = options.maxYaw;
  70895. }
  70896. else {
  70897. this.maxYaw = Math.PI;
  70898. }
  70899. if (options.minYaw != null) {
  70900. this.minYaw = options.minYaw;
  70901. }
  70902. else {
  70903. this.minYaw = -Math.PI;
  70904. }
  70905. if (options.maxPitch != null) {
  70906. this.maxPitch = options.maxPitch;
  70907. }
  70908. else {
  70909. this.maxPitch = Math.PI;
  70910. }
  70911. if (options.minPitch != null) {
  70912. this.minPitch = options.minPitch;
  70913. }
  70914. else {
  70915. this.minPitch = -Math.PI;
  70916. }
  70917. if (options.slerpAmount != null) {
  70918. this.slerpAmount = options.slerpAmount;
  70919. }
  70920. if (options.upAxis != null) {
  70921. this.upAxis = options.upAxis;
  70922. }
  70923. if (options.upAxisSpace != null) {
  70924. this.upAxisSpace = options.upAxisSpace;
  70925. }
  70926. if (options.yawAxis != null || options.pitchAxis != null) {
  70927. var newYawAxis = BABYLON.Axis.Y;
  70928. var newPitchAxis = BABYLON.Axis.X;
  70929. if (options.yawAxis != null) {
  70930. newYawAxis = options.yawAxis.clone();
  70931. newYawAxis.normalize();
  70932. }
  70933. if (options.pitchAxis != null) {
  70934. newPitchAxis = options.pitchAxis.clone();
  70935. newPitchAxis.normalize();
  70936. }
  70937. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  70938. this._transformYawPitch = BABYLON.Matrix.Identity();
  70939. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  70940. this._transformYawPitchInv = this._transformYawPitch.clone();
  70941. this._transformYawPitch.invert();
  70942. }
  70943. }
  70944. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  70945. this.upAxisSpace = BABYLON.Space.LOCAL;
  70946. }
  70947. }
  70948. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  70949. /**
  70950. * Get/set the minimum yaw angle that the bone can look to.
  70951. */
  70952. get: function () {
  70953. return this._minYaw;
  70954. },
  70955. set: function (value) {
  70956. this._minYaw = value;
  70957. this._minYawSin = Math.sin(value);
  70958. this._minYawCos = Math.cos(value);
  70959. if (this._maxYaw != null) {
  70960. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  70961. this._yawRange = this._maxYaw - this._minYaw;
  70962. }
  70963. },
  70964. enumerable: true,
  70965. configurable: true
  70966. });
  70967. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  70968. /**
  70969. * Get/set the maximum yaw angle that the bone can look to.
  70970. */
  70971. get: function () {
  70972. return this._maxYaw;
  70973. },
  70974. set: function (value) {
  70975. this._maxYaw = value;
  70976. this._maxYawSin = Math.sin(value);
  70977. this._maxYawCos = Math.cos(value);
  70978. if (this._minYaw != null) {
  70979. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  70980. this._yawRange = this._maxYaw - this._minYaw;
  70981. }
  70982. },
  70983. enumerable: true,
  70984. configurable: true
  70985. });
  70986. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  70987. /**
  70988. * Get/set the minimum pitch angle that the bone can look to.
  70989. */
  70990. get: function () {
  70991. return this._minPitch;
  70992. },
  70993. set: function (value) {
  70994. this._minPitch = value;
  70995. this._minPitchTan = Math.tan(value);
  70996. },
  70997. enumerable: true,
  70998. configurable: true
  70999. });
  71000. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  71001. /**
  71002. * Get/set the maximum pitch angle that the bone can look to.
  71003. */
  71004. get: function () {
  71005. return this._maxPitch;
  71006. },
  71007. set: function (value) {
  71008. this._maxPitch = value;
  71009. this._maxPitchTan = Math.tan(value);
  71010. },
  71011. enumerable: true,
  71012. configurable: true
  71013. });
  71014. /**
  71015. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  71016. */
  71017. BoneLookController.prototype.update = function () {
  71018. //skip the first frame when slerping so that the mesh rotation is correct
  71019. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  71020. this._firstFrameSkipped = true;
  71021. return;
  71022. }
  71023. var bone = this.bone;
  71024. var bonePos = BoneLookController._tmpVecs[0];
  71025. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  71026. var target = this.target;
  71027. var _tmpMat1 = BoneLookController._tmpMats[0];
  71028. var _tmpMat2 = BoneLookController._tmpMats[1];
  71029. var mesh = this.mesh;
  71030. var parentBone = bone.getParent();
  71031. var upAxis = BoneLookController._tmpVecs[1];
  71032. upAxis.copyFrom(this.upAxis);
  71033. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  71034. if (this._transformYawPitch) {
  71035. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  71036. }
  71037. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  71038. }
  71039. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  71040. mesh.getDirectionToRef(upAxis, upAxis);
  71041. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  71042. upAxis.normalize();
  71043. }
  71044. }
  71045. var checkYaw = false;
  71046. var checkPitch = false;
  71047. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  71048. checkYaw = true;
  71049. }
  71050. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  71051. checkPitch = true;
  71052. }
  71053. if (checkYaw || checkPitch) {
  71054. var spaceMat = BoneLookController._tmpMats[2];
  71055. var spaceMatInv = BoneLookController._tmpMats[3];
  71056. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  71057. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  71058. }
  71059. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  71060. spaceMat.copyFrom(mesh.getWorldMatrix());
  71061. }
  71062. else {
  71063. var forwardAxis = BoneLookController._tmpVecs[2];
  71064. forwardAxis.copyFrom(this._fowardAxis);
  71065. if (this._transformYawPitch) {
  71066. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  71067. }
  71068. if (parentBone) {
  71069. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  71070. }
  71071. else {
  71072. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  71073. }
  71074. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  71075. rightAxis.normalize();
  71076. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  71077. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  71078. }
  71079. spaceMat.invertToRef(spaceMatInv);
  71080. var xzlen = null;
  71081. if (checkPitch) {
  71082. var localTarget = BoneLookController._tmpVecs[3];
  71083. target.subtractToRef(bonePos, localTarget);
  71084. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71085. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71086. var pitch = Math.atan2(localTarget.y, xzlen);
  71087. var newPitch = pitch;
  71088. if (pitch > this._maxPitch) {
  71089. localTarget.y = this._maxPitchTan * xzlen;
  71090. newPitch = this._maxPitch;
  71091. }
  71092. else if (pitch < this._minPitch) {
  71093. localTarget.y = this._minPitchTan * xzlen;
  71094. newPitch = this._minPitch;
  71095. }
  71096. if (pitch != newPitch) {
  71097. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71098. localTarget.addInPlace(bonePos);
  71099. target = localTarget;
  71100. }
  71101. }
  71102. if (checkYaw) {
  71103. var localTarget = BoneLookController._tmpVecs[4];
  71104. target.subtractToRef(bonePos, localTarget);
  71105. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  71106. var yaw = Math.atan2(localTarget.x, localTarget.z);
  71107. var newYaw = yaw;
  71108. if (yaw > this._maxYaw || yaw < this._minYaw) {
  71109. if (xzlen == null) {
  71110. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71111. }
  71112. if (this._yawRange > Math.PI) {
  71113. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  71114. localTarget.z = this._maxYawCos * xzlen;
  71115. localTarget.x = this._maxYawSin * xzlen;
  71116. newYaw = this._maxYaw;
  71117. }
  71118. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  71119. localTarget.z = this._minYawCos * xzlen;
  71120. localTarget.x = this._minYawSin * xzlen;
  71121. newYaw = this._minYaw;
  71122. }
  71123. }
  71124. else {
  71125. if (yaw > this._maxYaw) {
  71126. localTarget.z = this._maxYawCos * xzlen;
  71127. localTarget.x = this._maxYawSin * xzlen;
  71128. newYaw = this._maxYaw;
  71129. }
  71130. else if (yaw < this._minYaw) {
  71131. localTarget.z = this._minYawCos * xzlen;
  71132. localTarget.x = this._minYawSin * xzlen;
  71133. newYaw = this._minYaw;
  71134. }
  71135. }
  71136. }
  71137. if (this._slerping && this._yawRange > Math.PI) {
  71138. //are we going to be crossing into the min/max region?
  71139. var boneFwd = BoneLookController._tmpVecs[8];
  71140. boneFwd.copyFrom(BABYLON.Axis.Z);
  71141. if (this._transformYawPitch) {
  71142. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  71143. }
  71144. var boneRotMat = BoneLookController._tmpMats[4];
  71145. this._boneQuat.toRotationMatrix(boneRotMat);
  71146. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  71147. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  71148. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  71149. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  71150. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  71151. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  71152. if (angBtwTar > angBtwMidYaw) {
  71153. if (xzlen == null) {
  71154. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  71155. }
  71156. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  71157. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  71158. if (angBtwMin < angBtwMax) {
  71159. newYaw = boneYaw + Math.PI * .75;
  71160. localTarget.z = Math.cos(newYaw) * xzlen;
  71161. localTarget.x = Math.sin(newYaw) * xzlen;
  71162. }
  71163. else {
  71164. newYaw = boneYaw - Math.PI * .75;
  71165. localTarget.z = Math.cos(newYaw) * xzlen;
  71166. localTarget.x = Math.sin(newYaw) * xzlen;
  71167. }
  71168. }
  71169. }
  71170. if (yaw != newYaw) {
  71171. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  71172. localTarget.addInPlace(bonePos);
  71173. target = localTarget;
  71174. }
  71175. }
  71176. }
  71177. var zaxis = BoneLookController._tmpVecs[5];
  71178. var xaxis = BoneLookController._tmpVecs[6];
  71179. var yaxis = BoneLookController._tmpVecs[7];
  71180. var _tmpQuat = BoneLookController._tmpQuat;
  71181. target.subtractToRef(bonePos, zaxis);
  71182. zaxis.normalize();
  71183. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  71184. xaxis.normalize();
  71185. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  71186. yaxis.normalize();
  71187. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  71188. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  71189. return;
  71190. }
  71191. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  71192. return;
  71193. }
  71194. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  71195. return;
  71196. }
  71197. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  71198. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  71199. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  71200. }
  71201. if (this.slerpAmount < 1) {
  71202. if (!this._slerping) {
  71203. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  71204. }
  71205. if (this._transformYawPitch) {
  71206. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71207. }
  71208. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  71209. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  71210. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  71211. this._slerping = true;
  71212. }
  71213. else {
  71214. if (this._transformYawPitch) {
  71215. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  71216. }
  71217. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  71218. this._slerping = false;
  71219. }
  71220. };
  71221. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  71222. var angDiff = ang2 - ang1;
  71223. angDiff %= Math.PI * 2;
  71224. if (angDiff > Math.PI) {
  71225. angDiff -= Math.PI * 2;
  71226. }
  71227. else if (angDiff < -Math.PI) {
  71228. angDiff += Math.PI * 2;
  71229. }
  71230. return angDiff;
  71231. };
  71232. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  71233. ang1 %= (2 * Math.PI);
  71234. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71235. ang2 %= (2 * Math.PI);
  71236. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71237. var ab = 0;
  71238. if (ang1 < ang2) {
  71239. ab = ang2 - ang1;
  71240. }
  71241. else {
  71242. ab = ang1 - ang2;
  71243. }
  71244. if (ab > Math.PI) {
  71245. ab = Math.PI * 2 - ab;
  71246. }
  71247. return ab;
  71248. };
  71249. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  71250. ang %= (2 * Math.PI);
  71251. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  71252. ang1 %= (2 * Math.PI);
  71253. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  71254. ang2 %= (2 * Math.PI);
  71255. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  71256. if (ang1 < ang2) {
  71257. if (ang > ang1 && ang < ang2) {
  71258. return true;
  71259. }
  71260. }
  71261. else {
  71262. if (ang > ang2 && ang < ang1) {
  71263. return true;
  71264. }
  71265. }
  71266. return false;
  71267. };
  71268. 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()];
  71269. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  71270. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  71271. return BoneLookController;
  71272. }());
  71273. BABYLON.BoneLookController = BoneLookController;
  71274. })(BABYLON || (BABYLON = {}));
  71275. //# sourceMappingURL=babylon.boneLookController.js.map
  71276. var BABYLON;
  71277. (function (BABYLON) {
  71278. var Skeleton = /** @class */ (function () {
  71279. function Skeleton(name, id, scene) {
  71280. this.name = name;
  71281. this.id = id;
  71282. this.bones = new Array();
  71283. this.needInitialSkinMatrix = false;
  71284. this._isDirty = true;
  71285. this._meshesWithPoseMatrix = new Array();
  71286. this._identity = BABYLON.Matrix.Identity();
  71287. this._ranges = {};
  71288. this._lastAbsoluteTransformsUpdateId = -1;
  71289. /**
  71290. * Specifies if the skeleton should be serialized.
  71291. */
  71292. this.doNotSerialize = false;
  71293. // Events
  71294. /**
  71295. * An event triggered before computing the skeleton's matrices
  71296. * @type {BABYLON.Observable}
  71297. */
  71298. this.onBeforeComputeObservable = new BABYLON.Observable();
  71299. this.bones = [];
  71300. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  71301. scene.skeletons.push(this);
  71302. //make sure it will recalculate the matrix next time prepare is called.
  71303. this._isDirty = true;
  71304. }
  71305. // Members
  71306. Skeleton.prototype.getTransformMatrices = function (mesh) {
  71307. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  71308. return mesh._bonesTransformMatrices;
  71309. }
  71310. if (!this._transformMatrices) {
  71311. this.prepare();
  71312. }
  71313. return this._transformMatrices;
  71314. };
  71315. Skeleton.prototype.getScene = function () {
  71316. return this._scene;
  71317. };
  71318. // Methods
  71319. /**
  71320. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  71321. */
  71322. Skeleton.prototype.toString = function (fullDetails) {
  71323. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  71324. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  71325. if (fullDetails) {
  71326. ret += ", Ranges: {";
  71327. var first = true;
  71328. for (var name_1 in this._ranges) {
  71329. if (first) {
  71330. ret += ", ";
  71331. first = false;
  71332. }
  71333. ret += name_1;
  71334. }
  71335. ret += "}";
  71336. }
  71337. return ret;
  71338. };
  71339. /**
  71340. * Get bone's index searching by name
  71341. * @param {string} name is bone's name to search for
  71342. * @return {number} Indice of the bone. Returns -1 if not found
  71343. */
  71344. Skeleton.prototype.getBoneIndexByName = function (name) {
  71345. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  71346. if (this.bones[boneIndex].name === name) {
  71347. return boneIndex;
  71348. }
  71349. }
  71350. return -1;
  71351. };
  71352. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  71353. // check name not already in use
  71354. if (!this._ranges[name]) {
  71355. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  71356. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71357. if (this.bones[i].animations[0]) {
  71358. this.bones[i].animations[0].createRange(name, from, to);
  71359. }
  71360. }
  71361. }
  71362. };
  71363. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  71364. if (deleteFrames === void 0) { deleteFrames = true; }
  71365. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71366. if (this.bones[i].animations[0]) {
  71367. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  71368. }
  71369. }
  71370. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  71371. };
  71372. Skeleton.prototype.getAnimationRange = function (name) {
  71373. return this._ranges[name];
  71374. };
  71375. /**
  71376. * Returns as an Array, all AnimationRanges defined on this skeleton
  71377. */
  71378. Skeleton.prototype.getAnimationRanges = function () {
  71379. var animationRanges = [];
  71380. var name;
  71381. var i = 0;
  71382. for (name in this._ranges) {
  71383. animationRanges[i] = this._ranges[name];
  71384. i++;
  71385. }
  71386. return animationRanges;
  71387. };
  71388. /**
  71389. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  71390. */
  71391. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  71392. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  71393. if (this._ranges[name] || !source.getAnimationRange(name)) {
  71394. return false;
  71395. }
  71396. var ret = true;
  71397. var frameOffset = this._getHighestAnimationFrame() + 1;
  71398. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  71399. var boneDict = {};
  71400. var sourceBones = source.bones;
  71401. var nBones;
  71402. var i;
  71403. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  71404. boneDict[sourceBones[i].name] = sourceBones[i];
  71405. }
  71406. if (this.bones.length !== sourceBones.length) {
  71407. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  71408. ret = false;
  71409. }
  71410. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  71411. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  71412. var boneName = this.bones[i].name;
  71413. var sourceBone = boneDict[boneName];
  71414. if (sourceBone) {
  71415. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  71416. }
  71417. else {
  71418. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  71419. ret = false;
  71420. }
  71421. }
  71422. // do not call createAnimationRange(), since it also is done to bones, which was already done
  71423. var range = source.getAnimationRange(name);
  71424. if (range) {
  71425. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  71426. }
  71427. return ret;
  71428. };
  71429. Skeleton.prototype.returnToRest = function () {
  71430. for (var index = 0; index < this.bones.length; index++) {
  71431. this.bones[index].returnToRest();
  71432. }
  71433. };
  71434. Skeleton.prototype._getHighestAnimationFrame = function () {
  71435. var ret = 0;
  71436. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  71437. if (this.bones[i].animations[0]) {
  71438. var highest = this.bones[i].animations[0].getHighestFrame();
  71439. if (ret < highest) {
  71440. ret = highest;
  71441. }
  71442. }
  71443. }
  71444. return ret;
  71445. };
  71446. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  71447. var range = this.getAnimationRange(name);
  71448. if (!range) {
  71449. return null;
  71450. }
  71451. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  71452. };
  71453. Skeleton.prototype._markAsDirty = function () {
  71454. this._isDirty = true;
  71455. };
  71456. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  71457. this._meshesWithPoseMatrix.push(mesh);
  71458. };
  71459. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  71460. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  71461. if (index > -1) {
  71462. this._meshesWithPoseMatrix.splice(index, 1);
  71463. }
  71464. };
  71465. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  71466. this.onBeforeComputeObservable.notifyObservers(this);
  71467. for (var index = 0; index < this.bones.length; index++) {
  71468. var bone = this.bones[index];
  71469. var parentBone = bone.getParent();
  71470. if (parentBone) {
  71471. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  71472. }
  71473. else {
  71474. if (initialSkinMatrix) {
  71475. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  71476. }
  71477. else {
  71478. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  71479. }
  71480. }
  71481. if (bone._index !== -1) {
  71482. var mappedIndex = bone._index === null ? index : bone._index;
  71483. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  71484. }
  71485. }
  71486. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  71487. };
  71488. Skeleton.prototype.prepare = function () {
  71489. if (!this._isDirty) {
  71490. return;
  71491. }
  71492. if (this.needInitialSkinMatrix) {
  71493. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  71494. var mesh = this._meshesWithPoseMatrix[index];
  71495. var poseMatrix = mesh.getPoseMatrix();
  71496. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  71497. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  71498. }
  71499. if (this._synchronizedWithMesh !== mesh) {
  71500. this._synchronizedWithMesh = mesh;
  71501. // Prepare bones
  71502. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  71503. var bone = this.bones[boneIndex];
  71504. if (!bone.getParent()) {
  71505. var matrix = bone.getBaseMatrix();
  71506. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  71507. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  71508. }
  71509. }
  71510. }
  71511. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  71512. }
  71513. }
  71514. else {
  71515. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  71516. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  71517. }
  71518. this._computeTransformMatrices(this._transformMatrices, null);
  71519. }
  71520. this._isDirty = false;
  71521. this._scene._activeBones.addCount(this.bones.length, false);
  71522. };
  71523. Skeleton.prototype.getAnimatables = function () {
  71524. if (!this._animatables || this._animatables.length !== this.bones.length) {
  71525. this._animatables = [];
  71526. for (var index = 0; index < this.bones.length; index++) {
  71527. this._animatables.push(this.bones[index]);
  71528. }
  71529. }
  71530. return this._animatables;
  71531. };
  71532. Skeleton.prototype.clone = function (name, id) {
  71533. var result = new Skeleton(name, id || name, this._scene);
  71534. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  71535. for (var index = 0; index < this.bones.length; index++) {
  71536. var source = this.bones[index];
  71537. var parentBone = null;
  71538. var parent_1 = source.getParent();
  71539. if (parent_1) {
  71540. var parentIndex = this.bones.indexOf(parent_1);
  71541. parentBone = result.bones[parentIndex];
  71542. }
  71543. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  71544. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  71545. }
  71546. if (this._ranges) {
  71547. result._ranges = {};
  71548. for (var rangeName in this._ranges) {
  71549. var range = this._ranges[rangeName];
  71550. if (range) {
  71551. result._ranges[rangeName] = range.clone();
  71552. }
  71553. }
  71554. }
  71555. this._isDirty = true;
  71556. return result;
  71557. };
  71558. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  71559. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  71560. this.bones.forEach(function (bone) {
  71561. bone.animations.forEach(function (animation) {
  71562. animation.enableBlending = true;
  71563. animation.blendingSpeed = blendingSpeed;
  71564. });
  71565. });
  71566. };
  71567. Skeleton.prototype.dispose = function () {
  71568. this._meshesWithPoseMatrix = [];
  71569. // Animations
  71570. this.getScene().stopAnimation(this);
  71571. // Remove from scene
  71572. this.getScene().removeSkeleton(this);
  71573. };
  71574. Skeleton.prototype.serialize = function () {
  71575. var serializationObject = {};
  71576. serializationObject.name = this.name;
  71577. serializationObject.id = this.id;
  71578. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  71579. serializationObject.bones = [];
  71580. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  71581. for (var index = 0; index < this.bones.length; index++) {
  71582. var bone = this.bones[index];
  71583. var parent_2 = bone.getParent();
  71584. var serializedBone = {
  71585. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  71586. name: bone.name,
  71587. matrix: bone.getBaseMatrix().toArray(),
  71588. rest: bone.getRestPose().toArray()
  71589. };
  71590. serializationObject.bones.push(serializedBone);
  71591. if (bone.length) {
  71592. serializedBone.length = bone.length;
  71593. }
  71594. if (bone.animations && bone.animations.length > 0) {
  71595. serializedBone.animation = bone.animations[0].serialize();
  71596. }
  71597. serializationObject.ranges = [];
  71598. for (var name in this._ranges) {
  71599. var source = this._ranges[name];
  71600. if (!source) {
  71601. continue;
  71602. }
  71603. var range = {};
  71604. range.name = name;
  71605. range.from = source.from;
  71606. range.to = source.to;
  71607. serializationObject.ranges.push(range);
  71608. }
  71609. }
  71610. return serializationObject;
  71611. };
  71612. Skeleton.Parse = function (parsedSkeleton, scene) {
  71613. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  71614. if (parsedSkeleton.dimensionsAtRest) {
  71615. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  71616. }
  71617. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  71618. var index;
  71619. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  71620. var parsedBone = parsedSkeleton.bones[index];
  71621. var parentBone = null;
  71622. if (parsedBone.parentBoneIndex > -1) {
  71623. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  71624. }
  71625. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  71626. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  71627. if (parsedBone.length) {
  71628. bone.length = parsedBone.length;
  71629. }
  71630. if (parsedBone.animation) {
  71631. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  71632. }
  71633. }
  71634. // placed after bones, so createAnimationRange can cascade down
  71635. if (parsedSkeleton.ranges) {
  71636. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  71637. var data = parsedSkeleton.ranges[index];
  71638. skeleton.createAnimationRange(data.name, data.from, data.to);
  71639. }
  71640. }
  71641. return skeleton;
  71642. };
  71643. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  71644. if (forceUpdate === void 0) { forceUpdate = false; }
  71645. var renderId = this._scene.getRenderId();
  71646. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  71647. this.bones[0].computeAbsoluteTransforms();
  71648. this._lastAbsoluteTransformsUpdateId = renderId;
  71649. }
  71650. };
  71651. Skeleton.prototype.getPoseMatrix = function () {
  71652. var poseMatrix = null;
  71653. if (this._meshesWithPoseMatrix.length > 0) {
  71654. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  71655. }
  71656. return poseMatrix;
  71657. };
  71658. Skeleton.prototype.sortBones = function () {
  71659. var bones = new Array();
  71660. var visited = new Array(this.bones.length);
  71661. for (var index = 0; index < this.bones.length; index++) {
  71662. this._sortBones(index, bones, visited);
  71663. }
  71664. this.bones = bones;
  71665. };
  71666. Skeleton.prototype._sortBones = function (index, bones, visited) {
  71667. if (visited[index]) {
  71668. return;
  71669. }
  71670. visited[index] = true;
  71671. var bone = this.bones[index];
  71672. if (bone._index === undefined) {
  71673. bone._index = index;
  71674. }
  71675. var parentBone = bone.getParent();
  71676. if (parentBone) {
  71677. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  71678. }
  71679. bones.push(bone);
  71680. };
  71681. return Skeleton;
  71682. }());
  71683. BABYLON.Skeleton = Skeleton;
  71684. })(BABYLON || (BABYLON = {}));
  71685. //# sourceMappingURL=babylon.skeleton.js.map
  71686. var BABYLON;
  71687. (function (BABYLON) {
  71688. var SphericalPolynomial = /** @class */ (function () {
  71689. function SphericalPolynomial() {
  71690. this.x = BABYLON.Vector3.Zero();
  71691. this.y = BABYLON.Vector3.Zero();
  71692. this.z = BABYLON.Vector3.Zero();
  71693. this.xx = BABYLON.Vector3.Zero();
  71694. this.yy = BABYLON.Vector3.Zero();
  71695. this.zz = BABYLON.Vector3.Zero();
  71696. this.xy = BABYLON.Vector3.Zero();
  71697. this.yz = BABYLON.Vector3.Zero();
  71698. this.zx = BABYLON.Vector3.Zero();
  71699. }
  71700. SphericalPolynomial.prototype.addAmbient = function (color) {
  71701. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  71702. this.xx = this.xx.add(colorVector);
  71703. this.yy = this.yy.add(colorVector);
  71704. this.zz = this.zz.add(colorVector);
  71705. };
  71706. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  71707. var result = new SphericalPolynomial();
  71708. result.x = harmonics.L11.scale(1.02333);
  71709. result.y = harmonics.L1_1.scale(1.02333);
  71710. result.z = harmonics.L10.scale(1.02333);
  71711. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  71712. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  71713. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  71714. result.yz = harmonics.L2_1.scale(0.858086);
  71715. result.zx = harmonics.L21.scale(0.858086);
  71716. result.xy = harmonics.L2_2.scale(0.858086);
  71717. result.scale(1.0 / Math.PI);
  71718. return result;
  71719. };
  71720. SphericalPolynomial.prototype.scale = function (scale) {
  71721. this.x = this.x.scale(scale);
  71722. this.y = this.y.scale(scale);
  71723. this.z = this.z.scale(scale);
  71724. this.xx = this.xx.scale(scale);
  71725. this.yy = this.yy.scale(scale);
  71726. this.zz = this.zz.scale(scale);
  71727. this.yz = this.yz.scale(scale);
  71728. this.zx = this.zx.scale(scale);
  71729. this.xy = this.xy.scale(scale);
  71730. };
  71731. return SphericalPolynomial;
  71732. }());
  71733. BABYLON.SphericalPolynomial = SphericalPolynomial;
  71734. var SphericalHarmonics = /** @class */ (function () {
  71735. function SphericalHarmonics() {
  71736. this.L00 = BABYLON.Vector3.Zero();
  71737. this.L1_1 = BABYLON.Vector3.Zero();
  71738. this.L10 = BABYLON.Vector3.Zero();
  71739. this.L11 = BABYLON.Vector3.Zero();
  71740. this.L2_2 = BABYLON.Vector3.Zero();
  71741. this.L2_1 = BABYLON.Vector3.Zero();
  71742. this.L20 = BABYLON.Vector3.Zero();
  71743. this.L21 = BABYLON.Vector3.Zero();
  71744. this.L22 = BABYLON.Vector3.Zero();
  71745. }
  71746. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  71747. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  71748. var c = colorVector.scale(deltaSolidAngle);
  71749. this.L00 = this.L00.add(c.scale(0.282095));
  71750. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  71751. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  71752. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  71753. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  71754. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  71755. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  71756. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  71757. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  71758. };
  71759. SphericalHarmonics.prototype.scale = function (scale) {
  71760. this.L00 = this.L00.scale(scale);
  71761. this.L1_1 = this.L1_1.scale(scale);
  71762. this.L10 = this.L10.scale(scale);
  71763. this.L11 = this.L11.scale(scale);
  71764. this.L2_2 = this.L2_2.scale(scale);
  71765. this.L2_1 = this.L2_1.scale(scale);
  71766. this.L20 = this.L20.scale(scale);
  71767. this.L21 = this.L21.scale(scale);
  71768. this.L22 = this.L22.scale(scale);
  71769. };
  71770. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  71771. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  71772. //
  71773. // E_lm = A_l * L_lm
  71774. //
  71775. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  71776. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  71777. // the scaling factors are given in equation 9.
  71778. // Constant (Band 0)
  71779. this.L00 = this.L00.scale(3.141593);
  71780. // Linear (Band 1)
  71781. this.L1_1 = this.L1_1.scale(2.094395);
  71782. this.L10 = this.L10.scale(2.094395);
  71783. this.L11 = this.L11.scale(2.094395);
  71784. // Quadratic (Band 2)
  71785. this.L2_2 = this.L2_2.scale(0.785398);
  71786. this.L2_1 = this.L2_1.scale(0.785398);
  71787. this.L20 = this.L20.scale(0.785398);
  71788. this.L21 = this.L21.scale(0.785398);
  71789. this.L22 = this.L22.scale(0.785398);
  71790. };
  71791. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  71792. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  71793. // L = (1/pi) * E * rho
  71794. //
  71795. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  71796. this.scale(1.0 / Math.PI);
  71797. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  71798. // (The pixel shader must apply albedo after texture fetches, etc).
  71799. };
  71800. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  71801. var result = new SphericalHarmonics();
  71802. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  71803. result.L1_1 = polynomial.y.scale(0.977204);
  71804. result.L10 = polynomial.z.scale(0.977204);
  71805. result.L11 = polynomial.x.scale(0.977204);
  71806. result.L2_2 = polynomial.xy.scale(1.16538);
  71807. result.L2_1 = polynomial.yz.scale(1.16538);
  71808. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  71809. result.L21 = polynomial.zx.scale(1.16538);
  71810. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  71811. result.scale(Math.PI);
  71812. return result;
  71813. };
  71814. return SphericalHarmonics;
  71815. }());
  71816. BABYLON.SphericalHarmonics = SphericalHarmonics;
  71817. })(BABYLON || (BABYLON = {}));
  71818. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  71819. var BABYLON;
  71820. (function (BABYLON) {
  71821. var FileFaceOrientation = /** @class */ (function () {
  71822. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  71823. this.name = name;
  71824. this.worldAxisForNormal = worldAxisForNormal;
  71825. this.worldAxisForFileX = worldAxisForFileX;
  71826. this.worldAxisForFileY = worldAxisForFileY;
  71827. }
  71828. return FileFaceOrientation;
  71829. }());
  71830. ;
  71831. /**
  71832. * Helper class dealing with the extraction of spherical polynomial dataArray
  71833. * from a cube map.
  71834. */
  71835. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  71836. function CubeMapToSphericalPolynomialTools() {
  71837. }
  71838. /**
  71839. * Converts a texture to the according Spherical Polynomial data.
  71840. * This extracts the first 3 orders only as they are the only one used in the lighting.
  71841. *
  71842. * @param texture The texture to extract the information from.
  71843. * @return The Spherical Polynomial data.
  71844. */
  71845. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  71846. if (!texture.isCube) {
  71847. // Only supports cube Textures currently.
  71848. return null;
  71849. }
  71850. var size = texture.getSize().width;
  71851. var right = texture.readPixels(0);
  71852. var left = texture.readPixels(1);
  71853. var up;
  71854. var down;
  71855. if (texture.isRenderTarget) {
  71856. up = texture.readPixels(3);
  71857. down = texture.readPixels(2);
  71858. }
  71859. else {
  71860. up = texture.readPixels(2);
  71861. down = texture.readPixels(3);
  71862. }
  71863. var front = texture.readPixels(4);
  71864. var back = texture.readPixels(5);
  71865. var gammaSpace = texture.gammaSpace;
  71866. // Always read as RGBA.
  71867. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  71868. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  71869. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  71870. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  71871. }
  71872. var cubeInfo = {
  71873. size: size,
  71874. right: right,
  71875. left: left,
  71876. up: up,
  71877. down: down,
  71878. front: front,
  71879. back: back,
  71880. format: format,
  71881. type: type,
  71882. gammaSpace: gammaSpace,
  71883. };
  71884. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  71885. };
  71886. /**
  71887. * Converts a cubemap to the according Spherical Polynomial data.
  71888. * This extracts the first 3 orders only as they are the only one used in the lighting.
  71889. *
  71890. * @param cubeInfo The Cube map to extract the information from.
  71891. * @return The Spherical Polynomial data.
  71892. */
  71893. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  71894. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  71895. var totalSolidAngle = 0.0;
  71896. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  71897. var du = 2.0 / cubeInfo.size;
  71898. var dv = du;
  71899. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  71900. var minUV = du * 0.5 - 1.0;
  71901. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  71902. var fileFace = this.FileFaces[faceIndex];
  71903. var dataArray = cubeInfo[fileFace.name];
  71904. var v = minUV;
  71905. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  71906. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  71907. // Because SP is still linear, so summation is fine in that basis.
  71908. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  71909. for (var y = 0; y < cubeInfo.size; y++) {
  71910. var u = minUV;
  71911. for (var x = 0; x < cubeInfo.size; x++) {
  71912. // World direction (not normalised)
  71913. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  71914. worldDirection.normalize();
  71915. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  71916. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  71917. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  71918. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  71919. // Handle Integer types.
  71920. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  71921. r /= 255;
  71922. g /= 255;
  71923. b /= 255;
  71924. }
  71925. // Handle Gamma space textures.
  71926. if (cubeInfo.gammaSpace) {
  71927. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  71928. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  71929. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  71930. }
  71931. var color = new BABYLON.Color3(r, g, b);
  71932. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  71933. totalSolidAngle += deltaSolidAngle;
  71934. u += du;
  71935. }
  71936. v += dv;
  71937. }
  71938. }
  71939. // Solid angle for entire sphere is 4*pi
  71940. var sphereSolidAngle = 4.0 * Math.PI;
  71941. // Adjust the solid angle to allow for how many faces we processed.
  71942. var facesProcessed = 6.0;
  71943. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  71944. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  71945. // This is needed because the numerical integration over the cube uses a
  71946. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  71947. // and also to compensate for accumulative error due to float precision in the summation.
  71948. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  71949. sphericalHarmonics.scale(correctionFactor);
  71950. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  71951. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  71952. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  71953. };
  71954. CubeMapToSphericalPolynomialTools.FileFaces = [
  71955. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  71956. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  71957. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  71958. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  71959. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  71960. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  71961. ];
  71962. return CubeMapToSphericalPolynomialTools;
  71963. }());
  71964. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  71965. })(BABYLON || (BABYLON = {}));
  71966. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  71967. var BABYLON;
  71968. (function (BABYLON) {
  71969. /**
  71970. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  71971. */
  71972. var PanoramaToCubeMapTools = /** @class */ (function () {
  71973. function PanoramaToCubeMapTools() {
  71974. }
  71975. /**
  71976. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  71977. *
  71978. * @param float32Array The source data.
  71979. * @param inputWidth The width of the input panorama.
  71980. * @param inputhHeight The height of the input panorama.
  71981. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  71982. * @return The cubemap data
  71983. */
  71984. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  71985. if (!float32Array) {
  71986. throw "ConvertPanoramaToCubemap: input cannot be null";
  71987. }
  71988. if (float32Array.length != inputWidth * inputHeight * 3) {
  71989. throw "ConvertPanoramaToCubemap: input size is wrong";
  71990. }
  71991. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  71992. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  71993. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  71994. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  71995. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  71996. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  71997. return {
  71998. front: textureFront,
  71999. back: textureBack,
  72000. left: textureLeft,
  72001. right: textureRight,
  72002. up: textureUp,
  72003. down: textureDown,
  72004. size: size,
  72005. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  72006. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  72007. gammaSpace: false,
  72008. };
  72009. };
  72010. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  72011. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  72012. var textureArray = new Float32Array(buffer);
  72013. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  72014. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  72015. var dy = 1 / texSize;
  72016. var fy = 0;
  72017. for (var y = 0; y < texSize; y++) {
  72018. var xv1 = faceData[0];
  72019. var xv2 = faceData[2];
  72020. for (var x = 0; x < texSize; x++) {
  72021. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  72022. v.normalize();
  72023. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  72024. // 3 channels per pixels
  72025. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  72026. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  72027. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  72028. xv1 = xv1.add(rotDX1);
  72029. xv2 = xv2.add(rotDX2);
  72030. }
  72031. fy += dy;
  72032. }
  72033. return textureArray;
  72034. };
  72035. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  72036. var theta = Math.atan2(vDir.z, vDir.x);
  72037. var phi = Math.acos(vDir.y);
  72038. while (theta < -Math.PI)
  72039. theta += 2 * Math.PI;
  72040. while (theta > Math.PI)
  72041. theta -= 2 * Math.PI;
  72042. var dx = theta / Math.PI;
  72043. var dy = phi / Math.PI;
  72044. // recenter.
  72045. dx = dx * 0.5 + 0.5;
  72046. var px = Math.round(dx * inputWidth);
  72047. if (px < 0)
  72048. px = 0;
  72049. else if (px >= inputWidth)
  72050. px = inputWidth - 1;
  72051. var py = Math.round(dy * inputHeight);
  72052. if (py < 0)
  72053. py = 0;
  72054. else if (py >= inputHeight)
  72055. py = inputHeight - 1;
  72056. var inputY = (inputHeight - py - 1);
  72057. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  72058. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  72059. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  72060. return {
  72061. r: r,
  72062. g: g,
  72063. b: b
  72064. };
  72065. };
  72066. PanoramaToCubeMapTools.FACE_FRONT = [
  72067. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72068. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72069. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72070. new BABYLON.Vector3(1.0, 1.0, -1.0)
  72071. ];
  72072. PanoramaToCubeMapTools.FACE_BACK = [
  72073. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72074. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72075. new BABYLON.Vector3(1.0, 1.0, 1.0),
  72076. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  72077. ];
  72078. PanoramaToCubeMapTools.FACE_RIGHT = [
  72079. new BABYLON.Vector3(1.0, -1.0, -1.0),
  72080. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72081. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72082. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72083. ];
  72084. PanoramaToCubeMapTools.FACE_LEFT = [
  72085. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72086. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72087. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72088. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  72089. ];
  72090. PanoramaToCubeMapTools.FACE_DOWN = [
  72091. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  72092. new BABYLON.Vector3(1.0, 1.0, -1.0),
  72093. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  72094. new BABYLON.Vector3(1.0, 1.0, 1.0)
  72095. ];
  72096. PanoramaToCubeMapTools.FACE_UP = [
  72097. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  72098. new BABYLON.Vector3(1.0, -1.0, 1.0),
  72099. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  72100. new BABYLON.Vector3(1.0, -1.0, -1.0)
  72101. ];
  72102. return PanoramaToCubeMapTools;
  72103. }());
  72104. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  72105. })(BABYLON || (BABYLON = {}));
  72106. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  72107. var BABYLON;
  72108. (function (BABYLON) {
  72109. ;
  72110. /**
  72111. * This groups tools to convert HDR texture to native colors array.
  72112. */
  72113. var HDRTools = /** @class */ (function () {
  72114. function HDRTools() {
  72115. }
  72116. HDRTools.Ldexp = function (mantissa, exponent) {
  72117. if (exponent > 1023) {
  72118. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  72119. }
  72120. if (exponent < -1074) {
  72121. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  72122. }
  72123. return mantissa * Math.pow(2, exponent);
  72124. };
  72125. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  72126. if (exponent > 0) {
  72127. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  72128. float32array[index + 0] = red * exponent;
  72129. float32array[index + 1] = green * exponent;
  72130. float32array[index + 2] = blue * exponent;
  72131. }
  72132. else {
  72133. float32array[index + 0] = 0;
  72134. float32array[index + 1] = 0;
  72135. float32array[index + 2] = 0;
  72136. }
  72137. };
  72138. HDRTools.readStringLine = function (uint8array, startIndex) {
  72139. var line = "";
  72140. var character = "";
  72141. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  72142. character = String.fromCharCode(uint8array[i]);
  72143. if (character == "\n") {
  72144. break;
  72145. }
  72146. line += character;
  72147. }
  72148. return line;
  72149. };
  72150. /**
  72151. * Reads header information from an RGBE texture stored in a native array.
  72152. * More information on this format are available here:
  72153. * https://en.wikipedia.org/wiki/RGBE_image_format
  72154. *
  72155. * @param uint8array The binary file stored in native array.
  72156. * @return The header information.
  72157. */
  72158. HDRTools.RGBE_ReadHeader = function (uint8array) {
  72159. var height = 0;
  72160. var width = 0;
  72161. var line = this.readStringLine(uint8array, 0);
  72162. if (line[0] != '#' || line[1] != '?') {
  72163. throw "Bad HDR Format.";
  72164. }
  72165. var endOfHeader = false;
  72166. var findFormat = false;
  72167. var lineIndex = 0;
  72168. do {
  72169. lineIndex += (line.length + 1);
  72170. line = this.readStringLine(uint8array, lineIndex);
  72171. if (line == "FORMAT=32-bit_rle_rgbe") {
  72172. findFormat = true;
  72173. }
  72174. else if (line.length == 0) {
  72175. endOfHeader = true;
  72176. }
  72177. } while (!endOfHeader);
  72178. if (!findFormat) {
  72179. throw "HDR Bad header format, unsupported FORMAT";
  72180. }
  72181. lineIndex += (line.length + 1);
  72182. line = this.readStringLine(uint8array, lineIndex);
  72183. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  72184. var match = sizeRegexp.exec(line);
  72185. // TODO. Support +Y and -X if needed.
  72186. if (!match || match.length < 3) {
  72187. throw "HDR Bad header format, no size";
  72188. }
  72189. width = parseInt(match[2]);
  72190. height = parseInt(match[1]);
  72191. if (width < 8 || width > 0x7fff) {
  72192. throw "HDR Bad header format, unsupported size";
  72193. }
  72194. lineIndex += (line.length + 1);
  72195. return {
  72196. height: height,
  72197. width: width,
  72198. dataPosition: lineIndex
  72199. };
  72200. };
  72201. /**
  72202. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  72203. * This RGBE texture needs to store the information as a panorama.
  72204. *
  72205. * More information on this format are available here:
  72206. * https://en.wikipedia.org/wiki/RGBE_image_format
  72207. *
  72208. * @param buffer The binary file stored in an array buffer.
  72209. * @param size The expected size of the extracted cubemap.
  72210. * @return The Cube Map information.
  72211. */
  72212. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  72213. var uint8array = new Uint8Array(buffer);
  72214. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  72215. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72216. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  72217. return cubeMapData;
  72218. };
  72219. /**
  72220. * Returns the pixels data extracted from an RGBE texture.
  72221. * This pixels will be stored left to right up to down in the R G B order in one array.
  72222. *
  72223. * More information on this format are available here:
  72224. * https://en.wikipedia.org/wiki/RGBE_image_format
  72225. *
  72226. * @param uint8array The binary file stored in an array buffer.
  72227. * @param hdrInfo The header information of the file.
  72228. * @return The pixels data in RGB right to left up to down order.
  72229. */
  72230. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  72231. // Keep for multi format supports.
  72232. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  72233. };
  72234. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  72235. var num_scanlines = hdrInfo.height;
  72236. var scanline_width = hdrInfo.width;
  72237. var a, b, c, d, count;
  72238. var dataIndex = hdrInfo.dataPosition;
  72239. var index = 0, endIndex = 0, i = 0;
  72240. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  72241. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  72242. // 3 channels of 4 bytes per pixel in float.
  72243. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  72244. var resultArray = new Float32Array(resultBuffer);
  72245. // read in each successive scanline
  72246. while (num_scanlines > 0) {
  72247. a = uint8array[dataIndex++];
  72248. b = uint8array[dataIndex++];
  72249. c = uint8array[dataIndex++];
  72250. d = uint8array[dataIndex++];
  72251. if (a != 2 || b != 2 || (c & 0x80)) {
  72252. // this file is not run length encoded
  72253. throw "HDR Bad header format, not RLE";
  72254. }
  72255. if (((c << 8) | d) != scanline_width) {
  72256. throw "HDR Bad header format, wrong scan line width";
  72257. }
  72258. index = 0;
  72259. // read each of the four channels for the scanline into the buffer
  72260. for (i = 0; i < 4; i++) {
  72261. endIndex = (i + 1) * scanline_width;
  72262. while (index < endIndex) {
  72263. a = uint8array[dataIndex++];
  72264. b = uint8array[dataIndex++];
  72265. if (a > 128) {
  72266. // a run of the same value
  72267. count = a - 128;
  72268. if ((count == 0) || (count > endIndex - index)) {
  72269. throw "HDR Bad Format, bad scanline data (run)";
  72270. }
  72271. while (count-- > 0) {
  72272. scanLineArray[index++] = b;
  72273. }
  72274. }
  72275. else {
  72276. // a non-run
  72277. count = a;
  72278. if ((count == 0) || (count > endIndex - index)) {
  72279. throw "HDR Bad Format, bad scanline data (non-run)";
  72280. }
  72281. scanLineArray[index++] = b;
  72282. if (--count > 0) {
  72283. for (var j = 0; j < count; j++) {
  72284. scanLineArray[index++] = uint8array[dataIndex++];
  72285. }
  72286. }
  72287. }
  72288. }
  72289. }
  72290. // now convert data from buffer into floats
  72291. for (i = 0; i < scanline_width; i++) {
  72292. a = scanLineArray[i];
  72293. b = scanLineArray[i + scanline_width];
  72294. c = scanLineArray[i + 2 * scanline_width];
  72295. d = scanLineArray[i + 3 * scanline_width];
  72296. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  72297. }
  72298. num_scanlines--;
  72299. }
  72300. return resultArray;
  72301. };
  72302. return HDRTools;
  72303. }());
  72304. BABYLON.HDRTools = HDRTools;
  72305. })(BABYLON || (BABYLON = {}));
  72306. //# sourceMappingURL=babylon.hdr.js.map
  72307. var BABYLON;
  72308. (function (BABYLON) {
  72309. /**
  72310. * This represents a texture coming from an HDR input.
  72311. *
  72312. * The only supported format is currently panorama picture stored in RGBE format.
  72313. * Example of such files can be found on HDRLib: http://hdrlib.com/
  72314. */
  72315. var HDRCubeTexture = /** @class */ (function (_super) {
  72316. __extends(HDRCubeTexture, _super);
  72317. /**
  72318. * Instantiates an HDRTexture from the following parameters.
  72319. *
  72320. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  72321. * @param scene The scene the texture will be used in
  72322. * @param size The cubemap 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.
  72323. * @param noMipmap Forces to not generate the mipmap if true
  72324. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  72325. * @param useInGammaSpace 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)
  72326. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  72327. */
  72328. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  72329. if (noMipmap === void 0) { noMipmap = false; }
  72330. if (generateHarmonics === void 0) { generateHarmonics = true; }
  72331. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  72332. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  72333. if (onLoad === void 0) { onLoad = null; }
  72334. if (onError === void 0) { onError = null; }
  72335. var _this = _super.call(this, scene) || this;
  72336. _this._useInGammaSpace = false;
  72337. _this._generateHarmonics = true;
  72338. _this._isBABYLONPreprocessed = false;
  72339. _this._onLoad = null;
  72340. _this._onError = null;
  72341. /**
  72342. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  72343. */
  72344. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  72345. /**
  72346. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  72347. * This is usefull at run time to apply the good shader.
  72348. */
  72349. _this.isPMREM = false;
  72350. _this._isBlocking = true;
  72351. if (!url) {
  72352. return _this;
  72353. }
  72354. _this.name = url;
  72355. _this.url = url;
  72356. _this.hasAlpha = false;
  72357. _this.isCube = true;
  72358. _this._textureMatrix = BABYLON.Matrix.Identity();
  72359. _this._onLoad = onLoad;
  72360. _this._onError = onError;
  72361. _this.gammaSpace = false;
  72362. var caps = scene.getEngine().getCaps();
  72363. if (size) {
  72364. _this._isBABYLONPreprocessed = false;
  72365. _this._noMipmap = noMipmap;
  72366. _this._size = size;
  72367. _this._useInGammaSpace = useInGammaSpace;
  72368. _this._usePMREMGenerator = usePMREMGenerator &&
  72369. caps.textureLOD &&
  72370. caps.textureFloat &&
  72371. !_this._useInGammaSpace;
  72372. }
  72373. else {
  72374. _this._isBABYLONPreprocessed = true;
  72375. _this._noMipmap = false;
  72376. _this._useInGammaSpace = false;
  72377. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  72378. !_this._useInGammaSpace;
  72379. }
  72380. _this.isPMREM = _this._usePMREMGenerator;
  72381. _this._texture = _this._getFromCache(url, _this._noMipmap);
  72382. if (!_this._texture) {
  72383. if (!scene.useDelayedTextureLoading) {
  72384. _this.loadTexture();
  72385. }
  72386. else {
  72387. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  72388. }
  72389. }
  72390. return _this;
  72391. }
  72392. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  72393. /**
  72394. * Gets wether or not the texture is blocking during loading.
  72395. */
  72396. get: function () {
  72397. return this._isBlocking;
  72398. },
  72399. /**
  72400. * Sets wether or not the texture is blocking during loading.
  72401. */
  72402. set: function (value) {
  72403. this._isBlocking = value;
  72404. },
  72405. enumerable: true,
  72406. configurable: true
  72407. });
  72408. /**
  72409. * Occurs when the file is a preprocessed .babylon.hdr file.
  72410. */
  72411. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  72412. var _this = this;
  72413. var mipLevels = 0;
  72414. var floatArrayView = null;
  72415. var scene = this.getScene();
  72416. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  72417. var mips = new Array();
  72418. if (!floatArrayView) {
  72419. return mips;
  72420. }
  72421. var startIndex = 30;
  72422. for (var level = 0; level < mipLevels; level++) {
  72423. mips.push([]);
  72424. // Fill each pixel of the mip level.
  72425. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  72426. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72427. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  72428. mips[level].push(faceData);
  72429. startIndex += faceSize;
  72430. }
  72431. }
  72432. return mips;
  72433. } : null;
  72434. var callback = function (buffer) {
  72435. var scene = _this.getScene();
  72436. if (!scene) {
  72437. return null;
  72438. }
  72439. // Create Native Array Views
  72440. var intArrayView = new Int32Array(buffer);
  72441. floatArrayView = new Float32Array(buffer);
  72442. // Fill header.
  72443. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  72444. _this._size = intArrayView[1]; // CubeMap max mip face size.
  72445. // Update Texture Information.
  72446. if (!_this._texture) {
  72447. return null;
  72448. }
  72449. _this._texture.updateSize(_this._size, _this._size);
  72450. // Fill polynomial information.
  72451. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  72452. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  72453. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  72454. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  72455. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  72456. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  72457. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  72458. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  72459. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  72460. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  72461. _this.sphericalPolynomial = sphericalPolynomial;
  72462. // Fill pixel data.
  72463. mipLevels = intArrayView[29]; // Number of mip levels.
  72464. var startIndex = 30;
  72465. var data = [];
  72466. var faceSize = Math.pow(_this._size, 2) * 3;
  72467. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  72468. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  72469. startIndex += faceSize;
  72470. }
  72471. var results = [];
  72472. var byteArray = null;
  72473. // Push each faces.
  72474. for (var k = 0; k < 6; k++) {
  72475. var dataFace = null;
  72476. // To be deprecated.
  72477. if (version === 1) {
  72478. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  72479. dataFace = data[j];
  72480. }
  72481. // If special cases.
  72482. if (!mipmapGenerator && dataFace) {
  72483. if (!scene.getEngine().getCaps().textureFloat) {
  72484. // 3 channels of 1 bytes per pixel in bytes.
  72485. var byteBuffer = new ArrayBuffer(faceSize);
  72486. byteArray = new Uint8Array(byteBuffer);
  72487. }
  72488. for (var i = 0; i < _this._size * _this._size; i++) {
  72489. // Put in gamma space if requested.
  72490. if (_this._useInGammaSpace) {
  72491. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  72492. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  72493. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  72494. }
  72495. // Convert to int texture for fallback.
  72496. if (byteArray) {
  72497. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  72498. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  72499. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  72500. // May use luminance instead if the result is not accurate.
  72501. var max = Math.max(Math.max(r, g), b);
  72502. if (max > 255) {
  72503. var scale = 255 / max;
  72504. r *= scale;
  72505. g *= scale;
  72506. b *= scale;
  72507. }
  72508. byteArray[(i * 3) + 0] = r;
  72509. byteArray[(i * 3) + 1] = g;
  72510. byteArray[(i * 3) + 2] = b;
  72511. }
  72512. }
  72513. }
  72514. // Fill the array accordingly.
  72515. if (byteArray) {
  72516. results.push(byteArray);
  72517. }
  72518. else {
  72519. results.push(dataFace);
  72520. }
  72521. }
  72522. return results;
  72523. };
  72524. if (scene) {
  72525. 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, mipmapGenerator, this._onLoad, this._onError);
  72526. }
  72527. };
  72528. /**
  72529. * Occurs when the file is raw .hdr file.
  72530. */
  72531. HDRCubeTexture.prototype.loadHDRTexture = function () {
  72532. var _this = this;
  72533. var callback = function (buffer) {
  72534. var scene = _this.getScene();
  72535. if (!scene) {
  72536. return null;
  72537. }
  72538. // Extract the raw linear data.
  72539. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  72540. // Generate harmonics if needed.
  72541. if (_this._generateHarmonics) {
  72542. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  72543. _this.sphericalPolynomial = sphericalPolynomial;
  72544. }
  72545. var results = [];
  72546. var byteArray = null;
  72547. // Push each faces.
  72548. for (var j = 0; j < 6; j++) {
  72549. // Create uintarray fallback.
  72550. if (!scene.getEngine().getCaps().textureFloat) {
  72551. // 3 channels of 1 bytes per pixel in bytes.
  72552. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  72553. byteArray = new Uint8Array(byteBuffer);
  72554. }
  72555. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  72556. // If special cases.
  72557. if (_this._useInGammaSpace || byteArray) {
  72558. for (var i = 0; i < _this._size * _this._size; i++) {
  72559. // Put in gamma space if requested.
  72560. if (_this._useInGammaSpace) {
  72561. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  72562. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  72563. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  72564. }
  72565. // Convert to int texture for fallback.
  72566. if (byteArray) {
  72567. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  72568. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  72569. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  72570. // May use luminance instead if the result is not accurate.
  72571. var max = Math.max(Math.max(r, g), b);
  72572. if (max > 255) {
  72573. var scale = 255 / max;
  72574. r *= scale;
  72575. g *= scale;
  72576. b *= scale;
  72577. }
  72578. byteArray[(i * 3) + 0] = r;
  72579. byteArray[(i * 3) + 1] = g;
  72580. byteArray[(i * 3) + 2] = b;
  72581. }
  72582. }
  72583. }
  72584. if (byteArray) {
  72585. results.push(byteArray);
  72586. }
  72587. else {
  72588. results.push(dataFace);
  72589. }
  72590. }
  72591. return results;
  72592. };
  72593. var mipmapGenerator = null;
  72594. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  72595. // if (!this._noMipmap &&
  72596. // this._usePMREMGenerator) {
  72597. // mipmapGenerator = (data: ArrayBufferView[]) => {
  72598. // // Custom setup of the generator matching with the PBR shader values.
  72599. // var generator = new BABYLON.PMREMGenerator(data,
  72600. // this._size,
  72601. // this._size,
  72602. // 0,
  72603. // 3,
  72604. // this.getScene().getEngine().getCaps().textureFloat,
  72605. // 2048,
  72606. // 0.25,
  72607. // false,
  72608. // true);
  72609. // return generator.filterCubeMap();
  72610. // };
  72611. // }
  72612. var scene = this.getScene();
  72613. if (scene) {
  72614. 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, mipmapGenerator, this._onLoad, this._onError);
  72615. }
  72616. };
  72617. /**
  72618. * Starts the loading process of the texture.
  72619. */
  72620. HDRCubeTexture.prototype.loadTexture = function () {
  72621. if (this._isBABYLONPreprocessed) {
  72622. this.loadBabylonTexture();
  72623. }
  72624. else {
  72625. this.loadHDRTexture();
  72626. }
  72627. };
  72628. HDRCubeTexture.prototype.clone = function () {
  72629. var scene = this.getScene();
  72630. if (!scene) {
  72631. return this;
  72632. }
  72633. var size = (this._isBABYLONPreprocessed ? null : this._size);
  72634. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  72635. // Base texture
  72636. newTexture.level = this.level;
  72637. newTexture.wrapU = this.wrapU;
  72638. newTexture.wrapV = this.wrapV;
  72639. newTexture.coordinatesIndex = this.coordinatesIndex;
  72640. newTexture.coordinatesMode = this.coordinatesMode;
  72641. return newTexture;
  72642. };
  72643. // Methods
  72644. HDRCubeTexture.prototype.delayLoad = function () {
  72645. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  72646. return;
  72647. }
  72648. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  72649. this._texture = this._getFromCache(this.url, this._noMipmap);
  72650. if (!this._texture) {
  72651. this.loadTexture();
  72652. }
  72653. };
  72654. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  72655. return this._textureMatrix;
  72656. };
  72657. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  72658. this._textureMatrix = value;
  72659. };
  72660. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  72661. var texture = null;
  72662. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  72663. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  72664. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  72665. texture.name = parsedTexture.name;
  72666. texture.hasAlpha = parsedTexture.hasAlpha;
  72667. texture.level = parsedTexture.level;
  72668. texture.coordinatesMode = parsedTexture.coordinatesMode;
  72669. texture.isBlocking = parsedTexture.isBlocking;
  72670. }
  72671. return texture;
  72672. };
  72673. HDRCubeTexture.prototype.serialize = function () {
  72674. if (!this.name) {
  72675. return null;
  72676. }
  72677. var serializationObject = {};
  72678. serializationObject.name = this.name;
  72679. serializationObject.hasAlpha = this.hasAlpha;
  72680. serializationObject.isCube = true;
  72681. serializationObject.level = this.level;
  72682. serializationObject.size = this._size;
  72683. serializationObject.coordinatesMode = this.coordinatesMode;
  72684. serializationObject.useInGammaSpace = this._useInGammaSpace;
  72685. serializationObject.generateHarmonics = this._generateHarmonics;
  72686. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  72687. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  72688. serializationObject.customType = "BABYLON.HDRCubeTexture";
  72689. serializationObject.noMipmap = this._noMipmap;
  72690. serializationObject.isBlocking = this._isBlocking;
  72691. return serializationObject;
  72692. };
  72693. /**
  72694. * Saves as a file the data contained in the texture in a binary format.
  72695. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  72696. * as the spherical used in the lighting.
  72697. * @param url The HDR file url.
  72698. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  72699. * @param onError Method called if any error happens during download.
  72700. * @return The packed binary data.
  72701. */
  72702. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  72703. if (onError === void 0) { onError = null; }
  72704. var callback = function (buffer) {
  72705. var data = new Blob([buffer], { type: 'application/octet-stream' });
  72706. // Returns a URL you can use as a href.
  72707. var objUrl = window.URL.createObjectURL(data);
  72708. // Simulates a link to it and click to dowload.
  72709. var a = document.createElement("a");
  72710. document.body.appendChild(a);
  72711. a.style.display = "none";
  72712. a.href = objUrl;
  72713. a.download = "envmap.babylon.hdr";
  72714. a.click();
  72715. };
  72716. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  72717. };
  72718. /**
  72719. * Serializes the data contained in the texture in a binary format.
  72720. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  72721. * as the spherical used in the lighting.
  72722. * @param url The HDR file url.
  72723. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  72724. * @param onError Method called if any error happens during download.
  72725. * @return The packed binary data.
  72726. */
  72727. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  72728. if (onError === void 0) { onError = null; }
  72729. // Needs the url tho create the texture.
  72730. if (!url) {
  72731. return;
  72732. }
  72733. // Check Power of two size.
  72734. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  72735. return;
  72736. }
  72737. // Coming Back in 3.x.
  72738. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  72739. };
  72740. HDRCubeTexture._facesMapping = [
  72741. "right",
  72742. "left",
  72743. "up",
  72744. "down",
  72745. "front",
  72746. "back"
  72747. ];
  72748. return HDRCubeTexture;
  72749. }(BABYLON.BaseTexture));
  72750. BABYLON.HDRCubeTexture = HDRCubeTexture;
  72751. })(BABYLON || (BABYLON = {}));
  72752. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  72753. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  72754. // Huge respect for a such great lib.
  72755. // Earcut license:
  72756. // Copyright (c) 2016, Mapbox
  72757. //
  72758. // Permission to use, copy, modify, and/or distribute this software for any purpose
  72759. // with or without fee is hereby granted, provided that the above copyright notice
  72760. // and this permission notice appear in all copies.
  72761. //
  72762. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  72763. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  72764. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  72765. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  72766. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  72767. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  72768. // THIS SOFTWARE.
  72769. var Earcut;
  72770. (function (Earcut) {
  72771. /**
  72772. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  72773. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  72774. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  72775. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  72776. */
  72777. function earcut(data, holeIndices, dim) {
  72778. dim = dim || 2;
  72779. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  72780. if (!outerNode)
  72781. return triangles;
  72782. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  72783. if (hasHoles)
  72784. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  72785. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  72786. if (data.length > 80 * dim) {
  72787. minX = maxX = data[0];
  72788. minY = maxY = data[1];
  72789. for (var i = dim; i < outerLen; i += dim) {
  72790. x = data[i];
  72791. y = data[i + 1];
  72792. if (x < minX)
  72793. minX = x;
  72794. if (y < minY)
  72795. minY = y;
  72796. if (x > maxX)
  72797. maxX = x;
  72798. if (y > maxY)
  72799. maxY = y;
  72800. }
  72801. // minX, minY and size are later used to transform coords into integers for z-order calculation
  72802. size = Math.max(maxX - minX, maxY - minY);
  72803. }
  72804. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  72805. return triangles;
  72806. }
  72807. Earcut.earcut = earcut;
  72808. var Node = /** @class */ (function () {
  72809. function Node(i, x, y) {
  72810. this.i = i;
  72811. this.x = x;
  72812. this.y = y;
  72813. this.prev = null;
  72814. this.next = null;
  72815. this.z = null;
  72816. this.prevZ = null;
  72817. this.nextZ = null;
  72818. this.steiner = false;
  72819. }
  72820. return Node;
  72821. }());
  72822. // create a circular doubly linked list from polygon points in the specified winding order
  72823. function linkedList(data, start, end, dim, clockwise) {
  72824. var i, last = null;
  72825. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  72826. for (i = start; i < end; i += dim)
  72827. last = insertNode(i, data[i], data[i + 1], last);
  72828. }
  72829. else {
  72830. for (i = end - dim; i >= start; i -= dim)
  72831. last = insertNode(i, data[i], data[i + 1], last);
  72832. }
  72833. if (last && equals(last, last.next)) {
  72834. removeNode(last);
  72835. last = last.next;
  72836. }
  72837. return last;
  72838. }
  72839. // eliminate colinear or duplicate points
  72840. function filterPoints(start, end) {
  72841. if (!start)
  72842. return start;
  72843. if (!end)
  72844. end = start;
  72845. var p = start, again;
  72846. do {
  72847. again = false;
  72848. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  72849. removeNode(p);
  72850. p = end = p.prev;
  72851. if (p === p.next)
  72852. return undefined;
  72853. again = true;
  72854. }
  72855. else {
  72856. p = p.next;
  72857. }
  72858. } while (again || p !== end);
  72859. return end;
  72860. }
  72861. // main ear slicing loop which triangulates a polygon (given as a linked list)
  72862. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  72863. if (!ear)
  72864. return;
  72865. // interlink polygon nodes in z-order
  72866. if (!pass && size)
  72867. indexCurve(ear, minX, minY, size);
  72868. var stop = ear, prev, next;
  72869. // iterate through ears, slicing them one by one
  72870. while (ear.prev !== ear.next) {
  72871. prev = ear.prev;
  72872. next = ear.next;
  72873. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  72874. // cut off the triangle
  72875. triangles.push(prev.i / dim);
  72876. triangles.push(ear.i / dim);
  72877. triangles.push(next.i / dim);
  72878. removeNode(ear);
  72879. // skipping the next vertice leads to less sliver triangles
  72880. ear = next.next;
  72881. stop = next.next;
  72882. continue;
  72883. }
  72884. ear = next;
  72885. // if we looped through the whole remaining polygon and can't find any more ears
  72886. if (ear === stop) {
  72887. // try filtering points and slicing again
  72888. if (!pass) {
  72889. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  72890. // if this didn't work, try curing all small self-intersections locally
  72891. }
  72892. else if (pass === 1) {
  72893. ear = cureLocalIntersections(ear, triangles, dim);
  72894. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  72895. // as a last resort, try splitting the remaining polygon into two
  72896. }
  72897. else if (pass === 2) {
  72898. splitEarcut(ear, triangles, dim, minX, minY, size);
  72899. }
  72900. break;
  72901. }
  72902. }
  72903. }
  72904. // check whether a polygon node forms a valid ear with adjacent nodes
  72905. function isEar(ear) {
  72906. var a = ear.prev, b = ear, c = ear.next;
  72907. if (area(a, b, c) >= 0)
  72908. return false; // reflex, can't be an ear
  72909. // now make sure we don't have other points inside the potential ear
  72910. var p = ear.next.next;
  72911. while (p !== ear.prev) {
  72912. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  72913. area(p.prev, p, p.next) >= 0)
  72914. return false;
  72915. p = p.next;
  72916. }
  72917. return true;
  72918. }
  72919. function isEarHashed(ear, minX, minY, size) {
  72920. var a = ear.prev, b = ear, c = ear.next;
  72921. if (area(a, b, c) >= 0)
  72922. return false; // reflex, can't be an ear
  72923. // triangle bbox; min & max are calculated like this for speed
  72924. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  72925. // z-order range for the current triangle bbox;
  72926. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  72927. // first look for points inside the triangle in increasing z-order
  72928. var p = ear.nextZ;
  72929. while (p && p.z <= maxZ) {
  72930. if (p !== ear.prev &&
  72931. p !== ear.next &&
  72932. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  72933. area(p.prev, p, p.next) >= 0)
  72934. return false;
  72935. p = p.nextZ;
  72936. }
  72937. // then look for points in decreasing z-order
  72938. p = ear.prevZ;
  72939. while (p && p.z >= minZ) {
  72940. if (p !== ear.prev &&
  72941. p !== ear.next &&
  72942. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  72943. area(p.prev, p, p.next) >= 0)
  72944. return false;
  72945. p = p.prevZ;
  72946. }
  72947. return true;
  72948. }
  72949. // go through all polygon nodes and cure small local self-intersections
  72950. function cureLocalIntersections(start, triangles, dim) {
  72951. var p = start;
  72952. do {
  72953. var a = p.prev, b = p.next.next;
  72954. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  72955. triangles.push(a.i / dim);
  72956. triangles.push(p.i / dim);
  72957. triangles.push(b.i / dim);
  72958. // remove two nodes involved
  72959. removeNode(p);
  72960. removeNode(p.next);
  72961. p = start = b;
  72962. }
  72963. p = p.next;
  72964. } while (p !== start);
  72965. return p;
  72966. }
  72967. // try splitting polygon into two and triangulate them independently
  72968. function splitEarcut(start, triangles, dim, minX, minY, size) {
  72969. // look for a valid diagonal that divides the polygon into two
  72970. var a = start;
  72971. do {
  72972. var b = a.next.next;
  72973. while (b !== a.prev) {
  72974. if (a.i !== b.i && isValidDiagonal(a, b)) {
  72975. // split the polygon in two by the diagonal
  72976. var c = splitPolygon(a, b);
  72977. // filter colinear points around the cuts
  72978. a = filterPoints(a, a.next);
  72979. c = filterPoints(c, c.next);
  72980. // run earcut on each half
  72981. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  72982. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  72983. return;
  72984. }
  72985. b = b.next;
  72986. }
  72987. a = a.next;
  72988. } while (a !== start);
  72989. }
  72990. // link every hole into the outer loop, producing a single-ring polygon without holes
  72991. function eliminateHoles(data, holeIndices, outerNode, dim) {
  72992. var queue = [], i, len, start, end, list;
  72993. for (i = 0, len = holeIndices.length; i < len; i++) {
  72994. start = holeIndices[i] * dim;
  72995. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  72996. list = linkedList(data, start, end, dim, false);
  72997. if (list === list.next)
  72998. list.steiner = true;
  72999. queue.push(getLeftmost(list));
  73000. }
  73001. queue.sort(compareX);
  73002. // process holes from left to right
  73003. for (i = 0; i < queue.length; i++) {
  73004. eliminateHole(queue[i], outerNode);
  73005. outerNode = filterPoints(outerNode, outerNode.next);
  73006. }
  73007. return outerNode;
  73008. }
  73009. function compareX(a, b) {
  73010. return a.x - b.x;
  73011. }
  73012. // find a bridge between vertices that connects hole with an outer ring and and link it
  73013. function eliminateHole(hole, outerNode) {
  73014. outerNode = findHoleBridge(hole, outerNode);
  73015. if (outerNode) {
  73016. var b = splitPolygon(outerNode, hole);
  73017. filterPoints(b, b.next);
  73018. }
  73019. }
  73020. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  73021. function findHoleBridge(hole, outerNode) {
  73022. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  73023. // find a segment intersected by a ray from the hole's leftmost point to the left;
  73024. // segment's endpoint with lesser x will be potential connection point
  73025. do {
  73026. if (hy <= p.y && hy >= p.next.y) {
  73027. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  73028. if (x <= hx && x > qx) {
  73029. qx = x;
  73030. if (x === hx) {
  73031. if (hy === p.y)
  73032. return p;
  73033. if (hy === p.next.y)
  73034. return p.next;
  73035. }
  73036. m = p.x < p.next.x ? p : p.next;
  73037. }
  73038. }
  73039. p = p.next;
  73040. } while (p !== outerNode);
  73041. if (!m)
  73042. return null;
  73043. if (hx === qx)
  73044. return m.prev; // hole touches outer segment; pick lower endpoint
  73045. // look for points inside the triangle of hole point, segment intersection and endpoint;
  73046. // if there are no points found, we have a valid connection;
  73047. // otherwise choose the point of the minimum angle with the ray as connection point
  73048. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  73049. p = m.next;
  73050. while (p !== stop) {
  73051. if (hx >= p.x &&
  73052. p.x >= mx &&
  73053. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  73054. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  73055. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  73056. m = p;
  73057. tanMin = tan;
  73058. }
  73059. }
  73060. p = p.next;
  73061. }
  73062. return m;
  73063. }
  73064. // interlink polygon nodes in z-order
  73065. function indexCurve(start, minX, minY, size) {
  73066. var p = start;
  73067. do {
  73068. if (p.z === null)
  73069. p.z = zOrder(p.x, p.y, minX, minY, size);
  73070. p.prevZ = p.prev;
  73071. p.nextZ = p.next;
  73072. p = p.next;
  73073. } while (p !== start);
  73074. p.prevZ.nextZ = null;
  73075. p.prevZ = null;
  73076. sortLinked(p);
  73077. }
  73078. // Simon Tatham's linked list merge sort algorithm
  73079. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  73080. function sortLinked(list) {
  73081. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  73082. do {
  73083. p = list;
  73084. list = null;
  73085. tail = null;
  73086. numMerges = 0;
  73087. while (p) {
  73088. numMerges++;
  73089. q = p;
  73090. pSize = 0;
  73091. for (i = 0; i < inSize; i++) {
  73092. pSize++;
  73093. q = q.nextZ;
  73094. if (!q)
  73095. break;
  73096. }
  73097. qSize = inSize;
  73098. while (pSize > 0 || (qSize > 0 && q)) {
  73099. if (pSize === 0) {
  73100. e = q;
  73101. q = q.nextZ;
  73102. qSize--;
  73103. }
  73104. else if (qSize === 0 || !q) {
  73105. e = p;
  73106. p = p.nextZ;
  73107. pSize--;
  73108. }
  73109. else if (p.z <= q.z) {
  73110. e = p;
  73111. p = p.nextZ;
  73112. pSize--;
  73113. }
  73114. else {
  73115. e = q;
  73116. q = q.nextZ;
  73117. qSize--;
  73118. }
  73119. if (tail)
  73120. tail.nextZ = e;
  73121. else
  73122. list = e;
  73123. e.prevZ = tail;
  73124. tail = e;
  73125. }
  73126. p = q;
  73127. }
  73128. tail.nextZ = null;
  73129. inSize *= 2;
  73130. } while (numMerges > 1);
  73131. return list;
  73132. }
  73133. // z-order of a point given coords and size of the data bounding box
  73134. function zOrder(x, y, minX, minY, size) {
  73135. // coords are transformed into non-negative 15-bit integer range
  73136. x = 32767 * (x - minX) / size;
  73137. y = 32767 * (y - minY) / size;
  73138. x = (x | (x << 8)) & 0x00FF00FF;
  73139. x = (x | (x << 4)) & 0x0F0F0F0F;
  73140. x = (x | (x << 2)) & 0x33333333;
  73141. x = (x | (x << 1)) & 0x55555555;
  73142. y = (y | (y << 8)) & 0x00FF00FF;
  73143. y = (y | (y << 4)) & 0x0F0F0F0F;
  73144. y = (y | (y << 2)) & 0x33333333;
  73145. y = (y | (y << 1)) & 0x55555555;
  73146. return x | (y << 1);
  73147. }
  73148. // find the leftmost node of a polygon ring
  73149. function getLeftmost(start) {
  73150. var p = start, leftmost = start;
  73151. do {
  73152. if (p.x < leftmost.x)
  73153. leftmost = p;
  73154. p = p.next;
  73155. } while (p !== start);
  73156. return leftmost;
  73157. }
  73158. // check if a point lies within a convex triangle
  73159. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  73160. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  73161. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  73162. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  73163. }
  73164. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  73165. function isValidDiagonal(a, b) {
  73166. return a.next.i !== b.i &&
  73167. a.prev.i !== b.i &&
  73168. !intersectsPolygon(a, b) &&
  73169. locallyInside(a, b) &&
  73170. locallyInside(b, a) &&
  73171. middleInside(a, b);
  73172. }
  73173. // signed area of a triangle
  73174. function area(p, q, r) {
  73175. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  73176. }
  73177. // check if two points are equal
  73178. function equals(p1, p2) {
  73179. return p1.x === p2.x && p1.y === p2.y;
  73180. }
  73181. // check if two segments intersect
  73182. function intersects(p1, q1, p2, q2) {
  73183. if ((equals(p1, q1) && equals(p2, q2)) ||
  73184. (equals(p1, q2) && equals(p2, q1)))
  73185. return true;
  73186. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  73187. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  73188. }
  73189. // check if a polygon diagonal intersects any polygon segments
  73190. function intersectsPolygon(a, b) {
  73191. var p = a;
  73192. do {
  73193. if (p.i !== a.i &&
  73194. p.next.i !== a.i &&
  73195. p.i !== b.i &&
  73196. p.next.i !== b.i &&
  73197. intersects(p, p.next, a, b))
  73198. return true;
  73199. p = p.next;
  73200. } while (p !== a);
  73201. return false;
  73202. }
  73203. // check if a polygon diagonal is locally inside the polygon
  73204. function locallyInside(a, b) {
  73205. return area(a.prev, a, a.next) < 0
  73206. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  73207. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  73208. }
  73209. // check if the middle point of a polygon diagonal is inside the polygon
  73210. function middleInside(a, b) {
  73211. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  73212. do {
  73213. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  73214. inside = !inside;
  73215. p = p.next;
  73216. } while (p !== a);
  73217. return inside;
  73218. }
  73219. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  73220. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  73221. function splitPolygon(a, b) {
  73222. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  73223. a.next = b;
  73224. b.prev = a;
  73225. a2.next = an;
  73226. an.prev = a2;
  73227. b2.next = a2;
  73228. a2.prev = b2;
  73229. bp.next = b2;
  73230. b2.prev = bp;
  73231. return b2;
  73232. }
  73233. // create a node and optionally link it with previous one (in a circular doubly linked list)
  73234. function insertNode(i, x, y, last) {
  73235. var p = new Node(i, x, y);
  73236. if (!last) {
  73237. p.prev = p;
  73238. p.next = p;
  73239. }
  73240. else {
  73241. p.next = last.next;
  73242. p.prev = last;
  73243. last.next.prev = p;
  73244. last.next = p;
  73245. }
  73246. return p;
  73247. }
  73248. function removeNode(p) {
  73249. p.next.prev = p.prev;
  73250. p.prev.next = p.next;
  73251. if (p.prevZ)
  73252. p.prevZ.nextZ = p.nextZ;
  73253. if (p.nextZ)
  73254. p.nextZ.prevZ = p.prevZ;
  73255. }
  73256. /**
  73257. * return a percentage difference between the polygon area and its triangulation area;
  73258. * used to verify correctness of triangulation
  73259. */
  73260. function deviation(data, holeIndices, dim, triangles) {
  73261. var hasHoles = holeIndices && holeIndices.length;
  73262. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  73263. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  73264. if (hasHoles) {
  73265. for (var i = 0, len = holeIndices.length; i < len; i++) {
  73266. var start = holeIndices[i] * dim;
  73267. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  73268. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  73269. }
  73270. }
  73271. var trianglesArea = 0;
  73272. for (i = 0; i < triangles.length; i += 3) {
  73273. var a = triangles[i] * dim;
  73274. var b = triangles[i + 1] * dim;
  73275. var c = triangles[i + 2] * dim;
  73276. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  73277. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  73278. }
  73279. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  73280. }
  73281. Earcut.deviation = deviation;
  73282. ;
  73283. function signedArea(data, start, end, dim) {
  73284. var sum = 0;
  73285. for (var i = start, j = end - dim; i < end; i += dim) {
  73286. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  73287. j = i;
  73288. }
  73289. return sum;
  73290. }
  73291. /**
  73292. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  73293. */
  73294. function flatten(data) {
  73295. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  73296. for (var i = 0; i < data.length; i++) {
  73297. for (var j = 0; j < data[i].length; j++) {
  73298. for (var d = 0; d < dim; d++)
  73299. result.vertices.push(data[i][j][d]);
  73300. }
  73301. if (i > 0) {
  73302. holeIndex += data[i - 1].length;
  73303. result.holes.push(holeIndex);
  73304. }
  73305. }
  73306. return result;
  73307. }
  73308. Earcut.flatten = flatten;
  73309. ;
  73310. })(Earcut || (Earcut = {}));
  73311. //# sourceMappingURL=babylon.earcut.js.map
  73312. var BABYLON;
  73313. (function (BABYLON) {
  73314. var IndexedVector2 = /** @class */ (function (_super) {
  73315. __extends(IndexedVector2, _super);
  73316. function IndexedVector2(original, index) {
  73317. var _this = _super.call(this, original.x, original.y) || this;
  73318. _this.index = index;
  73319. return _this;
  73320. }
  73321. return IndexedVector2;
  73322. }(BABYLON.Vector2));
  73323. var PolygonPoints = /** @class */ (function () {
  73324. function PolygonPoints() {
  73325. this.elements = new Array();
  73326. }
  73327. PolygonPoints.prototype.add = function (originalPoints) {
  73328. var _this = this;
  73329. var result = new Array();
  73330. originalPoints.forEach(function (point) {
  73331. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  73332. var newPoint = new IndexedVector2(point, _this.elements.length);
  73333. result.push(newPoint);
  73334. _this.elements.push(newPoint);
  73335. }
  73336. });
  73337. return result;
  73338. };
  73339. PolygonPoints.prototype.computeBounds = function () {
  73340. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73341. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  73342. this.elements.forEach(function (point) {
  73343. // x
  73344. if (point.x < lmin.x) {
  73345. lmin.x = point.x;
  73346. }
  73347. else if (point.x > lmax.x) {
  73348. lmax.x = point.x;
  73349. }
  73350. // y
  73351. if (point.y < lmin.y) {
  73352. lmin.y = point.y;
  73353. }
  73354. else if (point.y > lmax.y) {
  73355. lmax.y = point.y;
  73356. }
  73357. });
  73358. return {
  73359. min: lmin,
  73360. max: lmax,
  73361. width: lmax.x - lmin.x,
  73362. height: lmax.y - lmin.y
  73363. };
  73364. };
  73365. return PolygonPoints;
  73366. }());
  73367. var Polygon = /** @class */ (function () {
  73368. function Polygon() {
  73369. }
  73370. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  73371. return [
  73372. new BABYLON.Vector2(xmin, ymin),
  73373. new BABYLON.Vector2(xmax, ymin),
  73374. new BABYLON.Vector2(xmax, ymax),
  73375. new BABYLON.Vector2(xmin, ymax)
  73376. ];
  73377. };
  73378. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  73379. if (cx === void 0) { cx = 0; }
  73380. if (cy === void 0) { cy = 0; }
  73381. if (numberOfSides === void 0) { numberOfSides = 32; }
  73382. var result = new Array();
  73383. var angle = 0;
  73384. var increment = (Math.PI * 2) / numberOfSides;
  73385. for (var i = 0; i < numberOfSides; i++) {
  73386. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  73387. angle -= increment;
  73388. }
  73389. return result;
  73390. };
  73391. Polygon.Parse = function (input) {
  73392. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  73393. var i, result = [];
  73394. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  73395. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  73396. }
  73397. return result;
  73398. };
  73399. Polygon.StartingAt = function (x, y) {
  73400. return BABYLON.Path2.StartingAt(x, y);
  73401. };
  73402. return Polygon;
  73403. }());
  73404. BABYLON.Polygon = Polygon;
  73405. var PolygonMeshBuilder = /** @class */ (function () {
  73406. function PolygonMeshBuilder(name, contours, scene) {
  73407. this._points = new PolygonPoints();
  73408. this._outlinepoints = new PolygonPoints();
  73409. this._holes = new Array();
  73410. this._epoints = new Array();
  73411. this._eholes = new Array();
  73412. this._name = name;
  73413. this._scene = scene;
  73414. var points;
  73415. if (contours instanceof BABYLON.Path2) {
  73416. points = contours.getPoints();
  73417. }
  73418. else {
  73419. points = contours;
  73420. }
  73421. this._addToepoint(points);
  73422. this._points.add(points);
  73423. this._outlinepoints.add(points);
  73424. }
  73425. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  73426. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  73427. var p = points_1[_i];
  73428. this._epoints.push(p.x, p.y);
  73429. }
  73430. };
  73431. PolygonMeshBuilder.prototype.addHole = function (hole) {
  73432. this._points.add(hole);
  73433. var holepoints = new PolygonPoints();
  73434. holepoints.add(hole);
  73435. this._holes.push(holepoints);
  73436. this._eholes.push(this._epoints.length / 2);
  73437. this._addToepoint(hole);
  73438. return this;
  73439. };
  73440. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  73441. var _this = this;
  73442. if (updatable === void 0) { updatable = false; }
  73443. if (depth === void 0) { depth = 0; }
  73444. var result = new BABYLON.Mesh(this._name, this._scene);
  73445. var normals = new Array();
  73446. var positions = new Array();
  73447. var uvs = new Array();
  73448. var bounds = this._points.computeBounds();
  73449. this._points.elements.forEach(function (p) {
  73450. normals.push(0, 1.0, 0);
  73451. positions.push(p.x, 0, p.y);
  73452. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  73453. });
  73454. var indices = new Array();
  73455. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  73456. for (var i = 0; i < res.length; i++) {
  73457. indices.push(res[i]);
  73458. }
  73459. if (depth > 0) {
  73460. var positionscount = (positions.length / 3); //get the current pointcount
  73461. this._points.elements.forEach(function (p) {
  73462. normals.push(0, -1.0, 0);
  73463. positions.push(p.x, -depth, p.y);
  73464. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  73465. });
  73466. var totalCount = indices.length;
  73467. for (var i = 0; i < totalCount; i += 3) {
  73468. var i0 = indices[i + 0];
  73469. var i1 = indices[i + 1];
  73470. var i2 = indices[i + 2];
  73471. indices.push(i2 + positionscount);
  73472. indices.push(i1 + positionscount);
  73473. indices.push(i0 + positionscount);
  73474. }
  73475. //Add the sides
  73476. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  73477. this._holes.forEach(function (hole) {
  73478. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  73479. });
  73480. }
  73481. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  73482. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  73483. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  73484. result.setIndices(indices);
  73485. return result;
  73486. };
  73487. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  73488. var StartIndex = positions.length / 3;
  73489. var ulength = 0;
  73490. for (var i = 0; i < points.elements.length; i++) {
  73491. var p = points.elements[i];
  73492. var p1;
  73493. if ((i + 1) > points.elements.length - 1) {
  73494. p1 = points.elements[0];
  73495. }
  73496. else {
  73497. p1 = points.elements[i + 1];
  73498. }
  73499. positions.push(p.x, 0, p.y);
  73500. positions.push(p.x, -depth, p.y);
  73501. positions.push(p1.x, 0, p1.y);
  73502. positions.push(p1.x, -depth, p1.y);
  73503. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  73504. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  73505. var v3 = v2.subtract(v1);
  73506. var v4 = new BABYLON.Vector3(0, 1, 0);
  73507. var vn = BABYLON.Vector3.Cross(v3, v4);
  73508. vn = vn.normalize();
  73509. uvs.push(ulength / bounds.width, 0);
  73510. uvs.push(ulength / bounds.width, 1);
  73511. ulength += v3.length();
  73512. uvs.push((ulength / bounds.width), 0);
  73513. uvs.push((ulength / bounds.width), 1);
  73514. if (!flip) {
  73515. normals.push(-vn.x, -vn.y, -vn.z);
  73516. normals.push(-vn.x, -vn.y, -vn.z);
  73517. normals.push(-vn.x, -vn.y, -vn.z);
  73518. normals.push(-vn.x, -vn.y, -vn.z);
  73519. indices.push(StartIndex);
  73520. indices.push(StartIndex + 1);
  73521. indices.push(StartIndex + 2);
  73522. indices.push(StartIndex + 1);
  73523. indices.push(StartIndex + 3);
  73524. indices.push(StartIndex + 2);
  73525. }
  73526. else {
  73527. normals.push(vn.x, vn.y, vn.z);
  73528. normals.push(vn.x, vn.y, vn.z);
  73529. normals.push(vn.x, vn.y, vn.z);
  73530. normals.push(vn.x, vn.y, vn.z);
  73531. indices.push(StartIndex);
  73532. indices.push(StartIndex + 2);
  73533. indices.push(StartIndex + 1);
  73534. indices.push(StartIndex + 1);
  73535. indices.push(StartIndex + 2);
  73536. indices.push(StartIndex + 3);
  73537. }
  73538. StartIndex += 4;
  73539. }
  73540. ;
  73541. };
  73542. return PolygonMeshBuilder;
  73543. }());
  73544. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  73545. })(BABYLON || (BABYLON = {}));
  73546. //# sourceMappingURL=babylon.polygonMesh.js.map
  73547. var BABYLON;
  73548. (function (BABYLON) {
  73549. // Unique ID when we import meshes from Babylon to CSG
  73550. var currentCSGMeshId = 0;
  73551. // # class Vertex
  73552. // Represents a vertex of a polygon. Use your own vertex class instead of this
  73553. // one to provide additional features like texture coordinates and vertex
  73554. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  73555. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  73556. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  73557. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  73558. // is not used anywhere else.
  73559. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  73560. var Vertex = /** @class */ (function () {
  73561. function Vertex(pos, normal, uv) {
  73562. this.pos = pos;
  73563. this.normal = normal;
  73564. this.uv = uv;
  73565. }
  73566. Vertex.prototype.clone = function () {
  73567. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  73568. };
  73569. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  73570. // orientation of a polygon is flipped.
  73571. Vertex.prototype.flip = function () {
  73572. this.normal = this.normal.scale(-1);
  73573. };
  73574. // Create a new vertex between this vertex and `other` by linearly
  73575. // interpolating all properties using a parameter of `t`. Subclasses should
  73576. // override this to interpolate additional properties.
  73577. Vertex.prototype.interpolate = function (other, t) {
  73578. 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));
  73579. };
  73580. return Vertex;
  73581. }());
  73582. // # class Plane
  73583. // Represents a plane in 3D space.
  73584. var Plane = /** @class */ (function () {
  73585. function Plane(normal, w) {
  73586. this.normal = normal;
  73587. this.w = w;
  73588. }
  73589. Plane.FromPoints = function (a, b, c) {
  73590. var v0 = c.subtract(a);
  73591. var v1 = b.subtract(a);
  73592. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  73593. return null;
  73594. }
  73595. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  73596. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  73597. };
  73598. Plane.prototype.clone = function () {
  73599. return new Plane(this.normal.clone(), this.w);
  73600. };
  73601. Plane.prototype.flip = function () {
  73602. this.normal.scaleInPlace(-1);
  73603. this.w = -this.w;
  73604. };
  73605. // Split `polygon` by this plane if needed, then put the polygon or polygon
  73606. // fragments in the appropriate lists. Coplanar polygons go into either
  73607. // `coplanarFront` or `coplanarBack` depending on their orientation with
  73608. // respect to this plane. Polygons in front or in back of this plane go into
  73609. // either `front` or `back`.
  73610. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  73611. var COPLANAR = 0;
  73612. var FRONT = 1;
  73613. var BACK = 2;
  73614. var SPANNING = 3;
  73615. // Classify each point as well as the entire polygon into one of the above
  73616. // four classes.
  73617. var polygonType = 0;
  73618. var types = [];
  73619. var i;
  73620. var t;
  73621. for (i = 0; i < polygon.vertices.length; i++) {
  73622. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  73623. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  73624. polygonType |= type;
  73625. types.push(type);
  73626. }
  73627. // Put the polygon in the correct list, splitting it when necessary.
  73628. switch (polygonType) {
  73629. case COPLANAR:
  73630. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  73631. break;
  73632. case FRONT:
  73633. front.push(polygon);
  73634. break;
  73635. case BACK:
  73636. back.push(polygon);
  73637. break;
  73638. case SPANNING:
  73639. var f = [], b = [];
  73640. for (i = 0; i < polygon.vertices.length; i++) {
  73641. var j = (i + 1) % polygon.vertices.length;
  73642. var ti = types[i], tj = types[j];
  73643. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  73644. if (ti !== BACK)
  73645. f.push(vi);
  73646. if (ti !== FRONT)
  73647. b.push(ti !== BACK ? vi.clone() : vi);
  73648. if ((ti | tj) === SPANNING) {
  73649. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  73650. var v = vi.interpolate(vj, t);
  73651. f.push(v);
  73652. b.push(v.clone());
  73653. }
  73654. }
  73655. var poly;
  73656. if (f.length >= 3) {
  73657. poly = new Polygon(f, polygon.shared);
  73658. if (poly.plane)
  73659. front.push(poly);
  73660. }
  73661. if (b.length >= 3) {
  73662. poly = new Polygon(b, polygon.shared);
  73663. if (poly.plane)
  73664. back.push(poly);
  73665. }
  73666. break;
  73667. }
  73668. };
  73669. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  73670. // point is on the plane.
  73671. Plane.EPSILON = 1e-5;
  73672. return Plane;
  73673. }());
  73674. // # class Polygon
  73675. // Represents a convex polygon. The vertices used to initialize a polygon must
  73676. // be coplanar and form a convex loop.
  73677. //
  73678. // Each convex polygon has a `shared` property, which is shared between all
  73679. // polygons that are clones of each other or were split from the same polygon.
  73680. // This can be used to define per-polygon properties (such as surface color).
  73681. var Polygon = /** @class */ (function () {
  73682. function Polygon(vertices, shared) {
  73683. this.vertices = vertices;
  73684. this.shared = shared;
  73685. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  73686. }
  73687. Polygon.prototype.clone = function () {
  73688. var vertices = this.vertices.map(function (v) { return v.clone(); });
  73689. return new Polygon(vertices, this.shared);
  73690. };
  73691. Polygon.prototype.flip = function () {
  73692. this.vertices.reverse().map(function (v) { v.flip(); });
  73693. this.plane.flip();
  73694. };
  73695. return Polygon;
  73696. }());
  73697. // # class Node
  73698. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  73699. // by picking a polygon to split along. That polygon (and all other coplanar
  73700. // polygons) are added directly to that node and the other polygons are added to
  73701. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  73702. // no distinction between internal and leaf nodes.
  73703. var Node = /** @class */ (function () {
  73704. function Node(polygons) {
  73705. this.plane = null;
  73706. this.front = null;
  73707. this.back = null;
  73708. this.polygons = new Array();
  73709. if (polygons) {
  73710. this.build(polygons);
  73711. }
  73712. }
  73713. Node.prototype.clone = function () {
  73714. var node = new Node();
  73715. node.plane = this.plane && this.plane.clone();
  73716. node.front = this.front && this.front.clone();
  73717. node.back = this.back && this.back.clone();
  73718. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  73719. return node;
  73720. };
  73721. // Convert solid space to empty space and empty space to solid space.
  73722. Node.prototype.invert = function () {
  73723. for (var i = 0; i < this.polygons.length; i++) {
  73724. this.polygons[i].flip();
  73725. }
  73726. if (this.plane) {
  73727. this.plane.flip();
  73728. }
  73729. if (this.front) {
  73730. this.front.invert();
  73731. }
  73732. if (this.back) {
  73733. this.back.invert();
  73734. }
  73735. var temp = this.front;
  73736. this.front = this.back;
  73737. this.back = temp;
  73738. };
  73739. // Recursively remove all polygons in `polygons` that are inside this BSP
  73740. // tree.
  73741. Node.prototype.clipPolygons = function (polygons) {
  73742. if (!this.plane)
  73743. return polygons.slice();
  73744. var front = new Array(), back = new Array();
  73745. for (var i = 0; i < polygons.length; i++) {
  73746. this.plane.splitPolygon(polygons[i], front, back, front, back);
  73747. }
  73748. if (this.front) {
  73749. front = this.front.clipPolygons(front);
  73750. }
  73751. if (this.back) {
  73752. back = this.back.clipPolygons(back);
  73753. }
  73754. else {
  73755. back = [];
  73756. }
  73757. return front.concat(back);
  73758. };
  73759. // Remove all polygons in this BSP tree that are inside the other BSP tree
  73760. // `bsp`.
  73761. Node.prototype.clipTo = function (bsp) {
  73762. this.polygons = bsp.clipPolygons(this.polygons);
  73763. if (this.front)
  73764. this.front.clipTo(bsp);
  73765. if (this.back)
  73766. this.back.clipTo(bsp);
  73767. };
  73768. // Return a list of all polygons in this BSP tree.
  73769. Node.prototype.allPolygons = function () {
  73770. var polygons = this.polygons.slice();
  73771. if (this.front)
  73772. polygons = polygons.concat(this.front.allPolygons());
  73773. if (this.back)
  73774. polygons = polygons.concat(this.back.allPolygons());
  73775. return polygons;
  73776. };
  73777. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  73778. // new polygons are filtered down to the bottom of the tree and become new
  73779. // nodes there. Each set of polygons is partitioned using the first polygon
  73780. // (no heuristic is used to pick a good split).
  73781. Node.prototype.build = function (polygons) {
  73782. if (!polygons.length)
  73783. return;
  73784. if (!this.plane)
  73785. this.plane = polygons[0].plane.clone();
  73786. var front = new Array(), back = new Array();
  73787. for (var i = 0; i < polygons.length; i++) {
  73788. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  73789. }
  73790. if (front.length) {
  73791. if (!this.front)
  73792. this.front = new Node();
  73793. this.front.build(front);
  73794. }
  73795. if (back.length) {
  73796. if (!this.back)
  73797. this.back = new Node();
  73798. this.back.build(back);
  73799. }
  73800. };
  73801. return Node;
  73802. }());
  73803. var CSG = /** @class */ (function () {
  73804. function CSG() {
  73805. this.polygons = new Array();
  73806. }
  73807. // Convert BABYLON.Mesh to BABYLON.CSG
  73808. CSG.FromMesh = function (mesh) {
  73809. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  73810. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  73811. if (mesh instanceof BABYLON.Mesh) {
  73812. mesh.computeWorldMatrix(true);
  73813. matrix = mesh.getWorldMatrix();
  73814. meshPosition = mesh.position.clone();
  73815. meshRotation = mesh.rotation.clone();
  73816. if (mesh.rotationQuaternion) {
  73817. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  73818. }
  73819. meshScaling = mesh.scaling.clone();
  73820. }
  73821. else {
  73822. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  73823. }
  73824. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  73825. var subMeshes = mesh.subMeshes;
  73826. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  73827. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  73828. vertices = [];
  73829. for (var j = 0; j < 3; j++) {
  73830. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  73831. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  73832. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  73833. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  73834. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  73835. vertex = new Vertex(position, normal, uv);
  73836. vertices.push(vertex);
  73837. }
  73838. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  73839. // To handle the case of degenerated triangle
  73840. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  73841. if (polygon.plane)
  73842. polygons.push(polygon);
  73843. }
  73844. }
  73845. var csg = CSG.FromPolygons(polygons);
  73846. csg.matrix = matrix;
  73847. csg.position = meshPosition;
  73848. csg.rotation = meshRotation;
  73849. csg.scaling = meshScaling;
  73850. csg.rotationQuaternion = meshRotationQuaternion;
  73851. currentCSGMeshId++;
  73852. return csg;
  73853. };
  73854. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  73855. CSG.FromPolygons = function (polygons) {
  73856. var csg = new CSG();
  73857. csg.polygons = polygons;
  73858. return csg;
  73859. };
  73860. CSG.prototype.clone = function () {
  73861. var csg = new CSG();
  73862. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  73863. csg.copyTransformAttributes(this);
  73864. return csg;
  73865. };
  73866. CSG.prototype.union = function (csg) {
  73867. var a = new Node(this.clone().polygons);
  73868. var b = new Node(csg.clone().polygons);
  73869. a.clipTo(b);
  73870. b.clipTo(a);
  73871. b.invert();
  73872. b.clipTo(a);
  73873. b.invert();
  73874. a.build(b.allPolygons());
  73875. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  73876. };
  73877. CSG.prototype.unionInPlace = function (csg) {
  73878. var a = new Node(this.polygons);
  73879. var b = new Node(csg.polygons);
  73880. a.clipTo(b);
  73881. b.clipTo(a);
  73882. b.invert();
  73883. b.clipTo(a);
  73884. b.invert();
  73885. a.build(b.allPolygons());
  73886. this.polygons = a.allPolygons();
  73887. };
  73888. CSG.prototype.subtract = function (csg) {
  73889. var a = new Node(this.clone().polygons);
  73890. var b = new Node(csg.clone().polygons);
  73891. a.invert();
  73892. a.clipTo(b);
  73893. b.clipTo(a);
  73894. b.invert();
  73895. b.clipTo(a);
  73896. b.invert();
  73897. a.build(b.allPolygons());
  73898. a.invert();
  73899. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  73900. };
  73901. CSG.prototype.subtractInPlace = function (csg) {
  73902. var a = new Node(this.polygons);
  73903. var b = new Node(csg.polygons);
  73904. a.invert();
  73905. a.clipTo(b);
  73906. b.clipTo(a);
  73907. b.invert();
  73908. b.clipTo(a);
  73909. b.invert();
  73910. a.build(b.allPolygons());
  73911. a.invert();
  73912. this.polygons = a.allPolygons();
  73913. };
  73914. CSG.prototype.intersect = function (csg) {
  73915. var a = new Node(this.clone().polygons);
  73916. var b = new Node(csg.clone().polygons);
  73917. a.invert();
  73918. b.clipTo(a);
  73919. b.invert();
  73920. a.clipTo(b);
  73921. b.clipTo(a);
  73922. a.build(b.allPolygons());
  73923. a.invert();
  73924. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  73925. };
  73926. CSG.prototype.intersectInPlace = function (csg) {
  73927. var a = new Node(this.polygons);
  73928. var b = new Node(csg.polygons);
  73929. a.invert();
  73930. b.clipTo(a);
  73931. b.invert();
  73932. a.clipTo(b);
  73933. b.clipTo(a);
  73934. a.build(b.allPolygons());
  73935. a.invert();
  73936. this.polygons = a.allPolygons();
  73937. };
  73938. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  73939. // not modified.
  73940. CSG.prototype.inverse = function () {
  73941. var csg = this.clone();
  73942. csg.inverseInPlace();
  73943. return csg;
  73944. };
  73945. CSG.prototype.inverseInPlace = function () {
  73946. this.polygons.map(function (p) { p.flip(); });
  73947. };
  73948. // This is used to keep meshes transformations so they can be restored
  73949. // when we build back a Babylon Mesh
  73950. // NB : All CSG operations are performed in world coordinates
  73951. CSG.prototype.copyTransformAttributes = function (csg) {
  73952. this.matrix = csg.matrix;
  73953. this.position = csg.position;
  73954. this.rotation = csg.rotation;
  73955. this.scaling = csg.scaling;
  73956. this.rotationQuaternion = csg.rotationQuaternion;
  73957. return this;
  73958. };
  73959. // Build Raw mesh from CSG
  73960. // Coordinates here are in world space
  73961. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  73962. var matrix = this.matrix.clone();
  73963. matrix.invert();
  73964. 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;
  73965. if (keepSubMeshes) {
  73966. // Sort Polygons, since subMeshes are indices range
  73967. polygons.sort(function (a, b) {
  73968. if (a.shared.meshId === b.shared.meshId) {
  73969. return a.shared.subMeshId - b.shared.subMeshId;
  73970. }
  73971. else {
  73972. return a.shared.meshId - b.shared.meshId;
  73973. }
  73974. });
  73975. }
  73976. for (var i = 0, il = polygons.length; i < il; i++) {
  73977. polygon = polygons[i];
  73978. // Building SubMeshes
  73979. if (!subMesh_dict[polygon.shared.meshId]) {
  73980. subMesh_dict[polygon.shared.meshId] = {};
  73981. }
  73982. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  73983. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  73984. indexStart: +Infinity,
  73985. indexEnd: -Infinity,
  73986. materialIndex: polygon.shared.materialIndex
  73987. };
  73988. }
  73989. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  73990. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  73991. polygonIndices[0] = 0;
  73992. polygonIndices[1] = j - 1;
  73993. polygonIndices[2] = j;
  73994. for (var k = 0; k < 3; k++) {
  73995. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  73996. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  73997. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  73998. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  73999. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  74000. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  74001. // Check if 2 points can be merged
  74002. if (!(typeof vertex_idx !== 'undefined' &&
  74003. normals[vertex_idx * 3] === localNormal.x &&
  74004. normals[vertex_idx * 3 + 1] === localNormal.y &&
  74005. normals[vertex_idx * 3 + 2] === localNormal.z &&
  74006. uvs[vertex_idx * 2] === uv.x &&
  74007. uvs[vertex_idx * 2 + 1] === uv.y)) {
  74008. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  74009. uvs.push(uv.x, uv.y);
  74010. normals.push(normal.x, normal.y, normal.z);
  74011. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  74012. }
  74013. indices.push(vertex_idx);
  74014. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  74015. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  74016. currentIndex++;
  74017. }
  74018. }
  74019. }
  74020. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  74021. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  74022. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  74023. mesh.setIndices(indices, null);
  74024. if (keepSubMeshes) {
  74025. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  74026. var materialIndexOffset = 0, materialMaxIndex;
  74027. mesh.subMeshes = new Array();
  74028. for (var m in subMesh_dict) {
  74029. materialMaxIndex = -1;
  74030. for (var sm in subMesh_dict[m]) {
  74031. subMesh_obj = subMesh_dict[m][sm];
  74032. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  74033. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  74034. }
  74035. materialIndexOffset += ++materialMaxIndex;
  74036. }
  74037. }
  74038. return mesh;
  74039. };
  74040. // Build Mesh from CSG taking material and transforms into account
  74041. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  74042. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  74043. mesh.material = material;
  74044. mesh.position.copyFrom(this.position);
  74045. mesh.rotation.copyFrom(this.rotation);
  74046. if (this.rotationQuaternion) {
  74047. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  74048. }
  74049. mesh.scaling.copyFrom(this.scaling);
  74050. mesh.computeWorldMatrix(true);
  74051. return mesh;
  74052. };
  74053. return CSG;
  74054. }());
  74055. BABYLON.CSG = CSG;
  74056. })(BABYLON || (BABYLON = {}));
  74057. //# sourceMappingURL=babylon.csg.js.map
  74058. var BABYLON;
  74059. (function (BABYLON) {
  74060. var LensFlare = /** @class */ (function () {
  74061. function LensFlare(size, position, color, imgUrl, system) {
  74062. this.size = size;
  74063. this.position = position;
  74064. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  74065. this.color = color || new BABYLON.Color3(1, 1, 1);
  74066. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  74067. this._system = system;
  74068. system.lensFlares.push(this);
  74069. }
  74070. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  74071. return new LensFlare(size, position, color, imgUrl, system);
  74072. };
  74073. LensFlare.prototype.dispose = function () {
  74074. if (this.texture) {
  74075. this.texture.dispose();
  74076. }
  74077. // Remove from scene
  74078. var index = this._system.lensFlares.indexOf(this);
  74079. this._system.lensFlares.splice(index, 1);
  74080. };
  74081. ;
  74082. return LensFlare;
  74083. }());
  74084. BABYLON.LensFlare = LensFlare;
  74085. })(BABYLON || (BABYLON = {}));
  74086. //# sourceMappingURL=babylon.lensFlare.js.map
  74087. var BABYLON;
  74088. (function (BABYLON) {
  74089. var LensFlareSystem = /** @class */ (function () {
  74090. function LensFlareSystem(name, emitter, scene) {
  74091. this.name = name;
  74092. this.lensFlares = new Array();
  74093. this.borderLimit = 300;
  74094. this.viewportBorder = 0;
  74095. this.layerMask = 0x0FFFFFFF;
  74096. this._vertexBuffers = {};
  74097. this._isEnabled = true;
  74098. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  74099. this._emitter = emitter;
  74100. this.id = name;
  74101. scene.lensFlareSystems.push(this);
  74102. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  74103. var engine = scene.getEngine();
  74104. // VBO
  74105. var vertices = [];
  74106. vertices.push(1, 1);
  74107. vertices.push(-1, 1);
  74108. vertices.push(-1, -1);
  74109. vertices.push(1, -1);
  74110. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  74111. // Indices
  74112. var indices = [];
  74113. indices.push(0);
  74114. indices.push(1);
  74115. indices.push(2);
  74116. indices.push(0);
  74117. indices.push(2);
  74118. indices.push(3);
  74119. this._indexBuffer = engine.createIndexBuffer(indices);
  74120. // Effects
  74121. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  74122. }
  74123. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  74124. get: function () {
  74125. return this._isEnabled;
  74126. },
  74127. set: function (value) {
  74128. this._isEnabled = value;
  74129. },
  74130. enumerable: true,
  74131. configurable: true
  74132. });
  74133. LensFlareSystem.prototype.getScene = function () {
  74134. return this._scene;
  74135. };
  74136. LensFlareSystem.prototype.getEmitter = function () {
  74137. return this._emitter;
  74138. };
  74139. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  74140. this._emitter = newEmitter;
  74141. };
  74142. LensFlareSystem.prototype.getEmitterPosition = function () {
  74143. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  74144. };
  74145. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  74146. var position = this.getEmitterPosition();
  74147. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  74148. this._positionX = position.x;
  74149. this._positionY = position.y;
  74150. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  74151. if (this.viewportBorder > 0) {
  74152. globalViewport.x -= this.viewportBorder;
  74153. globalViewport.y -= this.viewportBorder;
  74154. globalViewport.width += this.viewportBorder * 2;
  74155. globalViewport.height += this.viewportBorder * 2;
  74156. position.x += this.viewportBorder;
  74157. position.y += this.viewportBorder;
  74158. this._positionX += this.viewportBorder;
  74159. this._positionY += this.viewportBorder;
  74160. }
  74161. if (position.z > 0) {
  74162. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  74163. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  74164. return true;
  74165. }
  74166. return true;
  74167. }
  74168. return false;
  74169. };
  74170. LensFlareSystem.prototype._isVisible = function () {
  74171. if (!this._isEnabled || !this._scene.activeCamera) {
  74172. return false;
  74173. }
  74174. var emitterPosition = this.getEmitterPosition();
  74175. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  74176. var distance = direction.length();
  74177. direction.normalize();
  74178. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  74179. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  74180. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  74181. };
  74182. LensFlareSystem.prototype.render = function () {
  74183. if (!this._effect.isReady() || !this._scene.activeCamera)
  74184. return false;
  74185. var engine = this._scene.getEngine();
  74186. var viewport = this._scene.activeCamera.viewport;
  74187. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  74188. // Position
  74189. if (!this.computeEffectivePosition(globalViewport)) {
  74190. return false;
  74191. }
  74192. // Visibility
  74193. if (!this._isVisible()) {
  74194. return false;
  74195. }
  74196. // Intensity
  74197. var awayX;
  74198. var awayY;
  74199. if (this._positionX < this.borderLimit + globalViewport.x) {
  74200. awayX = this.borderLimit + globalViewport.x - this._positionX;
  74201. }
  74202. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  74203. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  74204. }
  74205. else {
  74206. awayX = 0;
  74207. }
  74208. if (this._positionY < this.borderLimit + globalViewport.y) {
  74209. awayY = this.borderLimit + globalViewport.y - this._positionY;
  74210. }
  74211. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  74212. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  74213. }
  74214. else {
  74215. awayY = 0;
  74216. }
  74217. var away = (awayX > awayY) ? awayX : awayY;
  74218. away -= this.viewportBorder;
  74219. if (away > this.borderLimit) {
  74220. away = this.borderLimit;
  74221. }
  74222. var intensity = 1.0 - (away / this.borderLimit);
  74223. if (intensity < 0) {
  74224. return false;
  74225. }
  74226. if (intensity > 1.0) {
  74227. intensity = 1.0;
  74228. }
  74229. if (this.viewportBorder > 0) {
  74230. globalViewport.x += this.viewportBorder;
  74231. globalViewport.y += this.viewportBorder;
  74232. globalViewport.width -= this.viewportBorder * 2;
  74233. globalViewport.height -= this.viewportBorder * 2;
  74234. this._positionX -= this.viewportBorder;
  74235. this._positionY -= this.viewportBorder;
  74236. }
  74237. // Position
  74238. var centerX = globalViewport.x + globalViewport.width / 2;
  74239. var centerY = globalViewport.y + globalViewport.height / 2;
  74240. var distX = centerX - this._positionX;
  74241. var distY = centerY - this._positionY;
  74242. // Effects
  74243. engine.enableEffect(this._effect);
  74244. engine.setState(false);
  74245. engine.setDepthBuffer(false);
  74246. // VBOs
  74247. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  74248. // Flares
  74249. for (var index = 0; index < this.lensFlares.length; index++) {
  74250. var flare = this.lensFlares[index];
  74251. engine.setAlphaMode(flare.alphaMode);
  74252. var x = centerX - (distX * flare.position);
  74253. var y = centerY - (distY * flare.position);
  74254. var cw = flare.size;
  74255. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  74256. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  74257. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  74258. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  74259. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  74260. // Texture
  74261. this._effect.setTexture("textureSampler", flare.texture);
  74262. // Color
  74263. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  74264. // Draw order
  74265. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  74266. }
  74267. engine.setDepthBuffer(true);
  74268. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  74269. return true;
  74270. };
  74271. LensFlareSystem.prototype.dispose = function () {
  74272. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  74273. if (vertexBuffer) {
  74274. vertexBuffer.dispose();
  74275. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  74276. }
  74277. if (this._indexBuffer) {
  74278. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  74279. this._indexBuffer = null;
  74280. }
  74281. while (this.lensFlares.length) {
  74282. this.lensFlares[0].dispose();
  74283. }
  74284. // Remove from scene
  74285. var index = this._scene.lensFlareSystems.indexOf(this);
  74286. this._scene.lensFlareSystems.splice(index, 1);
  74287. };
  74288. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  74289. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  74290. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  74291. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  74292. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  74293. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  74294. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  74295. var parsedFlare = parsedLensFlareSystem.flares[index];
  74296. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  74297. }
  74298. return lensFlareSystem;
  74299. };
  74300. LensFlareSystem.prototype.serialize = function () {
  74301. var serializationObject = {};
  74302. serializationObject.id = this.id;
  74303. serializationObject.name = this.name;
  74304. serializationObject.emitterId = this.getEmitter().id;
  74305. serializationObject.borderLimit = this.borderLimit;
  74306. serializationObject.flares = [];
  74307. for (var index = 0; index < this.lensFlares.length; index++) {
  74308. var flare = this.lensFlares[index];
  74309. serializationObject.flares.push({
  74310. size: flare.size,
  74311. position: flare.position,
  74312. color: flare.color.asArray(),
  74313. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  74314. });
  74315. }
  74316. return serializationObject;
  74317. };
  74318. return LensFlareSystem;
  74319. }());
  74320. BABYLON.LensFlareSystem = LensFlareSystem;
  74321. })(BABYLON || (BABYLON = {}));
  74322. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  74323. var BABYLON;
  74324. (function (BABYLON) {
  74325. /**
  74326. * This is a holder class for the physics joint created by the physics plugin.
  74327. * It holds a set of functions to control the underlying joint.
  74328. */
  74329. var PhysicsJoint = /** @class */ (function () {
  74330. function PhysicsJoint(type, jointData) {
  74331. this.type = type;
  74332. this.jointData = jointData;
  74333. jointData.nativeParams = jointData.nativeParams || {};
  74334. }
  74335. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  74336. get: function () {
  74337. return this._physicsJoint;
  74338. },
  74339. set: function (newJoint) {
  74340. if (this._physicsJoint) {
  74341. //remove from the wolrd
  74342. }
  74343. this._physicsJoint = newJoint;
  74344. },
  74345. enumerable: true,
  74346. configurable: true
  74347. });
  74348. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  74349. set: function (physicsPlugin) {
  74350. this._physicsPlugin = physicsPlugin;
  74351. },
  74352. enumerable: true,
  74353. configurable: true
  74354. });
  74355. /**
  74356. * Execute a function that is physics-plugin specific.
  74357. * @param {Function} func the function that will be executed.
  74358. * It accepts two parameters: the physics world and the physics joint.
  74359. */
  74360. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  74361. func(this._physicsPlugin.world, this._physicsJoint);
  74362. };
  74363. //TODO check if the native joints are the same
  74364. //Joint Types
  74365. PhysicsJoint.DistanceJoint = 0;
  74366. PhysicsJoint.HingeJoint = 1;
  74367. PhysicsJoint.BallAndSocketJoint = 2;
  74368. PhysicsJoint.WheelJoint = 3;
  74369. PhysicsJoint.SliderJoint = 4;
  74370. //OIMO
  74371. PhysicsJoint.PrismaticJoint = 5;
  74372. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  74373. PhysicsJoint.UniversalJoint = 6;
  74374. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  74375. //Cannon
  74376. //Similar to a Ball-Joint. Different in params
  74377. PhysicsJoint.PointToPointJoint = 8;
  74378. //Cannon only at the moment
  74379. PhysicsJoint.SpringJoint = 9;
  74380. PhysicsJoint.LockJoint = 10;
  74381. return PhysicsJoint;
  74382. }());
  74383. BABYLON.PhysicsJoint = PhysicsJoint;
  74384. /**
  74385. * A class representing a physics distance joint.
  74386. */
  74387. var DistanceJoint = /** @class */ (function (_super) {
  74388. __extends(DistanceJoint, _super);
  74389. function DistanceJoint(jointData) {
  74390. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  74391. }
  74392. /**
  74393. * Update the predefined distance.
  74394. */
  74395. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  74396. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  74397. };
  74398. return DistanceJoint;
  74399. }(PhysicsJoint));
  74400. BABYLON.DistanceJoint = DistanceJoint;
  74401. var MotorEnabledJoint = /** @class */ (function (_super) {
  74402. __extends(MotorEnabledJoint, _super);
  74403. function MotorEnabledJoint(type, jointData) {
  74404. return _super.call(this, type, jointData) || this;
  74405. }
  74406. /**
  74407. * Set the motor values.
  74408. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74409. * @param {number} force the force to apply
  74410. * @param {number} maxForce max force for this motor.
  74411. */
  74412. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  74413. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  74414. };
  74415. /**
  74416. * Set the motor's limits.
  74417. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74418. */
  74419. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  74420. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  74421. };
  74422. return MotorEnabledJoint;
  74423. }(PhysicsJoint));
  74424. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  74425. /**
  74426. * This class represents a single hinge physics joint
  74427. */
  74428. var HingeJoint = /** @class */ (function (_super) {
  74429. __extends(HingeJoint, _super);
  74430. function HingeJoint(jointData) {
  74431. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  74432. }
  74433. /**
  74434. * Set the motor values.
  74435. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74436. * @param {number} force the force to apply
  74437. * @param {number} maxForce max force for this motor.
  74438. */
  74439. HingeJoint.prototype.setMotor = function (force, maxForce) {
  74440. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  74441. };
  74442. /**
  74443. * Set the motor's limits.
  74444. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74445. */
  74446. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  74447. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  74448. };
  74449. return HingeJoint;
  74450. }(MotorEnabledJoint));
  74451. BABYLON.HingeJoint = HingeJoint;
  74452. /**
  74453. * This class represents a dual hinge physics joint (same as wheel joint)
  74454. */
  74455. var Hinge2Joint = /** @class */ (function (_super) {
  74456. __extends(Hinge2Joint, _super);
  74457. function Hinge2Joint(jointData) {
  74458. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  74459. }
  74460. /**
  74461. * Set the motor values.
  74462. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74463. * @param {number} force the force to apply
  74464. * @param {number} maxForce max force for this motor.
  74465. * @param {motorIndex} the motor's index, 0 or 1.
  74466. */
  74467. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  74468. if (motorIndex === void 0) { motorIndex = 0; }
  74469. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  74470. };
  74471. /**
  74472. * Set the motor limits.
  74473. * Attention, this function is plugin specific. Engines won't react 100% the same.
  74474. * @param {number} upperLimit the upper limit
  74475. * @param {number} lowerLimit lower limit
  74476. * @param {motorIndex} the motor's index, 0 or 1.
  74477. */
  74478. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  74479. if (motorIndex === void 0) { motorIndex = 0; }
  74480. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  74481. };
  74482. return Hinge2Joint;
  74483. }(MotorEnabledJoint));
  74484. BABYLON.Hinge2Joint = Hinge2Joint;
  74485. })(BABYLON || (BABYLON = {}));
  74486. //# sourceMappingURL=babylon.physicsJoint.js.map
  74487. var BABYLON;
  74488. (function (BABYLON) {
  74489. var PhysicsImpostor = /** @class */ (function () {
  74490. function PhysicsImpostor(object, type, _options, _scene) {
  74491. if (_options === void 0) { _options = { mass: 0 }; }
  74492. var _this = this;
  74493. this.object = object;
  74494. this.type = type;
  74495. this._options = _options;
  74496. this._scene = _scene;
  74497. this._bodyUpdateRequired = false;
  74498. this._onBeforePhysicsStepCallbacks = new Array();
  74499. this._onAfterPhysicsStepCallbacks = new Array();
  74500. this._onPhysicsCollideCallbacks = [];
  74501. this._deltaPosition = BABYLON.Vector3.Zero();
  74502. this._isDisposed = false;
  74503. //temp variables for parent rotation calculations
  74504. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  74505. this._tmpQuat = new BABYLON.Quaternion();
  74506. this._tmpQuat2 = new BABYLON.Quaternion();
  74507. /**
  74508. * this function is executed by the physics engine.
  74509. */
  74510. this.beforeStep = function () {
  74511. if (!_this._physicsEngine) {
  74512. return;
  74513. }
  74514. _this.object.translate(_this._deltaPosition, -1);
  74515. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  74516. _this.object.computeWorldMatrix(false);
  74517. if (_this.object.parent && _this.object.rotationQuaternion) {
  74518. _this.getParentsRotation();
  74519. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  74520. }
  74521. else {
  74522. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  74523. }
  74524. if (!_this._options.disableBidirectionalTransformation) {
  74525. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  74526. }
  74527. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  74528. func(_this);
  74529. });
  74530. };
  74531. /**
  74532. * this function is executed by the physics engine.
  74533. */
  74534. this.afterStep = function () {
  74535. if (!_this._physicsEngine) {
  74536. return;
  74537. }
  74538. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  74539. func(_this);
  74540. });
  74541. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  74542. // object has now its world rotation. needs to be converted to local.
  74543. if (_this.object.parent && _this.object.rotationQuaternion) {
  74544. _this.getParentsRotation();
  74545. _this._tmpQuat.conjugateInPlace();
  74546. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  74547. }
  74548. // take the position set and make it the absolute position of this object.
  74549. _this.object.setAbsolutePosition(_this.object.position);
  74550. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  74551. _this.object.translate(_this._deltaPosition, 1);
  74552. };
  74553. /**
  74554. * Legacy collision detection event support
  74555. */
  74556. this.onCollideEvent = null;
  74557. //event and body object due to cannon's event-based architecture.
  74558. this.onCollide = function (e) {
  74559. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  74560. return;
  74561. }
  74562. if (!_this._physicsEngine) {
  74563. return;
  74564. }
  74565. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  74566. if (otherImpostor) {
  74567. // Legacy collision detection event support
  74568. if (_this.onCollideEvent) {
  74569. _this.onCollideEvent(_this, otherImpostor);
  74570. }
  74571. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  74572. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  74573. }).forEach(function (obj) {
  74574. obj.callback(_this, otherImpostor);
  74575. });
  74576. }
  74577. };
  74578. //sanity check!
  74579. if (!this.object) {
  74580. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  74581. return;
  74582. }
  74583. //legacy support for old syntax.
  74584. if (!this._scene && object.getScene) {
  74585. this._scene = object.getScene();
  74586. }
  74587. if (!this._scene) {
  74588. return;
  74589. }
  74590. this._physicsEngine = this._scene.getPhysicsEngine();
  74591. if (!this._physicsEngine) {
  74592. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  74593. }
  74594. else {
  74595. //set the object's quaternion, if not set
  74596. if (!this.object.rotationQuaternion) {
  74597. if (this.object.rotation) {
  74598. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  74599. }
  74600. else {
  74601. this.object.rotationQuaternion = new BABYLON.Quaternion();
  74602. }
  74603. }
  74604. //default options params
  74605. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  74606. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  74607. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  74608. this._joints = [];
  74609. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  74610. if (!this.object.parent || this._options.ignoreParent) {
  74611. this._init();
  74612. }
  74613. else if (this.object.parent.physicsImpostor) {
  74614. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  74615. }
  74616. }
  74617. }
  74618. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  74619. get: function () {
  74620. return this._isDisposed;
  74621. },
  74622. enumerable: true,
  74623. configurable: true
  74624. });
  74625. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  74626. get: function () {
  74627. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  74628. },
  74629. set: function (value) {
  74630. this.setMass(value);
  74631. },
  74632. enumerable: true,
  74633. configurable: true
  74634. });
  74635. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  74636. get: function () {
  74637. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  74638. },
  74639. set: function (value) {
  74640. if (!this._physicsEngine) {
  74641. return;
  74642. }
  74643. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  74644. },
  74645. enumerable: true,
  74646. configurable: true
  74647. });
  74648. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  74649. get: function () {
  74650. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  74651. },
  74652. set: function (value) {
  74653. if (!this._physicsEngine) {
  74654. return;
  74655. }
  74656. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  74657. },
  74658. enumerable: true,
  74659. configurable: true
  74660. });
  74661. /**
  74662. * This function will completly initialize this impostor.
  74663. * It will create a new body - but only if this mesh has no parent.
  74664. * If it has, this impostor will not be used other than to define the impostor
  74665. * of the child mesh.
  74666. */
  74667. PhysicsImpostor.prototype._init = function () {
  74668. if (!this._physicsEngine) {
  74669. return;
  74670. }
  74671. this._physicsEngine.removeImpostor(this);
  74672. this.physicsBody = null;
  74673. this._parent = this._parent || this._getPhysicsParent();
  74674. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  74675. this._physicsEngine.addImpostor(this);
  74676. }
  74677. };
  74678. PhysicsImpostor.prototype._getPhysicsParent = function () {
  74679. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  74680. var parentMesh = this.object.parent;
  74681. return parentMesh.physicsImpostor;
  74682. }
  74683. return null;
  74684. };
  74685. /**
  74686. * Should a new body be generated.
  74687. */
  74688. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  74689. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  74690. };
  74691. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  74692. this.forceUpdate();
  74693. };
  74694. /**
  74695. * Force a regeneration of this or the parent's impostor's body.
  74696. * Use under cautious - This will remove all joints already implemented.
  74697. */
  74698. PhysicsImpostor.prototype.forceUpdate = function () {
  74699. this._init();
  74700. if (this.parent && !this._options.ignoreParent) {
  74701. this.parent.forceUpdate();
  74702. }
  74703. };
  74704. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  74705. /*public get mesh(): AbstractMesh {
  74706. return this._mesh;
  74707. }*/
  74708. /**
  74709. * Gets the body that holds this impostor. Either its own, or its parent.
  74710. */
  74711. get: function () {
  74712. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  74713. },
  74714. /**
  74715. * Set the physics body. Used mainly by the physics engine/plugin
  74716. */
  74717. set: function (physicsBody) {
  74718. if (this._physicsBody && this._physicsEngine) {
  74719. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  74720. }
  74721. this._physicsBody = physicsBody;
  74722. this.resetUpdateFlags();
  74723. },
  74724. enumerable: true,
  74725. configurable: true
  74726. });
  74727. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  74728. get: function () {
  74729. return !this._options.ignoreParent && this._parent ? this._parent : null;
  74730. },
  74731. set: function (value) {
  74732. this._parent = value;
  74733. },
  74734. enumerable: true,
  74735. configurable: true
  74736. });
  74737. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  74738. this._bodyUpdateRequired = false;
  74739. };
  74740. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  74741. if (this.object.getBoundingInfo) {
  74742. var q = this.object.rotationQuaternion;
  74743. //reset rotation
  74744. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  74745. //calculate the world matrix with no rotation
  74746. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  74747. var boundingInfo = this.object.getBoundingInfo();
  74748. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  74749. //bring back the rotation
  74750. this.object.rotationQuaternion = q;
  74751. //calculate the world matrix with the new rotation
  74752. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  74753. return size;
  74754. }
  74755. else {
  74756. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  74757. }
  74758. };
  74759. PhysicsImpostor.prototype.getObjectCenter = function () {
  74760. if (this.object.getBoundingInfo) {
  74761. var boundingInfo = this.object.getBoundingInfo();
  74762. return boundingInfo.boundingBox.centerWorld;
  74763. }
  74764. else {
  74765. return this.object.position;
  74766. }
  74767. };
  74768. /**
  74769. * Get a specific parametes from the options parameter.
  74770. */
  74771. PhysicsImpostor.prototype.getParam = function (paramName) {
  74772. return this._options[paramName];
  74773. };
  74774. /**
  74775. * Sets a specific parameter in the options given to the physics plugin
  74776. */
  74777. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  74778. this._options[paramName] = value;
  74779. this._bodyUpdateRequired = true;
  74780. };
  74781. /**
  74782. * Specifically change the body's mass option. Won't recreate the physics body object
  74783. */
  74784. PhysicsImpostor.prototype.setMass = function (mass) {
  74785. if (this.getParam("mass") !== mass) {
  74786. this.setParam("mass", mass);
  74787. }
  74788. if (this._physicsEngine) {
  74789. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  74790. }
  74791. };
  74792. PhysicsImpostor.prototype.getLinearVelocity = function () {
  74793. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  74794. };
  74795. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  74796. if (this._physicsEngine) {
  74797. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  74798. }
  74799. };
  74800. PhysicsImpostor.prototype.getAngularVelocity = function () {
  74801. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  74802. };
  74803. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  74804. if (this._physicsEngine) {
  74805. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  74806. }
  74807. };
  74808. /**
  74809. * Execute a function with the physics plugin native code.
  74810. * Provide a function the will have two variables - the world object and the physics body object.
  74811. */
  74812. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  74813. if (this._physicsEngine) {
  74814. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  74815. }
  74816. };
  74817. /**
  74818. * Register a function that will be executed before the physics world is stepping forward.
  74819. */
  74820. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  74821. this._onBeforePhysicsStepCallbacks.push(func);
  74822. };
  74823. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  74824. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  74825. if (index > -1) {
  74826. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  74827. }
  74828. else {
  74829. BABYLON.Tools.Warn("Function to remove was not found");
  74830. }
  74831. };
  74832. /**
  74833. * Register a function that will be executed after the physics step
  74834. */
  74835. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  74836. this._onAfterPhysicsStepCallbacks.push(func);
  74837. };
  74838. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  74839. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  74840. if (index > -1) {
  74841. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  74842. }
  74843. else {
  74844. BABYLON.Tools.Warn("Function to remove was not found");
  74845. }
  74846. };
  74847. /**
  74848. * register a function that will be executed when this impostor collides against a different body.
  74849. */
  74850. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  74851. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  74852. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  74853. };
  74854. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  74855. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  74856. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  74857. if (index > -1) {
  74858. this._onPhysicsCollideCallbacks.splice(index, 1);
  74859. }
  74860. else {
  74861. BABYLON.Tools.Warn("Function to remove was not found");
  74862. }
  74863. };
  74864. PhysicsImpostor.prototype.getParentsRotation = function () {
  74865. var parent = this.object.parent;
  74866. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  74867. while (parent) {
  74868. if (parent.rotationQuaternion) {
  74869. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  74870. }
  74871. else {
  74872. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  74873. }
  74874. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  74875. parent = parent.parent;
  74876. }
  74877. return this._tmpQuat;
  74878. };
  74879. /**
  74880. * Apply a force
  74881. */
  74882. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  74883. if (this._physicsEngine) {
  74884. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  74885. }
  74886. return this;
  74887. };
  74888. /**
  74889. * Apply an impulse
  74890. */
  74891. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  74892. if (this._physicsEngine) {
  74893. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  74894. }
  74895. return this;
  74896. };
  74897. /**
  74898. * A help function to create a joint.
  74899. */
  74900. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  74901. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  74902. this.addJoint(otherImpostor, joint);
  74903. return this;
  74904. };
  74905. /**
  74906. * Add a joint to this impostor with a different impostor.
  74907. */
  74908. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  74909. this._joints.push({
  74910. otherImpostor: otherImpostor,
  74911. joint: joint
  74912. });
  74913. if (this._physicsEngine) {
  74914. this._physicsEngine.addJoint(this, otherImpostor, joint);
  74915. }
  74916. return this;
  74917. };
  74918. /**
  74919. * Will keep this body still, in a sleep mode.
  74920. */
  74921. PhysicsImpostor.prototype.sleep = function () {
  74922. if (this._physicsEngine) {
  74923. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  74924. }
  74925. return this;
  74926. };
  74927. /**
  74928. * Wake the body up.
  74929. */
  74930. PhysicsImpostor.prototype.wakeUp = function () {
  74931. if (this._physicsEngine) {
  74932. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  74933. }
  74934. return this;
  74935. };
  74936. PhysicsImpostor.prototype.clone = function (newObject) {
  74937. if (!newObject)
  74938. return null;
  74939. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  74940. };
  74941. PhysicsImpostor.prototype.dispose = function () {
  74942. var _this = this;
  74943. //no dispose if no physics engine is available.
  74944. if (!this._physicsEngine) {
  74945. return;
  74946. }
  74947. this._joints.forEach(function (j) {
  74948. if (_this._physicsEngine) {
  74949. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  74950. }
  74951. });
  74952. //dispose the physics body
  74953. this._physicsEngine.removeImpostor(this);
  74954. if (this.parent) {
  74955. this.parent.forceUpdate();
  74956. }
  74957. else {
  74958. /*this._object.getChildMeshes().forEach(function(mesh) {
  74959. if (mesh.physicsImpostor) {
  74960. if (disposeChildren) {
  74961. mesh.physicsImpostor.dispose();
  74962. mesh.physicsImpostor = null;
  74963. }
  74964. }
  74965. })*/
  74966. }
  74967. this._isDisposed = true;
  74968. };
  74969. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  74970. this._deltaPosition.copyFrom(position);
  74971. };
  74972. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  74973. if (!this._deltaRotation) {
  74974. this._deltaRotation = new BABYLON.Quaternion();
  74975. }
  74976. this._deltaRotation.copyFrom(rotation);
  74977. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  74978. };
  74979. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  74980. if (this._physicsEngine) {
  74981. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  74982. }
  74983. return this;
  74984. };
  74985. PhysicsImpostor.prototype.getRadius = function () {
  74986. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  74987. };
  74988. /**
  74989. * Sync a bone with this impostor
  74990. * @param bone The bone to sync to the impostor.
  74991. * @param boneMesh The mesh that the bone is influencing.
  74992. * @param jointPivot The pivot of the joint / bone in local space.
  74993. * @param distToJoint Optional distance from the impostor to the joint.
  74994. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  74995. */
  74996. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  74997. var tempVec = PhysicsImpostor._tmpVecs[0];
  74998. var mesh = this.object;
  74999. if (mesh.rotationQuaternion) {
  75000. if (adjustRotation) {
  75001. var tempQuat = PhysicsImpostor._tmpQuat;
  75002. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  75003. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  75004. }
  75005. else {
  75006. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  75007. }
  75008. }
  75009. tempVec.x = 0;
  75010. tempVec.y = 0;
  75011. tempVec.z = 0;
  75012. if (jointPivot) {
  75013. tempVec.x = jointPivot.x;
  75014. tempVec.y = jointPivot.y;
  75015. tempVec.z = jointPivot.z;
  75016. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  75017. if (distToJoint === undefined || distToJoint === null) {
  75018. distToJoint = jointPivot.length();
  75019. }
  75020. tempVec.x *= distToJoint;
  75021. tempVec.y *= distToJoint;
  75022. tempVec.z *= distToJoint;
  75023. }
  75024. if (bone.getParent()) {
  75025. tempVec.addInPlace(mesh.getAbsolutePosition());
  75026. bone.setAbsolutePosition(tempVec, boneMesh);
  75027. }
  75028. else {
  75029. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  75030. boneMesh.position.x -= tempVec.x;
  75031. boneMesh.position.y -= tempVec.y;
  75032. boneMesh.position.z -= tempVec.z;
  75033. }
  75034. };
  75035. /**
  75036. * Sync impostor to a bone
  75037. * @param bone The bone that the impostor will be synced to.
  75038. * @param boneMesh The mesh that the bone is influencing.
  75039. * @param jointPivot The pivot of the joint / bone in local space.
  75040. * @param distToJoint Optional distance from the impostor to the joint.
  75041. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  75042. * @param boneAxis Optional vector3 axis the bone is aligned with
  75043. */
  75044. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  75045. var mesh = this.object;
  75046. if (mesh.rotationQuaternion) {
  75047. if (adjustRotation) {
  75048. var tempQuat = PhysicsImpostor._tmpQuat;
  75049. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  75050. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  75051. }
  75052. else {
  75053. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  75054. }
  75055. }
  75056. var pos = PhysicsImpostor._tmpVecs[0];
  75057. var boneDir = PhysicsImpostor._tmpVecs[1];
  75058. if (!boneAxis) {
  75059. boneAxis = PhysicsImpostor._tmpVecs[2];
  75060. boneAxis.x = 0;
  75061. boneAxis.y = 1;
  75062. boneAxis.z = 0;
  75063. }
  75064. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  75065. bone.getAbsolutePositionToRef(boneMesh, pos);
  75066. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  75067. distToJoint = jointPivot.length();
  75068. }
  75069. if (distToJoint !== undefined && distToJoint !== null) {
  75070. pos.x += boneDir.x * distToJoint;
  75071. pos.y += boneDir.y * distToJoint;
  75072. pos.z += boneDir.z * distToJoint;
  75073. }
  75074. mesh.setAbsolutePosition(pos);
  75075. };
  75076. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  75077. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  75078. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  75079. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  75080. //Impostor types
  75081. PhysicsImpostor.NoImpostor = 0;
  75082. PhysicsImpostor.SphereImpostor = 1;
  75083. PhysicsImpostor.BoxImpostor = 2;
  75084. PhysicsImpostor.PlaneImpostor = 3;
  75085. PhysicsImpostor.MeshImpostor = 4;
  75086. PhysicsImpostor.CylinderImpostor = 7;
  75087. PhysicsImpostor.ParticleImpostor = 8;
  75088. PhysicsImpostor.HeightmapImpostor = 9;
  75089. return PhysicsImpostor;
  75090. }());
  75091. BABYLON.PhysicsImpostor = PhysicsImpostor;
  75092. })(BABYLON || (BABYLON = {}));
  75093. //# sourceMappingURL=babylon.physicsImpostor.js.map
  75094. var BABYLON;
  75095. (function (BABYLON) {
  75096. var PhysicsEngine = /** @class */ (function () {
  75097. function PhysicsEngine(gravity, _physicsPlugin) {
  75098. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  75099. this._physicsPlugin = _physicsPlugin;
  75100. //new methods and parameters
  75101. this._impostors = [];
  75102. this._joints = [];
  75103. if (!this._physicsPlugin.isSupported()) {
  75104. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  75105. + "Please make sure it is included.");
  75106. }
  75107. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  75108. this.setGravity(gravity);
  75109. this.setTimeStep();
  75110. }
  75111. PhysicsEngine.prototype.setGravity = function (gravity) {
  75112. this.gravity = gravity;
  75113. this._physicsPlugin.setGravity(this.gravity);
  75114. };
  75115. /**
  75116. * Set the time step of the physics engine.
  75117. * default is 1/60.
  75118. * To slow it down, enter 1/600 for example.
  75119. * To speed it up, 1/30
  75120. * @param {number} newTimeStep the new timestep to apply to this world.
  75121. */
  75122. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  75123. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  75124. this._physicsPlugin.setTimeStep(newTimeStep);
  75125. };
  75126. /**
  75127. * Get the time step of the physics engine.
  75128. */
  75129. PhysicsEngine.prototype.getTimeStep = function () {
  75130. return this._physicsPlugin.getTimeStep();
  75131. };
  75132. PhysicsEngine.prototype.dispose = function () {
  75133. this._impostors.forEach(function (impostor) {
  75134. impostor.dispose();
  75135. });
  75136. this._physicsPlugin.dispose();
  75137. };
  75138. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  75139. return this._physicsPlugin.name;
  75140. };
  75141. /**
  75142. * Adding a new impostor for the impostor tracking.
  75143. * This will be done by the impostor itself.
  75144. * @param {PhysicsImpostor} impostor the impostor to add
  75145. */
  75146. PhysicsEngine.prototype.addImpostor = function (impostor) {
  75147. impostor.uniqueId = this._impostors.push(impostor);
  75148. //if no parent, generate the body
  75149. if (!impostor.parent) {
  75150. this._physicsPlugin.generatePhysicsBody(impostor);
  75151. }
  75152. };
  75153. /**
  75154. * Remove an impostor from the engine.
  75155. * This impostor and its mesh will not longer be updated by the physics engine.
  75156. * @param {PhysicsImpostor} impostor the impostor to remove
  75157. */
  75158. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  75159. var index = this._impostors.indexOf(impostor);
  75160. if (index > -1) {
  75161. var removed = this._impostors.splice(index, 1);
  75162. //Is it needed?
  75163. if (removed.length) {
  75164. //this will also remove it from the world.
  75165. removed[0].physicsBody = null;
  75166. }
  75167. }
  75168. };
  75169. /**
  75170. * Add a joint to the physics engine
  75171. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  75172. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  75173. * @param {PhysicsJoint} the joint that will connect both impostors.
  75174. */
  75175. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  75176. var impostorJoint = {
  75177. mainImpostor: mainImpostor,
  75178. connectedImpostor: connectedImpostor,
  75179. joint: joint
  75180. };
  75181. joint.physicsPlugin = this._physicsPlugin;
  75182. this._joints.push(impostorJoint);
  75183. this._physicsPlugin.generateJoint(impostorJoint);
  75184. };
  75185. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  75186. var matchingJoints = this._joints.filter(function (impostorJoint) {
  75187. return (impostorJoint.connectedImpostor === connectedImpostor
  75188. && impostorJoint.joint === joint
  75189. && impostorJoint.mainImpostor === mainImpostor);
  75190. });
  75191. if (matchingJoints.length) {
  75192. this._physicsPlugin.removeJoint(matchingJoints[0]);
  75193. //TODO remove it from the list as well
  75194. }
  75195. };
  75196. /**
  75197. * Called by the scene. no need to call it.
  75198. */
  75199. PhysicsEngine.prototype._step = function (delta) {
  75200. var _this = this;
  75201. //check if any mesh has no body / requires an update
  75202. this._impostors.forEach(function (impostor) {
  75203. if (impostor.isBodyInitRequired()) {
  75204. _this._physicsPlugin.generatePhysicsBody(impostor);
  75205. }
  75206. });
  75207. if (delta > 0.1) {
  75208. delta = 0.1;
  75209. }
  75210. else if (delta <= 0) {
  75211. delta = 1.0 / 60.0;
  75212. }
  75213. this._physicsPlugin.executeStep(delta, this._impostors);
  75214. };
  75215. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  75216. return this._physicsPlugin;
  75217. };
  75218. PhysicsEngine.prototype.getImpostors = function () {
  75219. return this._impostors;
  75220. };
  75221. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  75222. for (var i = 0; i < this._impostors.length; ++i) {
  75223. if (this._impostors[i].object === object) {
  75224. return this._impostors[i];
  75225. }
  75226. }
  75227. return null;
  75228. };
  75229. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  75230. for (var i = 0; i < this._impostors.length; ++i) {
  75231. if (this._impostors[i].physicsBody === body) {
  75232. return this._impostors[i];
  75233. }
  75234. }
  75235. return null;
  75236. };
  75237. // Statics
  75238. PhysicsEngine.Epsilon = 0.001;
  75239. return PhysicsEngine;
  75240. }());
  75241. BABYLON.PhysicsEngine = PhysicsEngine;
  75242. })(BABYLON || (BABYLON = {}));
  75243. //# sourceMappingURL=babylon.physicsEngine.js.map
  75244. var BABYLON;
  75245. (function (BABYLON) {
  75246. var PhysicsHelper = /** @class */ (function () {
  75247. function PhysicsHelper(scene) {
  75248. this._scene = scene;
  75249. this._physicsEngine = this._scene.getPhysicsEngine();
  75250. if (!this._physicsEngine) {
  75251. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  75252. }
  75253. }
  75254. /**
  75255. * @param {Vector3} origin the origin of the explosion
  75256. * @param {number} radius the explosion radius
  75257. * @param {number} strength the explosion strength
  75258. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75259. */
  75260. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  75261. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75262. if (!this._physicsEngine) {
  75263. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  75264. return null;
  75265. }
  75266. var impostors = this._physicsEngine.getImpostors();
  75267. if (impostors.length === 0) {
  75268. return null;
  75269. }
  75270. var event = new PhysicsRadialExplosionEvent(this._scene);
  75271. impostors.forEach(function (impostor) {
  75272. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75273. if (!impostorForceAndContactPoint) {
  75274. return;
  75275. }
  75276. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75277. });
  75278. event.dispose(false);
  75279. return event;
  75280. };
  75281. /**
  75282. * @param {Vector3} origin the origin of the explosion
  75283. * @param {number} radius the explosion radius
  75284. * @param {number} strength the explosion strength
  75285. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75286. */
  75287. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  75288. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75289. if (!this._physicsEngine) {
  75290. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75291. return null;
  75292. }
  75293. var impostors = this._physicsEngine.getImpostors();
  75294. if (impostors.length === 0) {
  75295. return null;
  75296. }
  75297. var event = new PhysicsRadialExplosionEvent(this._scene);
  75298. impostors.forEach(function (impostor) {
  75299. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  75300. if (!impostorForceAndContactPoint) {
  75301. return;
  75302. }
  75303. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75304. });
  75305. event.dispose(false);
  75306. return event;
  75307. };
  75308. /**
  75309. * @param {Vector3} origin the origin of the explosion
  75310. * @param {number} radius the explosion radius
  75311. * @param {number} strength the explosion strength
  75312. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  75313. */
  75314. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  75315. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75316. if (!this._physicsEngine) {
  75317. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75318. return null;
  75319. }
  75320. var impostors = this._physicsEngine.getImpostors();
  75321. if (impostors.length === 0) {
  75322. return null;
  75323. }
  75324. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  75325. event.dispose(false);
  75326. return event;
  75327. };
  75328. /**
  75329. * @param {Vector3} origin the origin of the updraft
  75330. * @param {number} radius the radius of the updraft
  75331. * @param {number} strength the strength of the updraft
  75332. * @param {number} height the height of the updraft
  75333. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  75334. */
  75335. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  75336. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  75337. if (!this._physicsEngine) {
  75338. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75339. return null;
  75340. }
  75341. if (this._physicsEngine.getImpostors().length === 0) {
  75342. return null;
  75343. }
  75344. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  75345. event.dispose(false);
  75346. return event;
  75347. };
  75348. /**
  75349. * @param {Vector3} origin the of the vortex
  75350. * @param {number} radius the radius of the vortex
  75351. * @param {number} strength the strength of the vortex
  75352. * @param {number} height the height of the vortex
  75353. */
  75354. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  75355. if (!this._physicsEngine) {
  75356. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  75357. return null;
  75358. }
  75359. if (this._physicsEngine.getImpostors().length === 0) {
  75360. return null;
  75361. }
  75362. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  75363. event.dispose(false);
  75364. return event;
  75365. };
  75366. return PhysicsHelper;
  75367. }());
  75368. BABYLON.PhysicsHelper = PhysicsHelper;
  75369. /***** Radial explosion *****/
  75370. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  75371. function PhysicsRadialExplosionEvent(scene) {
  75372. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  75373. this._rays = [];
  75374. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  75375. this._scene = scene;
  75376. }
  75377. /**
  75378. * Returns the data related to the radial explosion event (sphere & rays).
  75379. * @returns {PhysicsRadialExplosionEventData}
  75380. */
  75381. PhysicsRadialExplosionEvent.prototype.getData = function () {
  75382. this._dataFetched = true;
  75383. return {
  75384. sphere: this._sphere,
  75385. rays: this._rays,
  75386. };
  75387. };
  75388. /**
  75389. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  75390. * @param impostor
  75391. * @param {Vector3} origin the origin of the explosion
  75392. * @param {number} radius the explosion radius
  75393. * @param {number} strength the explosion strength
  75394. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  75395. * @returns {Nullable<PhysicsForceAndContactPoint>}
  75396. */
  75397. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  75398. if (impostor.mass === 0) {
  75399. return null;
  75400. }
  75401. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  75402. return null;
  75403. }
  75404. if (impostor.object.getClassName() !== 'Mesh') {
  75405. return null;
  75406. }
  75407. var impostorObject = impostor.object;
  75408. var impostorObjectCenter = impostor.getObjectCenter();
  75409. var direction = impostorObjectCenter.subtract(origin);
  75410. var ray = new BABYLON.Ray(origin, direction, radius);
  75411. this._rays.push(ray);
  75412. var hit = ray.intersectsMesh(impostorObject);
  75413. var contactPoint = hit.pickedPoint;
  75414. if (!contactPoint) {
  75415. return null;
  75416. }
  75417. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  75418. if (distanceFromOrigin > radius) {
  75419. return null;
  75420. }
  75421. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  75422. ? strength
  75423. : strength * (1 - (distanceFromOrigin / radius));
  75424. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  75425. return { force: force, contactPoint: contactPoint };
  75426. };
  75427. /**
  75428. * Disposes the sphere.
  75429. * @param {bolean} force
  75430. */
  75431. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  75432. var _this = this;
  75433. if (force === void 0) { force = true; }
  75434. if (force) {
  75435. this._sphere.dispose();
  75436. }
  75437. else {
  75438. setTimeout(function () {
  75439. if (!_this._dataFetched) {
  75440. _this._sphere.dispose();
  75441. }
  75442. }, 0);
  75443. }
  75444. };
  75445. /*** Helpers ***/
  75446. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  75447. if (!this._sphere) {
  75448. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  75449. this._sphere.isVisible = false;
  75450. }
  75451. };
  75452. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  75453. var impostorObject = impostor.object;
  75454. this._prepareSphere();
  75455. this._sphere.position = origin;
  75456. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  75457. this._sphere._updateBoundingInfo();
  75458. this._sphere.computeWorldMatrix(true);
  75459. return this._sphere.intersectsMesh(impostorObject, true);
  75460. };
  75461. return PhysicsRadialExplosionEvent;
  75462. }());
  75463. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  75464. /***** Gravitational Field *****/
  75465. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  75466. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  75467. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  75468. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75469. this._physicsHelper = physicsHelper;
  75470. this._scene = scene;
  75471. this._origin = origin;
  75472. this._radius = radius;
  75473. this._strength = strength;
  75474. this._falloff = falloff;
  75475. this._tickCallback = this._tick.bind(this);
  75476. }
  75477. /**
  75478. * Returns the data related to the gravitational field event (sphere).
  75479. * @returns {PhysicsGravitationalFieldEventData}
  75480. */
  75481. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  75482. this._dataFetched = true;
  75483. return {
  75484. sphere: this._sphere,
  75485. };
  75486. };
  75487. /**
  75488. * Enables the gravitational field.
  75489. */
  75490. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  75491. this._tickCallback.call(this);
  75492. this._scene.registerBeforeRender(this._tickCallback);
  75493. };
  75494. /**
  75495. * Disables the gravitational field.
  75496. */
  75497. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  75498. this._scene.unregisterBeforeRender(this._tickCallback);
  75499. };
  75500. /**
  75501. * Disposes the sphere.
  75502. * @param {bolean} force
  75503. */
  75504. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  75505. var _this = this;
  75506. if (force === void 0) { force = true; }
  75507. if (force) {
  75508. this._sphere.dispose();
  75509. }
  75510. else {
  75511. setTimeout(function () {
  75512. if (!_this._dataFetched) {
  75513. _this._sphere.dispose();
  75514. }
  75515. }, 0);
  75516. }
  75517. };
  75518. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  75519. // Since the params won't change, we fetch the event only once
  75520. if (this._sphere) {
  75521. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  75522. }
  75523. else {
  75524. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  75525. if (radialExplosionEvent) {
  75526. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  75527. }
  75528. }
  75529. };
  75530. return PhysicsGravitationalFieldEvent;
  75531. }());
  75532. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  75533. /***** Updraft *****/
  75534. var PhysicsUpdraftEvent = /** @class */ (function () {
  75535. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  75536. this._scene = _scene;
  75537. this._origin = _origin;
  75538. this._radius = _radius;
  75539. this._strength = _strength;
  75540. this._height = _height;
  75541. this._updraftMode = _updraftMode;
  75542. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  75543. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  75544. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  75545. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75546. this._physicsEngine = this._scene.getPhysicsEngine();
  75547. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  75548. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  75549. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  75550. this._originDirection = this._origin.subtract(this._originTop).normalize();
  75551. }
  75552. this._tickCallback = this._tick.bind(this);
  75553. }
  75554. /**
  75555. * Returns the data related to the updraft event (cylinder).
  75556. * @returns {PhysicsUpdraftEventData}
  75557. */
  75558. PhysicsUpdraftEvent.prototype.getData = function () {
  75559. this._dataFetched = true;
  75560. return {
  75561. cylinder: this._cylinder,
  75562. };
  75563. };
  75564. /**
  75565. * Enables the updraft.
  75566. */
  75567. PhysicsUpdraftEvent.prototype.enable = function () {
  75568. this._tickCallback.call(this);
  75569. this._scene.registerBeforeRender(this._tickCallback);
  75570. };
  75571. /**
  75572. * Disables the cortex.
  75573. */
  75574. PhysicsUpdraftEvent.prototype.disable = function () {
  75575. this._scene.unregisterBeforeRender(this._tickCallback);
  75576. };
  75577. /**
  75578. * Disposes the sphere.
  75579. * @param {bolean} force
  75580. */
  75581. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  75582. var _this = this;
  75583. if (force === void 0) { force = true; }
  75584. if (force) {
  75585. this._cylinder.dispose();
  75586. }
  75587. else {
  75588. setTimeout(function () {
  75589. if (!_this._dataFetched) {
  75590. _this._cylinder.dispose();
  75591. }
  75592. }, 0);
  75593. }
  75594. };
  75595. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  75596. if (impostor.mass === 0) {
  75597. return null;
  75598. }
  75599. if (!this._intersectsWithCylinder(impostor)) {
  75600. return null;
  75601. }
  75602. var impostorObjectCenter = impostor.getObjectCenter();
  75603. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  75604. var direction = this._originDirection;
  75605. }
  75606. else {
  75607. var direction = impostorObjectCenter.subtract(this._originTop);
  75608. }
  75609. var multiplier = this._strength * -1;
  75610. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  75611. return { force: force, contactPoint: impostorObjectCenter };
  75612. };
  75613. PhysicsUpdraftEvent.prototype._tick = function () {
  75614. var _this = this;
  75615. this._physicsEngine.getImpostors().forEach(function (impostor) {
  75616. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  75617. if (!impostorForceAndContactPoint) {
  75618. return;
  75619. }
  75620. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75621. });
  75622. };
  75623. /*** Helpers ***/
  75624. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  75625. if (!this._cylinder) {
  75626. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  75627. height: this._height,
  75628. diameter: this._radius * 2,
  75629. }, this._scene);
  75630. this._cylinder.isVisible = false;
  75631. }
  75632. };
  75633. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  75634. var impostorObject = impostor.object;
  75635. this._prepareCylinder();
  75636. this._cylinder.position = this._cylinderPosition;
  75637. return this._cylinder.intersectsMesh(impostorObject, true);
  75638. };
  75639. return PhysicsUpdraftEvent;
  75640. }());
  75641. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  75642. /***** Vortex *****/
  75643. var PhysicsVortexEvent = /** @class */ (function () {
  75644. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  75645. this._scene = _scene;
  75646. this._origin = _origin;
  75647. this._radius = _radius;
  75648. this._strength = _strength;
  75649. this._height = _height;
  75650. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  75651. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  75652. this._updraftMultiplier = 0.02;
  75653. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  75654. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  75655. this._physicsEngine = this._scene.getPhysicsEngine();
  75656. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  75657. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  75658. this._tickCallback = this._tick.bind(this);
  75659. }
  75660. /**
  75661. * Returns the data related to the vortex event (cylinder).
  75662. * @returns {PhysicsVortexEventData}
  75663. */
  75664. PhysicsVortexEvent.prototype.getData = function () {
  75665. this._dataFetched = true;
  75666. return {
  75667. cylinder: this._cylinder,
  75668. };
  75669. };
  75670. /**
  75671. * Enables the vortex.
  75672. */
  75673. PhysicsVortexEvent.prototype.enable = function () {
  75674. this._tickCallback.call(this);
  75675. this._scene.registerBeforeRender(this._tickCallback);
  75676. };
  75677. /**
  75678. * Disables the cortex.
  75679. */
  75680. PhysicsVortexEvent.prototype.disable = function () {
  75681. this._scene.unregisterBeforeRender(this._tickCallback);
  75682. };
  75683. /**
  75684. * Disposes the sphere.
  75685. * @param {bolean} force
  75686. */
  75687. PhysicsVortexEvent.prototype.dispose = function (force) {
  75688. var _this = this;
  75689. if (force === void 0) { force = true; }
  75690. if (force) {
  75691. this._cylinder.dispose();
  75692. }
  75693. else {
  75694. setTimeout(function () {
  75695. if (!_this._dataFetched) {
  75696. _this._cylinder.dispose();
  75697. }
  75698. }, 0);
  75699. }
  75700. };
  75701. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  75702. if (impostor.mass === 0) {
  75703. return null;
  75704. }
  75705. if (!this._intersectsWithCylinder(impostor)) {
  75706. return null;
  75707. }
  75708. if (impostor.object.getClassName() !== 'Mesh') {
  75709. return null;
  75710. }
  75711. var impostorObject = impostor.object;
  75712. var impostorObjectCenter = impostor.getObjectCenter();
  75713. 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)
  75714. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  75715. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  75716. var hit = ray.intersectsMesh(impostorObject);
  75717. var contactPoint = hit.pickedPoint;
  75718. if (!contactPoint) {
  75719. return null;
  75720. }
  75721. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  75722. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  75723. var directionToOrigin = contactPoint.normalize();
  75724. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  75725. directionToOrigin = directionToOrigin.negate();
  75726. }
  75727. // TODO: find a more physically based solution
  75728. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  75729. var forceX = directionToOrigin.x * this._strength / 8;
  75730. var forceY = directionToOrigin.y * this._updraftMultiplier;
  75731. var forceZ = directionToOrigin.z * this._strength / 8;
  75732. }
  75733. else {
  75734. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  75735. var forceY = this._originTop.y * this._updraftMultiplier;
  75736. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  75737. }
  75738. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  75739. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  75740. return { force: force, contactPoint: impostorObjectCenter };
  75741. };
  75742. PhysicsVortexEvent.prototype._tick = function () {
  75743. var _this = this;
  75744. this._physicsEngine.getImpostors().forEach(function (impostor) {
  75745. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  75746. if (!impostorForceAndContactPoint) {
  75747. return;
  75748. }
  75749. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  75750. });
  75751. };
  75752. /*** Helpers ***/
  75753. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  75754. if (!this._cylinder) {
  75755. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  75756. height: this._height,
  75757. diameter: this._radius * 2,
  75758. }, this._scene);
  75759. this._cylinder.isVisible = false;
  75760. }
  75761. };
  75762. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  75763. var impostorObject = impostor.object;
  75764. this._prepareCylinder();
  75765. this._cylinder.position = this._cylinderPosition;
  75766. return this._cylinder.intersectsMesh(impostorObject, true);
  75767. };
  75768. return PhysicsVortexEvent;
  75769. }());
  75770. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  75771. /***** Enums *****/
  75772. /**
  75773. * The strenght of the force in correspondence to the distance of the affected object
  75774. */
  75775. var PhysicsRadialImpulseFalloff;
  75776. (function (PhysicsRadialImpulseFalloff) {
  75777. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  75778. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  75779. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  75780. /**
  75781. * The strenght of the force in correspondence to the distance of the affected object
  75782. */
  75783. var PhysicsUpdraftMode;
  75784. (function (PhysicsUpdraftMode) {
  75785. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  75786. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  75787. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  75788. })(BABYLON || (BABYLON = {}));
  75789. //# sourceMappingURL=babylon.physicsHelper.js.map
  75790. var BABYLON;
  75791. (function (BABYLON) {
  75792. var CannonJSPlugin = /** @class */ (function () {
  75793. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  75794. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  75795. if (iterations === void 0) { iterations = 10; }
  75796. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  75797. this.name = "CannonJSPlugin";
  75798. this._physicsMaterials = new Array();
  75799. this._fixedTimeStep = 1 / 60;
  75800. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  75801. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  75802. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  75803. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  75804. this._tmpPosition = BABYLON.Vector3.Zero();
  75805. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  75806. this._tmpUnityRotation = new BABYLON.Quaternion();
  75807. if (!this.isSupported()) {
  75808. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  75809. return;
  75810. }
  75811. this._extendNamespace();
  75812. this.world = new this.BJSCANNON.World();
  75813. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  75814. this.world.solver.iterations = iterations;
  75815. }
  75816. CannonJSPlugin.prototype.setGravity = function (gravity) {
  75817. this.world.gravity.copy(gravity);
  75818. };
  75819. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  75820. this._fixedTimeStep = timeStep;
  75821. };
  75822. CannonJSPlugin.prototype.getTimeStep = function () {
  75823. return this._fixedTimeStep;
  75824. };
  75825. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  75826. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  75827. };
  75828. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  75829. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  75830. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  75831. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  75832. };
  75833. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  75834. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  75835. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  75836. impostor.physicsBody.applyForce(impulse, worldPoint);
  75837. };
  75838. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  75839. //parent-child relationship. Does this impostor has a parent impostor?
  75840. if (impostor.parent) {
  75841. if (impostor.physicsBody) {
  75842. this.removePhysicsBody(impostor);
  75843. //TODO is that needed?
  75844. impostor.forceUpdate();
  75845. }
  75846. return;
  75847. }
  75848. //should a new body be created for this impostor?
  75849. if (impostor.isBodyInitRequired()) {
  75850. var shape = this._createShape(impostor);
  75851. //unregister events, if body is being changed
  75852. var oldBody = impostor.physicsBody;
  75853. if (oldBody) {
  75854. this.removePhysicsBody(impostor);
  75855. }
  75856. //create the body and material
  75857. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  75858. var bodyCreationObject = {
  75859. mass: impostor.getParam("mass"),
  75860. material: material
  75861. };
  75862. // A simple extend, in case native options were used.
  75863. var nativeOptions = impostor.getParam("nativeOptions");
  75864. for (var key in nativeOptions) {
  75865. if (nativeOptions.hasOwnProperty(key)) {
  75866. bodyCreationObject[key] = nativeOptions[key];
  75867. }
  75868. }
  75869. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  75870. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  75871. this.world.addEventListener("preStep", impostor.beforeStep);
  75872. this.world.addEventListener("postStep", impostor.afterStep);
  75873. impostor.physicsBody.addShape(shape);
  75874. this.world.add(impostor.physicsBody);
  75875. //try to keep the body moving in the right direction by taking old properties.
  75876. //Should be tested!
  75877. if (oldBody) {
  75878. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  75879. impostor.physicsBody[param].copy(oldBody[param]);
  75880. });
  75881. }
  75882. this._processChildMeshes(impostor);
  75883. }
  75884. //now update the body's transformation
  75885. this._updatePhysicsBodyTransformation(impostor);
  75886. };
  75887. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  75888. var _this = this;
  75889. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  75890. var currentRotation = mainImpostor.object.rotationQuaternion;
  75891. if (meshChildren.length) {
  75892. var processMesh = function (localPosition, mesh) {
  75893. if (!currentRotation || !mesh.rotationQuaternion) {
  75894. return;
  75895. }
  75896. var childImpostor = mesh.getPhysicsImpostor();
  75897. if (childImpostor) {
  75898. var parent = childImpostor.parent;
  75899. if (parent !== mainImpostor) {
  75900. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  75901. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  75902. if (childImpostor.physicsBody) {
  75903. _this.removePhysicsBody(childImpostor);
  75904. childImpostor.physicsBody = null;
  75905. }
  75906. childImpostor.parent = mainImpostor;
  75907. childImpostor.resetUpdateFlags();
  75908. 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));
  75909. //Add the mass of the children.
  75910. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  75911. }
  75912. }
  75913. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  75914. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  75915. };
  75916. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  75917. }
  75918. };
  75919. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  75920. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  75921. this.world.removeEventListener("preStep", impostor.beforeStep);
  75922. this.world.removeEventListener("postStep", impostor.afterStep);
  75923. this.world.remove(impostor.physicsBody);
  75924. };
  75925. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  75926. var mainBody = impostorJoint.mainImpostor.physicsBody;
  75927. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  75928. if (!mainBody || !connectedBody) {
  75929. return;
  75930. }
  75931. var constraint;
  75932. var jointData = impostorJoint.joint.jointData;
  75933. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  75934. var constraintData = {
  75935. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  75936. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  75937. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  75938. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  75939. maxForce: jointData.nativeParams.maxForce,
  75940. collideConnected: !!jointData.collision
  75941. };
  75942. switch (impostorJoint.joint.type) {
  75943. case BABYLON.PhysicsJoint.HingeJoint:
  75944. case BABYLON.PhysicsJoint.Hinge2Joint:
  75945. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  75946. break;
  75947. case BABYLON.PhysicsJoint.DistanceJoint:
  75948. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  75949. break;
  75950. case BABYLON.PhysicsJoint.SpringJoint:
  75951. var springData = jointData;
  75952. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  75953. restLength: springData.length,
  75954. stiffness: springData.stiffness,
  75955. damping: springData.damping,
  75956. localAnchorA: constraintData.pivotA,
  75957. localAnchorB: constraintData.pivotB
  75958. });
  75959. break;
  75960. case BABYLON.PhysicsJoint.LockJoint:
  75961. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  75962. break;
  75963. case BABYLON.PhysicsJoint.PointToPointJoint:
  75964. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  75965. default:
  75966. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  75967. break;
  75968. }
  75969. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  75970. constraint.collideConnected = !!jointData.collision;
  75971. impostorJoint.joint.physicsJoint = constraint;
  75972. //don't add spring as constraint, as it is not one.
  75973. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  75974. this.world.addConstraint(constraint);
  75975. }
  75976. else {
  75977. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  75978. constraint.applyForce();
  75979. });
  75980. }
  75981. };
  75982. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  75983. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  75984. };
  75985. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  75986. var index;
  75987. var mat;
  75988. for (index = 0; index < this._physicsMaterials.length; index++) {
  75989. mat = this._physicsMaterials[index];
  75990. if (mat.friction === friction && mat.restitution === restitution) {
  75991. return mat;
  75992. }
  75993. }
  75994. var currentMat = new this.BJSCANNON.Material(name);
  75995. currentMat.friction = friction;
  75996. currentMat.restitution = restitution;
  75997. this._physicsMaterials.push(currentMat);
  75998. return currentMat;
  75999. };
  76000. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  76001. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  76002. };
  76003. CannonJSPlugin.prototype._createShape = function (impostor) {
  76004. var object = impostor.object;
  76005. var returnValue;
  76006. var extendSize = impostor.getObjectExtendSize();
  76007. switch (impostor.type) {
  76008. case BABYLON.PhysicsImpostor.SphereImpostor:
  76009. var radiusX = extendSize.x;
  76010. var radiusY = extendSize.y;
  76011. var radiusZ = extendSize.z;
  76012. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  76013. break;
  76014. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  76015. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76016. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  76017. break;
  76018. case BABYLON.PhysicsImpostor.BoxImpostor:
  76019. var box = extendSize.scale(0.5);
  76020. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  76021. break;
  76022. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76023. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  76024. returnValue = new this.BJSCANNON.Plane();
  76025. break;
  76026. case BABYLON.PhysicsImpostor.MeshImpostor:
  76027. // should transform the vertex data to world coordinates!!
  76028. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  76029. var rawFaces = object.getIndices ? object.getIndices() : [];
  76030. if (!rawVerts)
  76031. return;
  76032. // get only scale! so the object could transform correctly.
  76033. var oldPosition = object.position.clone();
  76034. var oldRotation = object.rotation && object.rotation.clone();
  76035. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  76036. object.position.copyFromFloats(0, 0, 0);
  76037. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76038. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76039. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76040. var transform = object.computeWorldMatrix(true);
  76041. // convert rawVerts to object space
  76042. var temp = new Array();
  76043. var index;
  76044. for (index = 0; index < rawVerts.length; index += 3) {
  76045. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  76046. }
  76047. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  76048. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  76049. //now set back the transformation!
  76050. object.position.copyFrom(oldPosition);
  76051. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  76052. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  76053. break;
  76054. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  76055. var oldPosition2 = object.position.clone();
  76056. var oldRotation2 = object.rotation && object.rotation.clone();
  76057. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  76058. object.position.copyFromFloats(0, 0, 0);
  76059. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  76060. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  76061. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  76062. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  76063. returnValue = this._createHeightmap(object);
  76064. object.position.copyFrom(oldPosition2);
  76065. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  76066. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  76067. object.computeWorldMatrix(true);
  76068. break;
  76069. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76070. returnValue = new this.BJSCANNON.Particle();
  76071. break;
  76072. }
  76073. return returnValue;
  76074. };
  76075. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  76076. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  76077. var transform = object.computeWorldMatrix(true);
  76078. // convert rawVerts to object space
  76079. var temp = new Array();
  76080. var index;
  76081. for (index = 0; index < pos.length; index += 3) {
  76082. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  76083. }
  76084. pos = temp;
  76085. var matrix = new Array();
  76086. //For now pointDepth will not be used and will be automatically calculated.
  76087. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  76088. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  76089. var boundingInfo = object.getBoundingInfo();
  76090. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  76091. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  76092. var elementSize = dim * 2 / arraySize;
  76093. for (var i = 0; i < pos.length; i = i + 3) {
  76094. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  76095. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  76096. var y = -pos[i + 2] + minY;
  76097. if (!matrix[x]) {
  76098. matrix[x] = [];
  76099. }
  76100. if (!matrix[x][z]) {
  76101. matrix[x][z] = y;
  76102. }
  76103. matrix[x][z] = Math.max(y, matrix[x][z]);
  76104. }
  76105. for (var x = 0; x <= arraySize; ++x) {
  76106. if (!matrix[x]) {
  76107. var loc = 1;
  76108. while (!matrix[(x + loc) % arraySize]) {
  76109. loc++;
  76110. }
  76111. matrix[x] = matrix[(x + loc) % arraySize].slice();
  76112. //console.log("missing x", x);
  76113. }
  76114. for (var z = 0; z <= arraySize; ++z) {
  76115. if (!matrix[x][z]) {
  76116. var loc = 1;
  76117. var newValue;
  76118. while (newValue === undefined) {
  76119. newValue = matrix[x][(z + loc++) % arraySize];
  76120. }
  76121. matrix[x][z] = newValue;
  76122. }
  76123. }
  76124. }
  76125. var shape = new this.BJSCANNON.Heightfield(matrix, {
  76126. elementSize: elementSize
  76127. });
  76128. //For future reference, needed for body transformation
  76129. shape.minY = minY;
  76130. return shape;
  76131. };
  76132. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  76133. var object = impostor.object;
  76134. //make sure it is updated...
  76135. object.computeWorldMatrix && object.computeWorldMatrix(true);
  76136. // The delta between the mesh position and the mesh bounding box center
  76137. var bInfo = object.getBoundingInfo();
  76138. if (!bInfo)
  76139. return;
  76140. var center = impostor.getObjectCenter();
  76141. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  76142. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  76143. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  76144. this._tmpPosition.copyFrom(center);
  76145. var quaternion = object.rotationQuaternion;
  76146. if (!quaternion) {
  76147. return;
  76148. }
  76149. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  76150. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  76151. //-90 DEG in X, precalculated
  76152. quaternion = quaternion.multiply(this._minus90X);
  76153. //Invert! (Precalculated, 90 deg in X)
  76154. //No need to clone. this will never change.
  76155. impostor.setDeltaRotation(this._plus90X);
  76156. }
  76157. //If it is a heightfield, if should be centered.
  76158. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  76159. var mesh = object;
  76160. var boundingInfo = mesh.getBoundingInfo();
  76161. //calculate the correct body position:
  76162. var rotationQuaternion = mesh.rotationQuaternion;
  76163. mesh.rotationQuaternion = this._tmpUnityRotation;
  76164. mesh.computeWorldMatrix(true);
  76165. //get original center with no rotation
  76166. var c = center.clone();
  76167. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  76168. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  76169. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  76170. mesh.setPreTransformMatrix(p);
  76171. mesh.computeWorldMatrix(true);
  76172. //calculate the translation
  76173. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  76174. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  76175. //add it inverted to the delta
  76176. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  76177. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  76178. //rotation is back
  76179. mesh.rotationQuaternion = rotationQuaternion;
  76180. mesh.setPreTransformMatrix(oldPivot);
  76181. mesh.computeWorldMatrix(true);
  76182. }
  76183. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  76184. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  76185. //this._tmpPosition.copyFrom(object.position);
  76186. }
  76187. impostor.setDeltaPosition(this._tmpDeltaPosition);
  76188. //Now update the impostor object
  76189. impostor.physicsBody.position.copy(this._tmpPosition);
  76190. impostor.physicsBody.quaternion.copy(quaternion);
  76191. };
  76192. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  76193. impostor.object.position.copyFrom(impostor.physicsBody.position);
  76194. if (impostor.object.rotationQuaternion) {
  76195. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  76196. }
  76197. };
  76198. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  76199. impostor.physicsBody.position.copy(newPosition);
  76200. impostor.physicsBody.quaternion.copy(newRotation);
  76201. };
  76202. CannonJSPlugin.prototype.isSupported = function () {
  76203. return this.BJSCANNON !== undefined;
  76204. };
  76205. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  76206. impostor.physicsBody.velocity.copy(velocity);
  76207. };
  76208. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  76209. impostor.physicsBody.angularVelocity.copy(velocity);
  76210. };
  76211. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  76212. var v = impostor.physicsBody.velocity;
  76213. if (!v) {
  76214. return null;
  76215. }
  76216. return new BABYLON.Vector3(v.x, v.y, v.z);
  76217. };
  76218. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  76219. var v = impostor.physicsBody.angularVelocity;
  76220. if (!v) {
  76221. return null;
  76222. }
  76223. return new BABYLON.Vector3(v.x, v.y, v.z);
  76224. };
  76225. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  76226. impostor.physicsBody.mass = mass;
  76227. impostor.physicsBody.updateMassProperties();
  76228. };
  76229. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  76230. return impostor.physicsBody.mass;
  76231. };
  76232. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  76233. return impostor.physicsBody.material.friction;
  76234. };
  76235. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  76236. impostor.physicsBody.material.friction = friction;
  76237. };
  76238. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  76239. return impostor.physicsBody.material.restitution;
  76240. };
  76241. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  76242. impostor.physicsBody.material.restitution = restitution;
  76243. };
  76244. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  76245. impostor.physicsBody.sleep();
  76246. };
  76247. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  76248. impostor.physicsBody.wakeUp();
  76249. };
  76250. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  76251. joint.physicsJoint.distance = maxDistance;
  76252. };
  76253. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76254. // if (!motorIndex) {
  76255. // joint.physicsJoint.enableMotor();
  76256. // }
  76257. // }
  76258. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  76259. // if (!motorIndex) {
  76260. // joint.physicsJoint.disableMotor();
  76261. // }
  76262. // }
  76263. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  76264. if (!motorIndex) {
  76265. joint.physicsJoint.enableMotor();
  76266. joint.physicsJoint.setMotorSpeed(speed);
  76267. if (maxForce) {
  76268. this.setLimit(joint, maxForce);
  76269. }
  76270. }
  76271. };
  76272. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  76273. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  76274. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  76275. };
  76276. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  76277. var body = impostor.physicsBody;
  76278. mesh.position.x = body.position.x;
  76279. mesh.position.y = body.position.y;
  76280. mesh.position.z = body.position.z;
  76281. if (mesh.rotationQuaternion) {
  76282. mesh.rotationQuaternion.x = body.quaternion.x;
  76283. mesh.rotationQuaternion.y = body.quaternion.y;
  76284. mesh.rotationQuaternion.z = body.quaternion.z;
  76285. mesh.rotationQuaternion.w = body.quaternion.w;
  76286. }
  76287. };
  76288. CannonJSPlugin.prototype.getRadius = function (impostor) {
  76289. var shape = impostor.physicsBody.shapes[0];
  76290. return shape.boundingSphereRadius;
  76291. };
  76292. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  76293. var shape = impostor.physicsBody.shapes[0];
  76294. result.x = shape.halfExtents.x * 2;
  76295. result.y = shape.halfExtents.y * 2;
  76296. result.z = shape.halfExtents.z * 2;
  76297. };
  76298. CannonJSPlugin.prototype.dispose = function () {
  76299. };
  76300. CannonJSPlugin.prototype._extendNamespace = function () {
  76301. //this will force cannon to execute at least one step when using interpolation
  76302. var step_tmp1 = new this.BJSCANNON.Vec3();
  76303. var Engine = this.BJSCANNON;
  76304. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  76305. maxSubSteps = maxSubSteps || 10;
  76306. timeSinceLastCalled = timeSinceLastCalled || 0;
  76307. if (timeSinceLastCalled === 0) {
  76308. this.internalStep(dt);
  76309. this.time += dt;
  76310. }
  76311. else {
  76312. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  76313. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  76314. var t0 = performance.now();
  76315. for (var i = 0; i !== internalSteps; i++) {
  76316. this.internalStep(dt);
  76317. if (performance.now() - t0 > dt * 1000) {
  76318. break;
  76319. }
  76320. }
  76321. this.time += timeSinceLastCalled;
  76322. var h = this.time % dt;
  76323. var h_div_dt = h / dt;
  76324. var interpvelo = step_tmp1;
  76325. var bodies = this.bodies;
  76326. for (var j = 0; j !== bodies.length; j++) {
  76327. var b = bodies[j];
  76328. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  76329. b.position.vsub(b.previousPosition, interpvelo);
  76330. interpvelo.scale(h_div_dt, interpvelo);
  76331. b.position.vadd(interpvelo, b.interpolatedPosition);
  76332. }
  76333. else {
  76334. b.interpolatedPosition.copy(b.position);
  76335. b.interpolatedQuaternion.copy(b.quaternion);
  76336. }
  76337. }
  76338. }
  76339. };
  76340. };
  76341. return CannonJSPlugin;
  76342. }());
  76343. BABYLON.CannonJSPlugin = CannonJSPlugin;
  76344. })(BABYLON || (BABYLON = {}));
  76345. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  76346. var BABYLON;
  76347. (function (BABYLON) {
  76348. var OimoJSPlugin = /** @class */ (function () {
  76349. function OimoJSPlugin(iterations) {
  76350. this.name = "OimoJSPlugin";
  76351. this._tmpImpostorsArray = [];
  76352. this._tmpPositionVector = BABYLON.Vector3.Zero();
  76353. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  76354. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  76355. this.world.worldscale(1);
  76356. this.world.clear();
  76357. //making sure no stats are calculated
  76358. this.world.isNoStat = true;
  76359. }
  76360. OimoJSPlugin.prototype.setGravity = function (gravity) {
  76361. this.world.gravity.copy(gravity);
  76362. };
  76363. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  76364. this.world.timeStep = timeStep;
  76365. };
  76366. OimoJSPlugin.prototype.getTimeStep = function () {
  76367. return this.world.timeStep;
  76368. };
  76369. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  76370. var _this = this;
  76371. impostors.forEach(function (impostor) {
  76372. impostor.beforeStep();
  76373. });
  76374. this.world.step();
  76375. impostors.forEach(function (impostor) {
  76376. impostor.afterStep();
  76377. //update the ordered impostors array
  76378. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  76379. });
  76380. //check for collisions
  76381. var contact = this.world.contacts;
  76382. while (contact !== null) {
  76383. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  76384. contact = contact.next;
  76385. continue;
  76386. }
  76387. //is this body colliding with any other? get the impostor
  76388. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  76389. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  76390. if (!mainImpostor || !collidingImpostor) {
  76391. contact = contact.next;
  76392. continue;
  76393. }
  76394. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  76395. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  76396. contact = contact.next;
  76397. }
  76398. };
  76399. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  76400. var mass = impostor.physicsBody.massInfo.mass;
  76401. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  76402. };
  76403. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  76404. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  76405. this.applyImpulse(impostor, force, contactPoint);
  76406. };
  76407. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  76408. var _this = this;
  76409. //parent-child relationship. Does this impostor has a parent impostor?
  76410. if (impostor.parent) {
  76411. if (impostor.physicsBody) {
  76412. this.removePhysicsBody(impostor);
  76413. //TODO is that needed?
  76414. impostor.forceUpdate();
  76415. }
  76416. return;
  76417. }
  76418. if (impostor.isBodyInitRequired()) {
  76419. var bodyConfig = {
  76420. name: impostor.uniqueId,
  76421. //Oimo must have mass, also for static objects.
  76422. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  76423. size: [],
  76424. type: [],
  76425. pos: [],
  76426. rot: [],
  76427. move: impostor.getParam("mass") !== 0,
  76428. //Supporting older versions of Oimo
  76429. world: this.world
  76430. };
  76431. var impostors = [impostor];
  76432. var addToArray = function (parent) {
  76433. if (!parent.getChildMeshes)
  76434. return;
  76435. parent.getChildMeshes().forEach(function (m) {
  76436. if (m.physicsImpostor) {
  76437. impostors.push(m.physicsImpostor);
  76438. //m.physicsImpostor._init();
  76439. }
  76440. });
  76441. };
  76442. addToArray(impostor.object);
  76443. var checkWithEpsilon_1 = function (value) {
  76444. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  76445. };
  76446. impostors.forEach(function (i) {
  76447. if (!impostor.object.rotationQuaternion) {
  76448. return;
  76449. }
  76450. //get the correct bounding box
  76451. var oldQuaternion = i.object.rotationQuaternion;
  76452. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  76453. x: impostor.object.rotationQuaternion.x,
  76454. y: impostor.object.rotationQuaternion.y,
  76455. z: impostor.object.rotationQuaternion.z,
  76456. s: impostor.object.rotationQuaternion.w
  76457. });
  76458. var extendSize = i.getObjectExtendSize();
  76459. if (i === impostor) {
  76460. var center = impostor.getObjectCenter();
  76461. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  76462. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  76463. //Can also use Array.prototype.push.apply
  76464. bodyConfig.pos.push(center.x);
  76465. bodyConfig.pos.push(center.y);
  76466. bodyConfig.pos.push(center.z);
  76467. //tmp solution
  76468. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76469. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76470. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  76471. }
  76472. else {
  76473. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  76474. bodyConfig.pos.push(localPosition.x);
  76475. bodyConfig.pos.push(localPosition.y);
  76476. bodyConfig.pos.push(localPosition.z);
  76477. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  76478. bodyConfig.rot.push(0);
  76479. bodyConfig.rot.push(0);
  76480. bodyConfig.rot.push(0);
  76481. }
  76482. // register mesh
  76483. switch (i.type) {
  76484. case BABYLON.PhysicsImpostor.ParticleImpostor:
  76485. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  76486. case BABYLON.PhysicsImpostor.SphereImpostor:
  76487. var radiusX = extendSize.x;
  76488. var radiusY = extendSize.y;
  76489. var radiusZ = extendSize.z;
  76490. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  76491. bodyConfig.type.push('sphere');
  76492. //due to the way oimo works with compounds, add 3 times
  76493. bodyConfig.size.push(size);
  76494. bodyConfig.size.push(size);
  76495. bodyConfig.size.push(size);
  76496. break;
  76497. case BABYLON.PhysicsImpostor.CylinderImpostor:
  76498. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  76499. var sizeY = checkWithEpsilon_1(extendSize.y);
  76500. bodyConfig.type.push('cylinder');
  76501. bodyConfig.size.push(sizeX);
  76502. bodyConfig.size.push(sizeY);
  76503. //due to the way oimo works with compounds, add one more value.
  76504. bodyConfig.size.push(sizeY);
  76505. break;
  76506. case BABYLON.PhysicsImpostor.PlaneImpostor:
  76507. case BABYLON.PhysicsImpostor.BoxImpostor:
  76508. default:
  76509. var sizeX = checkWithEpsilon_1(extendSize.x);
  76510. var sizeY = checkWithEpsilon_1(extendSize.y);
  76511. var sizeZ = checkWithEpsilon_1(extendSize.z);
  76512. bodyConfig.type.push('box');
  76513. bodyConfig.size.push(sizeX);
  76514. bodyConfig.size.push(sizeY);
  76515. bodyConfig.size.push(sizeZ);
  76516. break;
  76517. }
  76518. //actually not needed, but hey...
  76519. i.object.rotationQuaternion = oldQuaternion;
  76520. });
  76521. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  76522. }
  76523. else {
  76524. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  76525. }
  76526. impostor.setDeltaPosition(this._tmpPositionVector);
  76527. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  76528. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  76529. };
  76530. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  76531. //impostor.physicsBody.dispose();
  76532. //Same as : (older oimo versions)
  76533. this.world.removeRigidBody(impostor.physicsBody);
  76534. };
  76535. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  76536. var mainBody = impostorJoint.mainImpostor.physicsBody;
  76537. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  76538. if (!mainBody || !connectedBody) {
  76539. return;
  76540. }
  76541. var jointData = impostorJoint.joint.jointData;
  76542. var options = jointData.nativeParams || {};
  76543. var type;
  76544. var nativeJointData = {
  76545. body1: mainBody,
  76546. body2: connectedBody,
  76547. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  76548. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  76549. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  76550. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  76551. min: options.min,
  76552. max: options.max,
  76553. collision: options.collision || jointData.collision,
  76554. spring: options.spring,
  76555. //supporting older version of Oimo
  76556. world: this.world
  76557. };
  76558. switch (impostorJoint.joint.type) {
  76559. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  76560. type = "jointBall";
  76561. break;
  76562. case BABYLON.PhysicsJoint.SpringJoint:
  76563. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  76564. var springData = jointData;
  76565. nativeJointData.min = springData.length || nativeJointData.min;
  76566. //Max should also be set, just make sure it is at least min
  76567. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  76568. case BABYLON.PhysicsJoint.DistanceJoint:
  76569. type = "jointDistance";
  76570. nativeJointData.max = jointData.maxDistance;
  76571. break;
  76572. case BABYLON.PhysicsJoint.PrismaticJoint:
  76573. type = "jointPrisme";
  76574. break;
  76575. case BABYLON.PhysicsJoint.SliderJoint:
  76576. type = "jointSlide";
  76577. break;
  76578. case BABYLON.PhysicsJoint.WheelJoint:
  76579. type = "jointWheel";
  76580. break;
  76581. case BABYLON.PhysicsJoint.HingeJoint:
  76582. default:
  76583. type = "jointHinge";
  76584. break;
  76585. }
  76586. nativeJointData.type = type;
  76587. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  76588. };
  76589. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  76590. //Bug in Oimo prevents us from disposing a joint in the playground
  76591. //joint.joint.physicsJoint.dispose();
  76592. //So we will bruteforce it!
  76593. try {
  76594. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  76595. }
  76596. catch (e) {
  76597. BABYLON.Tools.Warn(e);
  76598. }
  76599. };
  76600. OimoJSPlugin.prototype.isSupported = function () {
  76601. return this.BJSOIMO !== undefined;
  76602. };
  76603. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  76604. if (!impostor.physicsBody.sleeping) {
  76605. //TODO check that
  76606. if (impostor.physicsBody.shapes.next) {
  76607. var parentShape = this._getLastShape(impostor.physicsBody);
  76608. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  76609. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  76610. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  76611. }
  76612. else {
  76613. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  76614. }
  76615. if (impostor.object.rotationQuaternion) {
  76616. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  76617. impostor.object.rotationQuaternion.normalize();
  76618. }
  76619. }
  76620. };
  76621. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  76622. var body = impostor.physicsBody;
  76623. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  76624. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  76625. body.syncShapes();
  76626. body.awake();
  76627. };
  76628. OimoJSPlugin.prototype._getLastShape = function (body) {
  76629. var lastShape = body.shapes;
  76630. while (lastShape.next) {
  76631. lastShape = lastShape.next;
  76632. }
  76633. return lastShape;
  76634. };
  76635. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  76636. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  76637. };
  76638. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  76639. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  76640. };
  76641. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  76642. var v = impostor.physicsBody.linearVelocity;
  76643. if (!v) {
  76644. return null;
  76645. }
  76646. return new BABYLON.Vector3(v.x, v.y, v.z);
  76647. };
  76648. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  76649. var v = impostor.physicsBody.angularVelocity;
  76650. if (!v) {
  76651. return null;
  76652. }
  76653. return new BABYLON.Vector3(v.x, v.y, v.z);
  76654. };
  76655. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  76656. var staticBody = mass === 0;
  76657. //this will actually set the body's density and not its mass.
  76658. //But this is how oimo treats the mass variable.
  76659. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  76660. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  76661. };
  76662. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  76663. return impostor.physicsBody.shapes.density;
  76664. };
  76665. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  76666. return impostor.physicsBody.shapes.friction;
  76667. };
  76668. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  76669. impostor.physicsBody.shapes.friction = friction;
  76670. };
  76671. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  76672. return impostor.physicsBody.shapes.restitution;
  76673. };
  76674. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  76675. impostor.physicsBody.shapes.restitution = restitution;
  76676. };
  76677. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  76678. impostor.physicsBody.sleep();
  76679. };
  76680. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  76681. impostor.physicsBody.awake();
  76682. };
  76683. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  76684. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  76685. if (minDistance !== void 0) {
  76686. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  76687. }
  76688. };
  76689. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  76690. //TODO separate rotational and transational motors.
  76691. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  76692. if (motor) {
  76693. motor.setMotor(speed, maxForce);
  76694. }
  76695. };
  76696. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  76697. //TODO separate rotational and transational motors.
  76698. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  76699. if (motor) {
  76700. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  76701. }
  76702. };
  76703. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  76704. var body = impostor.physicsBody;
  76705. mesh.position.x = body.position.x;
  76706. mesh.position.y = body.position.y;
  76707. mesh.position.z = body.position.z;
  76708. if (mesh.rotationQuaternion) {
  76709. mesh.rotationQuaternion.x = body.orientation.x;
  76710. mesh.rotationQuaternion.y = body.orientation.y;
  76711. mesh.rotationQuaternion.z = body.orientation.z;
  76712. mesh.rotationQuaternion.w = body.orientation.s;
  76713. }
  76714. };
  76715. OimoJSPlugin.prototype.getRadius = function (impostor) {
  76716. return impostor.physicsBody.shapes.radius;
  76717. };
  76718. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  76719. var shape = impostor.physicsBody.shapes;
  76720. result.x = shape.halfWidth * 2;
  76721. result.y = shape.halfHeight * 2;
  76722. result.z = shape.halfDepth * 2;
  76723. };
  76724. OimoJSPlugin.prototype.dispose = function () {
  76725. this.world.clear();
  76726. };
  76727. return OimoJSPlugin;
  76728. }());
  76729. BABYLON.OimoJSPlugin = OimoJSPlugin;
  76730. })(BABYLON || (BABYLON = {}));
  76731. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  76732. var BABYLON;
  76733. (function (BABYLON) {
  76734. /*
  76735. * Based on jsTGALoader - Javascript loader for TGA file
  76736. * By Vincent Thibault
  76737. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  76738. */
  76739. var TGATools = /** @class */ (function () {
  76740. function TGATools() {
  76741. }
  76742. TGATools.GetTGAHeader = function (data) {
  76743. var offset = 0;
  76744. var header = {
  76745. id_length: data[offset++],
  76746. colormap_type: data[offset++],
  76747. image_type: data[offset++],
  76748. colormap_index: data[offset++] | data[offset++] << 8,
  76749. colormap_length: data[offset++] | data[offset++] << 8,
  76750. colormap_size: data[offset++],
  76751. origin: [
  76752. data[offset++] | data[offset++] << 8,
  76753. data[offset++] | data[offset++] << 8
  76754. ],
  76755. width: data[offset++] | data[offset++] << 8,
  76756. height: data[offset++] | data[offset++] << 8,
  76757. pixel_size: data[offset++],
  76758. flags: data[offset++]
  76759. };
  76760. return header;
  76761. };
  76762. TGATools.UploadContent = function (gl, data) {
  76763. // Not enough data to contain header ?
  76764. if (data.length < 19) {
  76765. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  76766. return;
  76767. }
  76768. // Read Header
  76769. var offset = 18;
  76770. var header = TGATools.GetTGAHeader(data);
  76771. // Assume it's a valid Targa file.
  76772. if (header.id_length + offset > data.length) {
  76773. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  76774. return;
  76775. }
  76776. // Skip not needed data
  76777. offset += header.id_length;
  76778. var use_rle = false;
  76779. var use_pal = false;
  76780. var use_grey = false;
  76781. // Get some informations.
  76782. switch (header.image_type) {
  76783. case TGATools._TYPE_RLE_INDEXED:
  76784. use_rle = true;
  76785. case TGATools._TYPE_INDEXED:
  76786. use_pal = true;
  76787. break;
  76788. case TGATools._TYPE_RLE_RGB:
  76789. use_rle = true;
  76790. case TGATools._TYPE_RGB:
  76791. // use_rgb = true;
  76792. break;
  76793. case TGATools._TYPE_RLE_GREY:
  76794. use_rle = true;
  76795. case TGATools._TYPE_GREY:
  76796. use_grey = true;
  76797. break;
  76798. }
  76799. var pixel_data;
  76800. // var numAlphaBits = header.flags & 0xf;
  76801. var pixel_size = header.pixel_size >> 3;
  76802. var pixel_total = header.width * header.height * pixel_size;
  76803. // Read palettes
  76804. var palettes;
  76805. if (use_pal) {
  76806. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  76807. }
  76808. // Read LRE
  76809. if (use_rle) {
  76810. pixel_data = new Uint8Array(pixel_total);
  76811. var c, count, i;
  76812. var localOffset = 0;
  76813. var pixels = new Uint8Array(pixel_size);
  76814. while (offset < pixel_total && localOffset < pixel_total) {
  76815. c = data[offset++];
  76816. count = (c & 0x7f) + 1;
  76817. // RLE pixels
  76818. if (c & 0x80) {
  76819. // Bind pixel tmp array
  76820. for (i = 0; i < pixel_size; ++i) {
  76821. pixels[i] = data[offset++];
  76822. }
  76823. // Copy pixel array
  76824. for (i = 0; i < count; ++i) {
  76825. pixel_data.set(pixels, localOffset + i * pixel_size);
  76826. }
  76827. localOffset += pixel_size * count;
  76828. }
  76829. else {
  76830. count *= pixel_size;
  76831. for (i = 0; i < count; ++i) {
  76832. pixel_data[localOffset + i] = data[offset++];
  76833. }
  76834. localOffset += count;
  76835. }
  76836. }
  76837. }
  76838. else {
  76839. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  76840. }
  76841. // Load to texture
  76842. var x_start, y_start, x_step, y_step, y_end, x_end;
  76843. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  76844. default:
  76845. case TGATools._ORIGIN_UL:
  76846. x_start = 0;
  76847. x_step = 1;
  76848. x_end = header.width;
  76849. y_start = 0;
  76850. y_step = 1;
  76851. y_end = header.height;
  76852. break;
  76853. case TGATools._ORIGIN_BL:
  76854. x_start = 0;
  76855. x_step = 1;
  76856. x_end = header.width;
  76857. y_start = header.height - 1;
  76858. y_step = -1;
  76859. y_end = -1;
  76860. break;
  76861. case TGATools._ORIGIN_UR:
  76862. x_start = header.width - 1;
  76863. x_step = -1;
  76864. x_end = -1;
  76865. y_start = 0;
  76866. y_step = 1;
  76867. y_end = header.height;
  76868. break;
  76869. case TGATools._ORIGIN_BR:
  76870. x_start = header.width - 1;
  76871. x_step = -1;
  76872. x_end = -1;
  76873. y_start = header.height - 1;
  76874. y_step = -1;
  76875. y_end = -1;
  76876. break;
  76877. }
  76878. // Load the specify method
  76879. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  76880. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  76881. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  76882. };
  76883. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76884. var image = pixel_data, colormap = palettes;
  76885. var width = header.width, height = header.height;
  76886. var color, i = 0, x, y;
  76887. var imageData = new Uint8Array(width * height * 4);
  76888. for (y = y_start; y !== y_end; y += y_step) {
  76889. for (x = x_start; x !== x_end; x += x_step, i++) {
  76890. color = image[i];
  76891. imageData[(x + width * y) * 4 + 3] = 255;
  76892. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  76893. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  76894. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  76895. }
  76896. }
  76897. return imageData;
  76898. };
  76899. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76900. var image = pixel_data;
  76901. var width = header.width, height = header.height;
  76902. var color, i = 0, x, y;
  76903. var imageData = new Uint8Array(width * height * 4);
  76904. for (y = y_start; y !== y_end; y += y_step) {
  76905. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  76906. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  76907. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  76908. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  76909. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  76910. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  76911. }
  76912. }
  76913. return imageData;
  76914. };
  76915. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76916. var image = pixel_data;
  76917. var width = header.width, height = header.height;
  76918. var i = 0, x, y;
  76919. var imageData = new Uint8Array(width * height * 4);
  76920. for (y = y_start; y !== y_end; y += y_step) {
  76921. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  76922. imageData[(x + width * y) * 4 + 3] = 255;
  76923. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  76924. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  76925. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  76926. }
  76927. }
  76928. return imageData;
  76929. };
  76930. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76931. var image = pixel_data;
  76932. var width = header.width, height = header.height;
  76933. var i = 0, x, y;
  76934. var imageData = new Uint8Array(width * height * 4);
  76935. for (y = y_start; y !== y_end; y += y_step) {
  76936. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  76937. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  76938. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  76939. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  76940. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  76941. }
  76942. }
  76943. return imageData;
  76944. };
  76945. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76946. var image = pixel_data;
  76947. var width = header.width, height = header.height;
  76948. var color, i = 0, x, y;
  76949. var imageData = new Uint8Array(width * height * 4);
  76950. for (y = y_start; y !== y_end; y += y_step) {
  76951. for (x = x_start; x !== x_end; x += x_step, i++) {
  76952. color = image[i];
  76953. imageData[(x + width * y) * 4 + 0] = color;
  76954. imageData[(x + width * y) * 4 + 1] = color;
  76955. imageData[(x + width * y) * 4 + 2] = color;
  76956. imageData[(x + width * y) * 4 + 3] = 255;
  76957. }
  76958. }
  76959. return imageData;
  76960. };
  76961. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  76962. var image = pixel_data;
  76963. var width = header.width, height = header.height;
  76964. var i = 0, x, y;
  76965. var imageData = new Uint8Array(width * height * 4);
  76966. for (y = y_start; y !== y_end; y += y_step) {
  76967. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  76968. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  76969. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  76970. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  76971. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  76972. }
  76973. }
  76974. return imageData;
  76975. };
  76976. //private static _TYPE_NO_DATA = 0;
  76977. TGATools._TYPE_INDEXED = 1;
  76978. TGATools._TYPE_RGB = 2;
  76979. TGATools._TYPE_GREY = 3;
  76980. TGATools._TYPE_RLE_INDEXED = 9;
  76981. TGATools._TYPE_RLE_RGB = 10;
  76982. TGATools._TYPE_RLE_GREY = 11;
  76983. TGATools._ORIGIN_MASK = 0x30;
  76984. TGATools._ORIGIN_SHIFT = 0x04;
  76985. TGATools._ORIGIN_BL = 0x00;
  76986. TGATools._ORIGIN_BR = 0x01;
  76987. TGATools._ORIGIN_UL = 0x02;
  76988. TGATools._ORIGIN_UR = 0x03;
  76989. return TGATools;
  76990. }());
  76991. BABYLON.TGATools = TGATools;
  76992. })(BABYLON || (BABYLON = {}));
  76993. //# sourceMappingURL=babylon.tga.js.map
  76994. var BABYLON;
  76995. (function (BABYLON) {
  76996. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  76997. // All values and structures referenced from:
  76998. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  76999. var DDS_MAGIC = 0x20534444;
  77000. var
  77001. //DDSD_CAPS = 0x1,
  77002. //DDSD_HEIGHT = 0x2,
  77003. //DDSD_WIDTH = 0x4,
  77004. //DDSD_PITCH = 0x8,
  77005. //DDSD_PIXELFORMAT = 0x1000,
  77006. DDSD_MIPMAPCOUNT = 0x20000;
  77007. //DDSD_LINEARSIZE = 0x80000,
  77008. //DDSD_DEPTH = 0x800000;
  77009. // var DDSCAPS_COMPLEX = 0x8,
  77010. // DDSCAPS_MIPMAP = 0x400000,
  77011. // DDSCAPS_TEXTURE = 0x1000;
  77012. var DDSCAPS2_CUBEMAP = 0x200;
  77013. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  77014. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  77015. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  77016. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  77017. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  77018. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  77019. // DDSCAPS2_VOLUME = 0x200000;
  77020. var
  77021. //DDPF_ALPHAPIXELS = 0x1,
  77022. //DDPF_ALPHA = 0x2,
  77023. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  77024. //DDPF_YUV = 0x200,
  77025. DDPF_LUMINANCE = 0x20000;
  77026. function FourCCToInt32(value) {
  77027. return value.charCodeAt(0) +
  77028. (value.charCodeAt(1) << 8) +
  77029. (value.charCodeAt(2) << 16) +
  77030. (value.charCodeAt(3) << 24);
  77031. }
  77032. function Int32ToFourCC(value) {
  77033. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  77034. }
  77035. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  77036. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  77037. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  77038. var FOURCC_DX10 = FourCCToInt32("DX10");
  77039. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  77040. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  77041. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  77042. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  77043. var headerLengthInt = 31; // The header length in 32 bit ints
  77044. // Offsets into the header array
  77045. var off_magic = 0;
  77046. var off_size = 1;
  77047. var off_flags = 2;
  77048. var off_height = 3;
  77049. var off_width = 4;
  77050. var off_mipmapCount = 7;
  77051. var off_pfFlags = 20;
  77052. var off_pfFourCC = 21;
  77053. var off_RGBbpp = 22;
  77054. var off_RMask = 23;
  77055. var off_GMask = 24;
  77056. var off_BMask = 25;
  77057. var off_AMask = 26;
  77058. // var off_caps1 = 27;
  77059. var off_caps2 = 28;
  77060. // var off_caps3 = 29;
  77061. // var off_caps4 = 30;
  77062. var off_dxgiFormat = 32;
  77063. ;
  77064. var DDSTools = /** @class */ (function () {
  77065. function DDSTools() {
  77066. }
  77067. DDSTools.GetDDSInfo = function (arrayBuffer) {
  77068. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77069. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  77070. var mipmapCount = 1;
  77071. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  77072. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77073. }
  77074. var fourCC = header[off_pfFourCC];
  77075. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  77076. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77077. switch (fourCC) {
  77078. case FOURCC_D3DFMT_R16G16B16A16F:
  77079. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77080. break;
  77081. case FOURCC_D3DFMT_R32G32B32A32F:
  77082. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77083. break;
  77084. case FOURCC_DX10:
  77085. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  77086. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  77087. break;
  77088. }
  77089. }
  77090. return {
  77091. width: header[off_width],
  77092. height: header[off_height],
  77093. mipmapCount: mipmapCount,
  77094. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  77095. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  77096. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  77097. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  77098. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  77099. dxgiFormat: dxgiFormat,
  77100. textureType: textureType
  77101. };
  77102. };
  77103. DDSTools._ToHalfFloat = function (value) {
  77104. if (!DDSTools._FloatView) {
  77105. DDSTools._FloatView = new Float32Array(1);
  77106. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  77107. }
  77108. DDSTools._FloatView[0] = value;
  77109. var x = DDSTools._Int32View[0];
  77110. var bits = (x >> 16) & 0x8000; /* Get the sign */
  77111. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  77112. var e = (x >> 23) & 0xff; /* Using int is faster here */
  77113. /* If zero, or denormal, or exponent underflows too much for a denormal
  77114. * half, return signed zero. */
  77115. if (e < 103) {
  77116. return bits;
  77117. }
  77118. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  77119. if (e > 142) {
  77120. bits |= 0x7c00;
  77121. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  77122. * not Inf, so make sure we set one mantissa bit too. */
  77123. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  77124. return bits;
  77125. }
  77126. /* If exponent underflows but not too much, return a denormal */
  77127. if (e < 113) {
  77128. m |= 0x0800;
  77129. /* Extra rounding may overflow and set mantissa to 0 and exponent
  77130. * to 1, which is OK. */
  77131. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  77132. return bits;
  77133. }
  77134. bits |= ((e - 112) << 10) | (m >> 1);
  77135. bits += m & 1;
  77136. return bits;
  77137. };
  77138. DDSTools._FromHalfFloat = function (value) {
  77139. var s = (value & 0x8000) >> 15;
  77140. var e = (value & 0x7C00) >> 10;
  77141. var f = value & 0x03FF;
  77142. if (e === 0) {
  77143. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  77144. }
  77145. else if (e == 0x1F) {
  77146. return f ? NaN : ((s ? -1 : 1) * Infinity);
  77147. }
  77148. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  77149. };
  77150. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77151. var destArray = new Float32Array(dataLength);
  77152. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77153. var index = 0;
  77154. for (var y = 0; y < height; y++) {
  77155. for (var x = 0; x < width; x++) {
  77156. var srcPos = (x + y * width) * 4;
  77157. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  77158. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  77159. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  77160. if (DDSTools.StoreLODInAlphaChannel) {
  77161. destArray[index + 3] = lod;
  77162. }
  77163. else {
  77164. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  77165. }
  77166. index += 4;
  77167. }
  77168. }
  77169. return destArray;
  77170. };
  77171. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77172. if (DDSTools.StoreLODInAlphaChannel) {
  77173. var destArray = new Uint16Array(dataLength);
  77174. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77175. var index = 0;
  77176. for (var y = 0; y < height; y++) {
  77177. for (var x = 0; x < width; x++) {
  77178. var srcPos = (x + y * width) * 4;
  77179. destArray[index] = srcData[srcPos];
  77180. destArray[index + 1] = srcData[srcPos + 1];
  77181. destArray[index + 2] = srcData[srcPos + 2];
  77182. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  77183. index += 4;
  77184. }
  77185. }
  77186. return destArray;
  77187. }
  77188. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  77189. };
  77190. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77191. if (DDSTools.StoreLODInAlphaChannel) {
  77192. var destArray = new Float32Array(dataLength);
  77193. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77194. var index = 0;
  77195. for (var y = 0; y < height; y++) {
  77196. for (var x = 0; x < width; x++) {
  77197. var srcPos = (x + y * width) * 4;
  77198. destArray[index] = srcData[srcPos];
  77199. destArray[index + 1] = srcData[srcPos + 1];
  77200. destArray[index + 2] = srcData[srcPos + 2];
  77201. destArray[index + 3] = lod;
  77202. index += 4;
  77203. }
  77204. }
  77205. return destArray;
  77206. }
  77207. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  77208. };
  77209. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77210. var destArray = new Uint8Array(dataLength);
  77211. var srcData = new Float32Array(arrayBuffer, dataOffset);
  77212. var index = 0;
  77213. for (var y = 0; y < height; y++) {
  77214. for (var x = 0; x < width; x++) {
  77215. var srcPos = (x + y * width) * 4;
  77216. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  77217. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  77218. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  77219. if (DDSTools.StoreLODInAlphaChannel) {
  77220. destArray[index + 3] = lod;
  77221. }
  77222. else {
  77223. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  77224. }
  77225. index += 4;
  77226. }
  77227. }
  77228. return destArray;
  77229. };
  77230. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  77231. var destArray = new Uint8Array(dataLength);
  77232. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  77233. var index = 0;
  77234. for (var y = 0; y < height; y++) {
  77235. for (var x = 0; x < width; x++) {
  77236. var srcPos = (x + y * width) * 4;
  77237. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  77238. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  77239. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  77240. if (DDSTools.StoreLODInAlphaChannel) {
  77241. destArray[index + 3] = lod;
  77242. }
  77243. else {
  77244. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  77245. }
  77246. index += 4;
  77247. }
  77248. }
  77249. return destArray;
  77250. };
  77251. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  77252. var byteArray = new Uint8Array(dataLength);
  77253. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77254. var index = 0;
  77255. for (var y = 0; y < height; y++) {
  77256. for (var x = 0; x < width; x++) {
  77257. var srcPos = (x + y * width) * 4;
  77258. byteArray[index] = srcData[srcPos + rOffset];
  77259. byteArray[index + 1] = srcData[srcPos + gOffset];
  77260. byteArray[index + 2] = srcData[srcPos + bOffset];
  77261. byteArray[index + 3] = srcData[srcPos + aOffset];
  77262. index += 4;
  77263. }
  77264. }
  77265. return byteArray;
  77266. };
  77267. DDSTools._ExtractLongWordOrder = function (value) {
  77268. if (value === 0 || value === 255 || value === -16777216) {
  77269. return 0;
  77270. }
  77271. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  77272. };
  77273. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  77274. var byteArray = new Uint8Array(dataLength);
  77275. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77276. var index = 0;
  77277. for (var y = 0; y < height; y++) {
  77278. for (var x = 0; x < width; x++) {
  77279. var srcPos = (x + y * width) * 3;
  77280. byteArray[index] = srcData[srcPos + rOffset];
  77281. byteArray[index + 1] = srcData[srcPos + gOffset];
  77282. byteArray[index + 2] = srcData[srcPos + bOffset];
  77283. index += 3;
  77284. }
  77285. }
  77286. return byteArray;
  77287. };
  77288. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  77289. var byteArray = new Uint8Array(dataLength);
  77290. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  77291. var index = 0;
  77292. for (var y = 0; y < height; y++) {
  77293. for (var x = 0; x < width; x++) {
  77294. var srcPos = (x + y * width);
  77295. byteArray[index] = srcData[srcPos];
  77296. index++;
  77297. }
  77298. }
  77299. return byteArray;
  77300. };
  77301. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  77302. if (lodIndex === void 0) { lodIndex = -1; }
  77303. var ext = engine.getCaps().s3tc;
  77304. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  77305. var fourCC, width, height, dataLength = 0, dataOffset;
  77306. var byteArray, mipmapCount, mip;
  77307. var internalFormat = 0;
  77308. var format = 0;
  77309. var blockBytes = 1;
  77310. if (header[off_magic] !== DDS_MAGIC) {
  77311. BABYLON.Tools.Error("Invalid magic number in DDS header");
  77312. return;
  77313. }
  77314. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  77315. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  77316. return;
  77317. }
  77318. if (info.isCompressed && !ext) {
  77319. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  77320. return;
  77321. }
  77322. var bpp = header[off_RGBbpp];
  77323. dataOffset = header[off_size] + 4;
  77324. var computeFormats = false;
  77325. if (info.isFourCC) {
  77326. fourCC = header[off_pfFourCC];
  77327. switch (fourCC) {
  77328. case FOURCC_DXT1:
  77329. blockBytes = 8;
  77330. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  77331. break;
  77332. case FOURCC_DXT3:
  77333. blockBytes = 16;
  77334. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  77335. break;
  77336. case FOURCC_DXT5:
  77337. blockBytes = 16;
  77338. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  77339. break;
  77340. case FOURCC_D3DFMT_R16G16B16A16F:
  77341. computeFormats = true;
  77342. break;
  77343. case FOURCC_D3DFMT_R32G32B32A32F:
  77344. computeFormats = true;
  77345. break;
  77346. case FOURCC_DX10:
  77347. // There is an additionnal header so dataOffset need to be changed
  77348. dataOffset += 5 * 4; // 5 uints
  77349. var supported = false;
  77350. switch (info.dxgiFormat) {
  77351. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  77352. computeFormats = true;
  77353. supported = true;
  77354. break;
  77355. case DXGI_FORMAT_B8G8R8X8_UNORM:
  77356. info.isRGB = true;
  77357. info.isFourCC = false;
  77358. bpp = 32;
  77359. supported = true;
  77360. break;
  77361. }
  77362. if (supported) {
  77363. break;
  77364. }
  77365. default:
  77366. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  77367. return;
  77368. }
  77369. }
  77370. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  77371. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  77372. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  77373. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  77374. if (computeFormats) {
  77375. format = engine._getWebGLTextureType(info.textureType);
  77376. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77377. }
  77378. mipmapCount = 1;
  77379. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  77380. mipmapCount = Math.max(1, header[off_mipmapCount]);
  77381. }
  77382. for (var face = 0; face < faces; face++) {
  77383. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  77384. width = header[off_width];
  77385. height = header[off_height];
  77386. for (mip = 0; mip < mipmapCount; ++mip) {
  77387. if (lodIndex === -1 || lodIndex === mip) {
  77388. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  77389. var i = (lodIndex === -1) ? mip : 0;
  77390. if (!info.isCompressed && info.isFourCC) {
  77391. dataLength = width * height * 4;
  77392. var floatArray = null;
  77393. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  77394. if (bpp === 128) {
  77395. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77396. }
  77397. else if (bpp === 64) {
  77398. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77399. }
  77400. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  77401. format = engine._getWebGLTextureType(info.textureType);
  77402. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77403. }
  77404. else {
  77405. if (bpp === 128) {
  77406. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77407. }
  77408. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  77409. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77410. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  77411. format = engine._getWebGLTextureType(info.textureType);
  77412. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  77413. }
  77414. else {
  77415. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  77416. }
  77417. }
  77418. if (floatArray) {
  77419. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  77420. }
  77421. }
  77422. else if (info.isRGB) {
  77423. if (bpp === 24) {
  77424. dataLength = width * height * 3;
  77425. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  77426. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  77427. }
  77428. else {
  77429. dataLength = width * height * 4;
  77430. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  77431. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  77432. }
  77433. }
  77434. else if (info.isLuminance) {
  77435. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  77436. var unpaddedRowSize = width;
  77437. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  77438. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  77439. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  77440. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  77441. }
  77442. else {
  77443. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  77444. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  77445. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  77446. }
  77447. }
  77448. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  77449. width *= 0.5;
  77450. height *= 0.5;
  77451. width = Math.max(1.0, width);
  77452. height = Math.max(1.0, height);
  77453. }
  77454. if (currentFace !== undefined) {
  77455. // Loading a single face
  77456. break;
  77457. }
  77458. }
  77459. };
  77460. DDSTools.StoreLODInAlphaChannel = false;
  77461. return DDSTools;
  77462. }());
  77463. BABYLON.DDSTools = DDSTools;
  77464. })(BABYLON || (BABYLON = {}));
  77465. //# sourceMappingURL=babylon.dds.js.map
  77466. var BABYLON;
  77467. (function (BABYLON) {
  77468. /**
  77469. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  77470. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  77471. */
  77472. var KhronosTextureContainer = /** @class */ (function () {
  77473. /**
  77474. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  77475. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  77476. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  77477. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  77478. */
  77479. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  77480. this.arrayBuffer = arrayBuffer;
  77481. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  77482. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  77483. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  77484. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  77485. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  77486. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  77487. BABYLON.Tools.Error("texture missing KTX identifier");
  77488. return;
  77489. }
  77490. // load the reset of the header in native 32 bit int
  77491. var header = new Int32Array(this.arrayBuffer, 12, 13);
  77492. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  77493. var oppositeEndianess = header[0] === 0x01020304;
  77494. // read all the header elements in order they exist in the file, without modification (sans endainness)
  77495. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  77496. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  77497. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  77498. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  77499. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  77500. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  77501. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  77502. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  77503. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  77504. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  77505. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  77506. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  77507. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  77508. if (this.glType !== 0) {
  77509. BABYLON.Tools.Error("only compressed formats currently supported");
  77510. return;
  77511. }
  77512. else {
  77513. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  77514. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  77515. }
  77516. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  77517. BABYLON.Tools.Error("only 2D textures currently supported");
  77518. return;
  77519. }
  77520. if (this.numberOfArrayElements !== 0) {
  77521. BABYLON.Tools.Error("texture arrays not currently supported");
  77522. return;
  77523. }
  77524. if (this.numberOfFaces !== facesExpected) {
  77525. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  77526. return;
  77527. }
  77528. // we now have a completely validated file, so could use existence of loadType as success
  77529. // would need to make this more elaborate & adjust checks above to support more than one load type
  77530. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  77531. }
  77532. // not as fast hardware based, but will probably never need to use
  77533. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  77534. return ((val & 0xFF) << 24)
  77535. | ((val & 0xFF00) << 8)
  77536. | ((val >> 8) & 0xFF00)
  77537. | ((val >> 24) & 0xFF);
  77538. };
  77539. /**
  77540. * It is assumed that the texture has already been created & is currently bound
  77541. */
  77542. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  77543. switch (this.loadType) {
  77544. case KhronosTextureContainer.COMPRESSED_2D:
  77545. this._upload2DCompressedLevels(gl, loadMipmaps);
  77546. break;
  77547. case KhronosTextureContainer.TEX_2D:
  77548. case KhronosTextureContainer.COMPRESSED_3D:
  77549. case KhronosTextureContainer.TEX_3D:
  77550. }
  77551. };
  77552. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  77553. // initialize width & height for level 1
  77554. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  77555. var width = this.pixelWidth;
  77556. var height = this.pixelHeight;
  77557. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  77558. for (var level = 0; level < mipmapCount; level++) {
  77559. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  77560. for (var face = 0; face < this.numberOfFaces; face++) {
  77561. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  77562. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  77563. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  77564. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  77565. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  77566. }
  77567. width = Math.max(1.0, width * 0.5);
  77568. height = Math.max(1.0, height * 0.5);
  77569. }
  77570. };
  77571. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  77572. // load types
  77573. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  77574. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  77575. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  77576. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  77577. return KhronosTextureContainer;
  77578. }());
  77579. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  77580. })(BABYLON || (BABYLON = {}));
  77581. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  77582. var BABYLON;
  77583. (function (BABYLON) {
  77584. var Debug = /** @class */ (function () {
  77585. function Debug() {
  77586. }
  77587. Debug.AxesViewer = /** @class */ (function () {
  77588. function AxesViewer(scene, scaleLines) {
  77589. if (scaleLines === void 0) { scaleLines = 1; }
  77590. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77591. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77592. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77593. this.scaleLines = 1;
  77594. this.scaleLines = scaleLines;
  77595. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  77596. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  77597. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  77598. this._xmesh.renderingGroupId = 2;
  77599. this._ymesh.renderingGroupId = 2;
  77600. this._zmesh.renderingGroupId = 2;
  77601. this._xmesh.material.checkReadyOnlyOnce = true;
  77602. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  77603. this._ymesh.material.checkReadyOnlyOnce = true;
  77604. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  77605. this._zmesh.material.checkReadyOnlyOnce = true;
  77606. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  77607. this.scene = scene;
  77608. }
  77609. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  77610. var scaleLines = this.scaleLines;
  77611. if (this._xmesh) {
  77612. this._xmesh.position.copyFrom(position);
  77613. }
  77614. if (this._ymesh) {
  77615. this._ymesh.position.copyFrom(position);
  77616. }
  77617. if (this._zmesh) {
  77618. this._zmesh.position.copyFrom(position);
  77619. }
  77620. var point2 = this._xline[1];
  77621. point2.x = xaxis.x * scaleLines;
  77622. point2.y = xaxis.y * scaleLines;
  77623. point2.z = xaxis.z * scaleLines;
  77624. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  77625. point2 = this._yline[1];
  77626. point2.x = yaxis.x * scaleLines;
  77627. point2.y = yaxis.y * scaleLines;
  77628. point2.z = yaxis.z * scaleLines;
  77629. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  77630. point2 = this._zline[1];
  77631. point2.x = zaxis.x * scaleLines;
  77632. point2.y = zaxis.y * scaleLines;
  77633. point2.z = zaxis.z * scaleLines;
  77634. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  77635. };
  77636. AxesViewer.prototype.dispose = function () {
  77637. if (this._xmesh) {
  77638. this._xmesh.dispose();
  77639. }
  77640. if (this._ymesh) {
  77641. this._ymesh.dispose();
  77642. }
  77643. if (this._zmesh) {
  77644. this._zmesh.dispose();
  77645. }
  77646. this._xmesh = null;
  77647. this._ymesh = null;
  77648. this._zmesh = null;
  77649. this.scene = null;
  77650. };
  77651. return AxesViewer;
  77652. }());
  77653. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  77654. __extends(BoneAxesViewer, _super);
  77655. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  77656. if (scaleLines === void 0) { scaleLines = 1; }
  77657. var _this = _super.call(this, scene, scaleLines) || this;
  77658. _this.pos = BABYLON.Vector3.Zero();
  77659. _this.xaxis = BABYLON.Vector3.Zero();
  77660. _this.yaxis = BABYLON.Vector3.Zero();
  77661. _this.zaxis = BABYLON.Vector3.Zero();
  77662. _this.mesh = mesh;
  77663. _this.bone = bone;
  77664. return _this;
  77665. }
  77666. BoneAxesViewer.prototype.update = function () {
  77667. if (!this.mesh || !this.bone) {
  77668. return;
  77669. }
  77670. var bone = this.bone;
  77671. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  77672. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  77673. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  77674. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  77675. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  77676. };
  77677. BoneAxesViewer.prototype.dispose = function () {
  77678. if (this.mesh) {
  77679. this.mesh = null;
  77680. this.bone = null;
  77681. _super.prototype.dispose.call(this);
  77682. }
  77683. };
  77684. return BoneAxesViewer;
  77685. }(Debug.AxesViewer));
  77686. Debug.PhysicsViewer = /** @class */ (function () {
  77687. function PhysicsViewer(scene) {
  77688. this._impostors = [];
  77689. this._meshes = [];
  77690. this._numMeshes = 0;
  77691. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  77692. var physicEngine = this._scene.getPhysicsEngine();
  77693. if (physicEngine) {
  77694. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  77695. }
  77696. }
  77697. PhysicsViewer.prototype._updateDebugMeshes = function () {
  77698. var plugin = this._physicsEnginePlugin;
  77699. for (var i = 0; i < this._numMeshes; i++) {
  77700. var impostor = this._impostors[i];
  77701. if (!impostor) {
  77702. continue;
  77703. }
  77704. if (impostor.isDisposed) {
  77705. this.hideImpostor(this._impostors[i--]);
  77706. }
  77707. else {
  77708. var mesh = this._meshes[i];
  77709. if (mesh && plugin) {
  77710. plugin.syncMeshWithImpostor(mesh, impostor);
  77711. }
  77712. }
  77713. }
  77714. };
  77715. PhysicsViewer.prototype.showImpostor = function (impostor) {
  77716. if (!this._scene) {
  77717. return;
  77718. }
  77719. for (var i = 0; i < this._numMeshes; i++) {
  77720. if (this._impostors[i] == impostor) {
  77721. return;
  77722. }
  77723. }
  77724. var debugMesh = this._getDebugMesh(impostor, this._scene);
  77725. if (debugMesh) {
  77726. this._impostors[this._numMeshes] = impostor;
  77727. this._meshes[this._numMeshes] = debugMesh;
  77728. if (this._numMeshes === 0) {
  77729. this._renderFunction = this._updateDebugMeshes.bind(this);
  77730. this._scene.registerBeforeRender(this._renderFunction);
  77731. }
  77732. this._numMeshes++;
  77733. }
  77734. };
  77735. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  77736. if (!impostor || !this._scene) {
  77737. return;
  77738. }
  77739. var removed = false;
  77740. for (var i = 0; i < this._numMeshes; i++) {
  77741. if (this._impostors[i] == impostor) {
  77742. var mesh = this._meshes[i];
  77743. if (!mesh) {
  77744. continue;
  77745. }
  77746. this._scene.removeMesh(mesh);
  77747. mesh.dispose();
  77748. this._numMeshes--;
  77749. if (this._numMeshes > 0) {
  77750. this._meshes[i] = this._meshes[this._numMeshes];
  77751. this._impostors[i] = this._impostors[this._numMeshes];
  77752. this._meshes[this._numMeshes] = null;
  77753. this._impostors[this._numMeshes] = null;
  77754. }
  77755. else {
  77756. this._meshes[0] = null;
  77757. this._impostors[0] = null;
  77758. }
  77759. removed = true;
  77760. break;
  77761. }
  77762. }
  77763. if (removed && this._numMeshes === 0) {
  77764. this._scene.unregisterBeforeRender(this._renderFunction);
  77765. }
  77766. };
  77767. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  77768. if (!this._debugMaterial) {
  77769. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  77770. this._debugMaterial.wireframe = true;
  77771. }
  77772. return this._debugMaterial;
  77773. };
  77774. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  77775. if (!this._debugBoxMesh) {
  77776. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  77777. this._debugBoxMesh.renderingGroupId = 1;
  77778. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  77779. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  77780. scene.removeMesh(this._debugBoxMesh);
  77781. }
  77782. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  77783. };
  77784. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  77785. if (!this._debugSphereMesh) {
  77786. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  77787. this._debugSphereMesh.renderingGroupId = 1;
  77788. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  77789. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  77790. scene.removeMesh(this._debugSphereMesh);
  77791. }
  77792. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  77793. };
  77794. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  77795. var mesh = null;
  77796. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  77797. mesh = this._getDebugBoxMesh(scene);
  77798. impostor.getBoxSizeToRef(mesh.scaling);
  77799. }
  77800. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  77801. mesh = this._getDebugSphereMesh(scene);
  77802. var radius = impostor.getRadius();
  77803. mesh.scaling.x = radius * 2;
  77804. mesh.scaling.y = radius * 2;
  77805. mesh.scaling.z = radius * 2;
  77806. }
  77807. return mesh;
  77808. };
  77809. PhysicsViewer.prototype.dispose = function () {
  77810. for (var i = 0; i < this._numMeshes; i++) {
  77811. this.hideImpostor(this._impostors[i]);
  77812. }
  77813. if (this._debugBoxMesh) {
  77814. this._debugBoxMesh.dispose();
  77815. }
  77816. if (this._debugSphereMesh) {
  77817. this._debugSphereMesh.dispose();
  77818. }
  77819. if (this._debugMaterial) {
  77820. this._debugMaterial.dispose();
  77821. }
  77822. this._impostors.length = 0;
  77823. this._scene = null;
  77824. this._physicsEnginePlugin = null;
  77825. };
  77826. return PhysicsViewer;
  77827. }());
  77828. Debug.SkeletonViewer = /** @class */ (function () {
  77829. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  77830. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  77831. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  77832. this.skeleton = skeleton;
  77833. this.mesh = mesh;
  77834. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  77835. this.renderingGroupId = renderingGroupId;
  77836. this.color = BABYLON.Color3.White();
  77837. this._debugLines = new Array();
  77838. this._isEnabled = false;
  77839. this._scene = scene;
  77840. this.update();
  77841. this._renderFunction = this.update.bind(this);
  77842. }
  77843. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  77844. get: function () {
  77845. return this._isEnabled;
  77846. },
  77847. set: function (value) {
  77848. if (this._isEnabled === value) {
  77849. return;
  77850. }
  77851. this._isEnabled = value;
  77852. if (value) {
  77853. this._scene.registerBeforeRender(this._renderFunction);
  77854. }
  77855. else {
  77856. this._scene.unregisterBeforeRender(this._renderFunction);
  77857. }
  77858. },
  77859. enumerable: true,
  77860. configurable: true
  77861. });
  77862. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  77863. if (x === void 0) { x = 0; }
  77864. if (y === void 0) { y = 0; }
  77865. if (z === void 0) { z = 0; }
  77866. var tmat = BABYLON.Tmp.Matrix[0];
  77867. var parentBone = bone.getParent();
  77868. tmat.copyFrom(bone.getLocalMatrix());
  77869. if (x !== 0 || y !== 0 || z !== 0) {
  77870. var tmat2 = BABYLON.Tmp.Matrix[1];
  77871. BABYLON.Matrix.IdentityToRef(tmat2);
  77872. tmat2.m[12] = x;
  77873. tmat2.m[13] = y;
  77874. tmat2.m[14] = z;
  77875. tmat2.multiplyToRef(tmat, tmat);
  77876. }
  77877. if (parentBone) {
  77878. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  77879. }
  77880. tmat.multiplyToRef(meshMat, tmat);
  77881. position.x = tmat.m[12];
  77882. position.y = tmat.m[13];
  77883. position.z = tmat.m[14];
  77884. };
  77885. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  77886. var len = bones.length;
  77887. var meshPos = this.mesh.position;
  77888. for (var i = 0; i < len; i++) {
  77889. var bone = bones[i];
  77890. var points = this._debugLines[i];
  77891. if (!points) {
  77892. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77893. this._debugLines[i] = points;
  77894. }
  77895. this._getBonePosition(points[0], bone, meshMat);
  77896. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  77897. points[0].subtractInPlace(meshPos);
  77898. points[1].subtractInPlace(meshPos);
  77899. }
  77900. };
  77901. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  77902. var len = bones.length;
  77903. var boneNum = 0;
  77904. var meshPos = this.mesh.position;
  77905. for (var i = len - 1; i >= 0; i--) {
  77906. var childBone = bones[i];
  77907. var parentBone = childBone.getParent();
  77908. if (!parentBone) {
  77909. continue;
  77910. }
  77911. var points = this._debugLines[boneNum];
  77912. if (!points) {
  77913. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77914. this._debugLines[boneNum] = points;
  77915. }
  77916. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  77917. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  77918. points[0].subtractInPlace(meshPos);
  77919. points[1].subtractInPlace(meshPos);
  77920. boneNum++;
  77921. }
  77922. };
  77923. SkeletonViewer.prototype.update = function () {
  77924. if (this.autoUpdateBonesMatrices) {
  77925. this.skeleton.computeAbsoluteTransforms();
  77926. }
  77927. if (this.skeleton.bones[0].length === undefined) {
  77928. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  77929. }
  77930. else {
  77931. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  77932. }
  77933. if (!this._debugMesh) {
  77934. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  77935. this._debugMesh.renderingGroupId = this.renderingGroupId;
  77936. }
  77937. else {
  77938. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  77939. }
  77940. this._debugMesh.position.copyFrom(this.mesh.position);
  77941. this._debugMesh.color = this.color;
  77942. };
  77943. SkeletonViewer.prototype.dispose = function () {
  77944. if (this._debugMesh) {
  77945. this.isEnabled = false;
  77946. this._debugMesh.dispose();
  77947. this._debugMesh = null;
  77948. }
  77949. };
  77950. return SkeletonViewer;
  77951. }());
  77952. return Debug;
  77953. }());
  77954. BABYLON.Debug = Debug;
  77955. })(BABYLON || (BABYLON = {}));
  77956. //# sourceMappingURL=babylon.debugModules.js.map
  77957. var BABYLON;
  77958. (function (BABYLON) {
  77959. var RayHelper = /** @class */ (function () {
  77960. function RayHelper(ray) {
  77961. this.ray = ray;
  77962. }
  77963. RayHelper.CreateAndShow = function (ray, scene, color) {
  77964. var helper = new RayHelper(ray);
  77965. helper.show(scene, color);
  77966. return helper;
  77967. };
  77968. RayHelper.prototype.show = function (scene, color) {
  77969. if (!this._renderFunction && this.ray) {
  77970. var ray = this.ray;
  77971. this._renderFunction = this._render.bind(this);
  77972. this._scene = scene;
  77973. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  77974. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  77975. if (this._renderFunction) {
  77976. this._scene.registerBeforeRender(this._renderFunction);
  77977. }
  77978. }
  77979. if (color && this._renderLine) {
  77980. this._renderLine.color.copyFrom(color);
  77981. }
  77982. };
  77983. RayHelper.prototype.hide = function () {
  77984. if (this._renderFunction && this._scene) {
  77985. this._scene.unregisterBeforeRender(this._renderFunction);
  77986. this._scene = null;
  77987. this._renderFunction = null;
  77988. if (this._renderLine) {
  77989. this._renderLine.dispose();
  77990. this._renderLine = null;
  77991. }
  77992. this._renderPoints = [];
  77993. }
  77994. };
  77995. RayHelper.prototype._render = function () {
  77996. var ray = this.ray;
  77997. if (!ray) {
  77998. return;
  77999. }
  78000. var point = this._renderPoints[1];
  78001. var len = Math.min(ray.length, 1000000);
  78002. point.copyFrom(ray.direction);
  78003. point.scaleInPlace(len);
  78004. point.addInPlace(ray.origin);
  78005. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  78006. };
  78007. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  78008. this._attachedToMesh = mesh;
  78009. var ray = this.ray;
  78010. if (!ray) {
  78011. return;
  78012. }
  78013. if (!ray.direction) {
  78014. ray.direction = BABYLON.Vector3.Zero();
  78015. }
  78016. if (!ray.origin) {
  78017. ray.origin = BABYLON.Vector3.Zero();
  78018. }
  78019. if (length) {
  78020. ray.length = length;
  78021. }
  78022. if (!meshSpaceOrigin) {
  78023. meshSpaceOrigin = BABYLON.Vector3.Zero();
  78024. }
  78025. if (!meshSpaceDirection) {
  78026. // -1 so that this will work with Mesh.lookAt
  78027. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  78028. }
  78029. if (!this._meshSpaceDirection) {
  78030. this._meshSpaceDirection = meshSpaceDirection.clone();
  78031. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  78032. }
  78033. else {
  78034. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  78035. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  78036. }
  78037. if (!this._updateToMeshFunction) {
  78038. this._updateToMeshFunction = this._updateToMesh.bind(this);
  78039. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  78040. }
  78041. this._updateToMesh();
  78042. };
  78043. RayHelper.prototype.detachFromMesh = function () {
  78044. if (this._attachedToMesh) {
  78045. if (this._updateToMeshFunction) {
  78046. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  78047. }
  78048. this._attachedToMesh = null;
  78049. this._updateToMeshFunction = null;
  78050. }
  78051. };
  78052. RayHelper.prototype._updateToMesh = function () {
  78053. var ray = this.ray;
  78054. if (!this._attachedToMesh || !ray) {
  78055. return;
  78056. }
  78057. if (this._attachedToMesh._isDisposed) {
  78058. this.detachFromMesh();
  78059. return;
  78060. }
  78061. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  78062. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  78063. };
  78064. RayHelper.prototype.dispose = function () {
  78065. this.hide();
  78066. this.detachFromMesh();
  78067. this.ray = null;
  78068. };
  78069. return RayHelper;
  78070. }());
  78071. BABYLON.RayHelper = RayHelper;
  78072. })(BABYLON || (BABYLON = {}));
  78073. //# sourceMappingURL=babylon.rayHelper.js.map
  78074. var BABYLON;
  78075. (function (BABYLON) {
  78076. // load the inspector using require, if not present in the global namespace.
  78077. var DebugLayer = /** @class */ (function () {
  78078. function DebugLayer(scene) {
  78079. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78080. this._scene = scene;
  78081. // load inspector using require, if it doesn't exist on the global namespace.
  78082. }
  78083. /** Creates the inspector window. */
  78084. DebugLayer.prototype._createInspector = function (config) {
  78085. if (config === void 0) { config = {}; }
  78086. var popup = config.popup || false;
  78087. var initialTab = config.initialTab || 0;
  78088. var parentElement = config.parentElement || null;
  78089. if (!this._inspector) {
  78090. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  78091. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  78092. } // else nothing to do,; instance is already existing
  78093. };
  78094. DebugLayer.prototype.isVisible = function () {
  78095. if (!this._inspector) {
  78096. return false;
  78097. }
  78098. return true;
  78099. };
  78100. DebugLayer.prototype.hide = function () {
  78101. if (this._inspector) {
  78102. try {
  78103. this._inspector.dispose();
  78104. }
  78105. catch (e) {
  78106. // If the inspector has been removed directly from the inspector tool
  78107. }
  78108. this._inspector = null;
  78109. }
  78110. };
  78111. DebugLayer.prototype.show = function (config) {
  78112. if (config === void 0) { config = {}; }
  78113. if (typeof this.BJSINSPECTOR == 'undefined') {
  78114. // Load inspector and add it to the DOM
  78115. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  78116. }
  78117. else {
  78118. // Otherwise creates the inspector
  78119. this._createInspector(config);
  78120. }
  78121. };
  78122. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  78123. return DebugLayer;
  78124. }());
  78125. BABYLON.DebugLayer = DebugLayer;
  78126. })(BABYLON || (BABYLON = {}));
  78127. //# sourceMappingURL=babylon.debugLayer.js.map
  78128. var BABYLON;
  78129. (function (BABYLON) {
  78130. var BoundingBoxRenderer = /** @class */ (function () {
  78131. function BoundingBoxRenderer(scene) {
  78132. this.frontColor = new BABYLON.Color3(1, 1, 1);
  78133. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  78134. this.showBackLines = true;
  78135. this.renderList = new BABYLON.SmartArray(32);
  78136. this._vertexBuffers = {};
  78137. this._scene = scene;
  78138. }
  78139. BoundingBoxRenderer.prototype._prepareRessources = function () {
  78140. if (this._colorShader) {
  78141. return;
  78142. }
  78143. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  78144. attributes: [BABYLON.VertexBuffer.PositionKind],
  78145. uniforms: ["world", "viewProjection", "color"]
  78146. });
  78147. var engine = this._scene.getEngine();
  78148. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  78149. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  78150. this._createIndexBuffer();
  78151. };
  78152. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  78153. var engine = this._scene.getEngine();
  78154. 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]);
  78155. };
  78156. BoundingBoxRenderer.prototype._rebuild = function () {
  78157. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78158. if (vb) {
  78159. vb._rebuild();
  78160. }
  78161. this._createIndexBuffer();
  78162. };
  78163. BoundingBoxRenderer.prototype.reset = function () {
  78164. this.renderList.reset();
  78165. };
  78166. BoundingBoxRenderer.prototype.render = function () {
  78167. if (this.renderList.length === 0) {
  78168. return;
  78169. }
  78170. this._prepareRessources();
  78171. if (!this._colorShader.isReady()) {
  78172. return;
  78173. }
  78174. var engine = this._scene.getEngine();
  78175. engine.setDepthWrite(false);
  78176. this._colorShader._preBind();
  78177. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  78178. var boundingBox = this.renderList.data[boundingBoxIndex];
  78179. var min = boundingBox.minimum;
  78180. var max = boundingBox.maximum;
  78181. var diff = max.subtract(min);
  78182. var median = min.add(diff.scale(0.5));
  78183. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78184. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78185. .multiply(boundingBox.getWorldMatrix());
  78186. // VBOs
  78187. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78188. if (this.showBackLines) {
  78189. // Back
  78190. engine.setDepthFunctionToGreaterOrEqual();
  78191. this._scene.resetCachedMaterial();
  78192. this._colorShader.setColor4("color", this.backColor.toColor4());
  78193. this._colorShader.bind(worldMatrix);
  78194. // Draw order
  78195. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78196. }
  78197. // Front
  78198. engine.setDepthFunctionToLess();
  78199. this._scene.resetCachedMaterial();
  78200. this._colorShader.setColor4("color", this.frontColor.toColor4());
  78201. this._colorShader.bind(worldMatrix);
  78202. // Draw order
  78203. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78204. }
  78205. this._colorShader.unbind();
  78206. engine.setDepthFunctionToLessOrEqual();
  78207. engine.setDepthWrite(true);
  78208. };
  78209. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  78210. this._prepareRessources();
  78211. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  78212. return;
  78213. }
  78214. var engine = this._scene.getEngine();
  78215. engine.setDepthWrite(false);
  78216. engine.setColorWrite(false);
  78217. this._colorShader._preBind();
  78218. var boundingBox = mesh._boundingInfo.boundingBox;
  78219. var min = boundingBox.minimum;
  78220. var max = boundingBox.maximum;
  78221. var diff = max.subtract(min);
  78222. var median = min.add(diff.scale(0.5));
  78223. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  78224. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  78225. .multiply(boundingBox.getWorldMatrix());
  78226. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  78227. engine.setDepthFunctionToLess();
  78228. this._scene.resetCachedMaterial();
  78229. this._colorShader.bind(worldMatrix);
  78230. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  78231. this._colorShader.unbind();
  78232. engine.setDepthFunctionToLessOrEqual();
  78233. engine.setDepthWrite(true);
  78234. engine.setColorWrite(true);
  78235. };
  78236. BoundingBoxRenderer.prototype.dispose = function () {
  78237. if (!this._colorShader) {
  78238. return;
  78239. }
  78240. this.renderList.dispose();
  78241. this._colorShader.dispose();
  78242. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  78243. if (buffer) {
  78244. buffer.dispose();
  78245. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  78246. }
  78247. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  78248. };
  78249. return BoundingBoxRenderer;
  78250. }());
  78251. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  78252. })(BABYLON || (BABYLON = {}));
  78253. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  78254. var BABYLON;
  78255. (function (BABYLON) {
  78256. var MorphTarget = /** @class */ (function () {
  78257. function MorphTarget(name, influence) {
  78258. if (influence === void 0) { influence = 0; }
  78259. this.name = name;
  78260. this.animations = new Array();
  78261. this._positions = null;
  78262. this._normals = null;
  78263. this._tangents = null;
  78264. this.onInfluenceChanged = new BABYLON.Observable();
  78265. this.influence = influence;
  78266. }
  78267. Object.defineProperty(MorphTarget.prototype, "influence", {
  78268. get: function () {
  78269. return this._influence;
  78270. },
  78271. set: function (influence) {
  78272. if (this._influence === influence) {
  78273. return;
  78274. }
  78275. var previous = this._influence;
  78276. this._influence = influence;
  78277. if (this.onInfluenceChanged.hasObservers) {
  78278. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  78279. }
  78280. },
  78281. enumerable: true,
  78282. configurable: true
  78283. });
  78284. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  78285. get: function () {
  78286. return !!this._positions;
  78287. },
  78288. enumerable: true,
  78289. configurable: true
  78290. });
  78291. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  78292. get: function () {
  78293. return !!this._normals;
  78294. },
  78295. enumerable: true,
  78296. configurable: true
  78297. });
  78298. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  78299. get: function () {
  78300. return !!this._tangents;
  78301. },
  78302. enumerable: true,
  78303. configurable: true
  78304. });
  78305. MorphTarget.prototype.setPositions = function (data) {
  78306. this._positions = data;
  78307. };
  78308. MorphTarget.prototype.getPositions = function () {
  78309. return this._positions;
  78310. };
  78311. MorphTarget.prototype.setNormals = function (data) {
  78312. this._normals = data;
  78313. };
  78314. MorphTarget.prototype.getNormals = function () {
  78315. return this._normals;
  78316. };
  78317. MorphTarget.prototype.setTangents = function (data) {
  78318. this._tangents = data;
  78319. };
  78320. MorphTarget.prototype.getTangents = function () {
  78321. return this._tangents;
  78322. };
  78323. /**
  78324. * Serializes the current target into a Serialization object.
  78325. * Returns the serialized object.
  78326. */
  78327. MorphTarget.prototype.serialize = function () {
  78328. var serializationObject = {};
  78329. serializationObject.name = this.name;
  78330. serializationObject.influence = this.influence;
  78331. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  78332. if (this.hasNormals) {
  78333. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  78334. }
  78335. if (this.hasTangents) {
  78336. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  78337. }
  78338. // Animations
  78339. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  78340. return serializationObject;
  78341. };
  78342. // Statics
  78343. MorphTarget.Parse = function (serializationObject) {
  78344. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  78345. result.setPositions(serializationObject.positions);
  78346. if (serializationObject.normals) {
  78347. result.setNormals(serializationObject.normals);
  78348. }
  78349. if (serializationObject.tangents) {
  78350. result.setTangents(serializationObject.tangents);
  78351. }
  78352. // Animations
  78353. if (serializationObject.animations) {
  78354. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  78355. var parsedAnimation = serializationObject.animations[animationIndex];
  78356. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  78357. }
  78358. }
  78359. return result;
  78360. };
  78361. MorphTarget.FromMesh = function (mesh, name, influence) {
  78362. if (!name) {
  78363. name = mesh.name;
  78364. }
  78365. var result = new MorphTarget(name, influence);
  78366. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78367. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  78368. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  78369. }
  78370. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  78371. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  78372. }
  78373. return result;
  78374. };
  78375. return MorphTarget;
  78376. }());
  78377. BABYLON.MorphTarget = MorphTarget;
  78378. })(BABYLON || (BABYLON = {}));
  78379. //# sourceMappingURL=babylon.morphTarget.js.map
  78380. var BABYLON;
  78381. (function (BABYLON) {
  78382. var MorphTargetManager = /** @class */ (function () {
  78383. function MorphTargetManager(scene) {
  78384. if (scene === void 0) { scene = null; }
  78385. this._targets = new Array();
  78386. this._targetObservable = new Array();
  78387. this._activeTargets = new BABYLON.SmartArray(16);
  78388. this._supportsNormals = false;
  78389. this._supportsTangents = false;
  78390. this._vertexCount = 0;
  78391. this._uniqueId = 0;
  78392. this._tempInfluences = new Array();
  78393. if (!scene) {
  78394. scene = BABYLON.Engine.LastCreatedScene;
  78395. }
  78396. this._scene = scene;
  78397. if (this._scene) {
  78398. this._scene.morphTargetManagers.push(this);
  78399. this._uniqueId = this._scene.getUniqueId();
  78400. }
  78401. }
  78402. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  78403. get: function () {
  78404. return this._uniqueId;
  78405. },
  78406. enumerable: true,
  78407. configurable: true
  78408. });
  78409. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  78410. get: function () {
  78411. return this._vertexCount;
  78412. },
  78413. enumerable: true,
  78414. configurable: true
  78415. });
  78416. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  78417. get: function () {
  78418. return this._supportsNormals;
  78419. },
  78420. enumerable: true,
  78421. configurable: true
  78422. });
  78423. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  78424. get: function () {
  78425. return this._supportsTangents;
  78426. },
  78427. enumerable: true,
  78428. configurable: true
  78429. });
  78430. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  78431. get: function () {
  78432. return this._targets.length;
  78433. },
  78434. enumerable: true,
  78435. configurable: true
  78436. });
  78437. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  78438. get: function () {
  78439. return this._activeTargets.length;
  78440. },
  78441. enumerable: true,
  78442. configurable: true
  78443. });
  78444. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  78445. get: function () {
  78446. return this._influences;
  78447. },
  78448. enumerable: true,
  78449. configurable: true
  78450. });
  78451. MorphTargetManager.prototype.getActiveTarget = function (index) {
  78452. return this._activeTargets.data[index];
  78453. };
  78454. MorphTargetManager.prototype.getTarget = function (index) {
  78455. return this._targets[index];
  78456. };
  78457. MorphTargetManager.prototype.addTarget = function (target) {
  78458. var _this = this;
  78459. this._targets.push(target);
  78460. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  78461. _this._syncActiveTargets(needUpdate);
  78462. }));
  78463. this._syncActiveTargets(true);
  78464. };
  78465. MorphTargetManager.prototype.removeTarget = function (target) {
  78466. var index = this._targets.indexOf(target);
  78467. if (index >= 0) {
  78468. this._targets.splice(index, 1);
  78469. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  78470. this._syncActiveTargets(true);
  78471. }
  78472. };
  78473. /**
  78474. * Serializes the current manager into a Serialization object.
  78475. * Returns the serialized object.
  78476. */
  78477. MorphTargetManager.prototype.serialize = function () {
  78478. var serializationObject = {};
  78479. serializationObject.id = this.uniqueId;
  78480. serializationObject.targets = [];
  78481. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  78482. var target = _a[_i];
  78483. serializationObject.targets.push(target.serialize());
  78484. }
  78485. return serializationObject;
  78486. };
  78487. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  78488. var influenceCount = 0;
  78489. this._activeTargets.reset();
  78490. this._supportsNormals = true;
  78491. this._supportsTangents = true;
  78492. this._vertexCount = 0;
  78493. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  78494. var target = _a[_i];
  78495. this._activeTargets.push(target);
  78496. this._tempInfluences[influenceCount++] = target.influence;
  78497. var positions = target.getPositions();
  78498. if (positions) {
  78499. this._supportsNormals = this._supportsNormals && target.hasNormals;
  78500. this._supportsTangents = this._supportsTangents && target.hasTangents;
  78501. var vertexCount = positions.length / 3;
  78502. if (this._vertexCount === 0) {
  78503. this._vertexCount = vertexCount;
  78504. }
  78505. else if (this._vertexCount !== vertexCount) {
  78506. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  78507. return;
  78508. }
  78509. }
  78510. }
  78511. if (!this._influences || this._influences.length !== influenceCount) {
  78512. this._influences = new Float32Array(influenceCount);
  78513. }
  78514. for (var index = 0; index < influenceCount; index++) {
  78515. this._influences[index] = this._tempInfluences[index];
  78516. }
  78517. if (needUpdate && this._scene) {
  78518. // Flag meshes as dirty to resync with the active targets
  78519. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  78520. var mesh = _c[_b];
  78521. if (mesh.morphTargetManager === this) {
  78522. mesh._syncGeometryWithMorphTargetManager();
  78523. }
  78524. }
  78525. }
  78526. };
  78527. // Statics
  78528. MorphTargetManager.Parse = function (serializationObject, scene) {
  78529. var result = new MorphTargetManager(scene);
  78530. result._uniqueId = serializationObject.id;
  78531. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  78532. var targetData = _a[_i];
  78533. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  78534. }
  78535. return result;
  78536. };
  78537. return MorphTargetManager;
  78538. }());
  78539. BABYLON.MorphTargetManager = MorphTargetManager;
  78540. })(BABYLON || (BABYLON = {}));
  78541. //# sourceMappingURL=babylon.morphTargetManager.js.map
  78542. var BABYLON;
  78543. (function (BABYLON) {
  78544. var Octree = /** @class */ (function () {
  78545. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  78546. if (maxDepth === void 0) { maxDepth = 2; }
  78547. this.maxDepth = maxDepth;
  78548. this.dynamicContent = new Array();
  78549. this._maxBlockCapacity = maxBlockCapacity || 64;
  78550. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  78551. this._creationFunc = creationFunc;
  78552. }
  78553. // Methods
  78554. Octree.prototype.update = function (worldMin, worldMax, entries) {
  78555. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  78556. };
  78557. Octree.prototype.addMesh = function (entry) {
  78558. for (var index = 0; index < this.blocks.length; index++) {
  78559. var block = this.blocks[index];
  78560. block.addEntry(entry);
  78561. }
  78562. };
  78563. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  78564. this._selectionContent.reset();
  78565. for (var index = 0; index < this.blocks.length; index++) {
  78566. var block = this.blocks[index];
  78567. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  78568. }
  78569. if (allowDuplicate) {
  78570. this._selectionContent.concat(this.dynamicContent);
  78571. }
  78572. else {
  78573. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78574. }
  78575. return this._selectionContent;
  78576. };
  78577. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  78578. this._selectionContent.reset();
  78579. for (var index = 0; index < this.blocks.length; index++) {
  78580. var block = this.blocks[index];
  78581. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  78582. }
  78583. if (allowDuplicate) {
  78584. this._selectionContent.concat(this.dynamicContent);
  78585. }
  78586. else {
  78587. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78588. }
  78589. return this._selectionContent;
  78590. };
  78591. Octree.prototype.intersectsRay = function (ray) {
  78592. this._selectionContent.reset();
  78593. for (var index = 0; index < this.blocks.length; index++) {
  78594. var block = this.blocks[index];
  78595. block.intersectsRay(ray, this._selectionContent);
  78596. }
  78597. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  78598. return this._selectionContent;
  78599. };
  78600. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  78601. target.blocks = new Array();
  78602. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  78603. // Segmenting space
  78604. for (var x = 0; x < 2; x++) {
  78605. for (var y = 0; y < 2; y++) {
  78606. for (var z = 0; z < 2; z++) {
  78607. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  78608. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  78609. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  78610. block.addEntries(entries);
  78611. target.blocks.push(block);
  78612. }
  78613. }
  78614. }
  78615. };
  78616. Octree.CreationFuncForMeshes = function (entry, block) {
  78617. var boundingInfo = entry.getBoundingInfo();
  78618. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  78619. block.entries.push(entry);
  78620. }
  78621. };
  78622. Octree.CreationFuncForSubMeshes = function (entry, block) {
  78623. var boundingInfo = entry.getBoundingInfo();
  78624. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  78625. block.entries.push(entry);
  78626. }
  78627. };
  78628. return Octree;
  78629. }());
  78630. BABYLON.Octree = Octree;
  78631. })(BABYLON || (BABYLON = {}));
  78632. //# sourceMappingURL=babylon.octree.js.map
  78633. var BABYLON;
  78634. (function (BABYLON) {
  78635. var OctreeBlock = /** @class */ (function () {
  78636. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  78637. this.entries = new Array();
  78638. this._boundingVectors = new Array();
  78639. this._capacity = capacity;
  78640. this._depth = depth;
  78641. this._maxDepth = maxDepth;
  78642. this._creationFunc = creationFunc;
  78643. this._minPoint = minPoint;
  78644. this._maxPoint = maxPoint;
  78645. this._boundingVectors.push(minPoint.clone());
  78646. this._boundingVectors.push(maxPoint.clone());
  78647. this._boundingVectors.push(minPoint.clone());
  78648. this._boundingVectors[2].x = maxPoint.x;
  78649. this._boundingVectors.push(minPoint.clone());
  78650. this._boundingVectors[3].y = maxPoint.y;
  78651. this._boundingVectors.push(minPoint.clone());
  78652. this._boundingVectors[4].z = maxPoint.z;
  78653. this._boundingVectors.push(maxPoint.clone());
  78654. this._boundingVectors[5].z = minPoint.z;
  78655. this._boundingVectors.push(maxPoint.clone());
  78656. this._boundingVectors[6].x = minPoint.x;
  78657. this._boundingVectors.push(maxPoint.clone());
  78658. this._boundingVectors[7].y = minPoint.y;
  78659. }
  78660. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  78661. // Property
  78662. get: function () {
  78663. return this._capacity;
  78664. },
  78665. enumerable: true,
  78666. configurable: true
  78667. });
  78668. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  78669. get: function () {
  78670. return this._minPoint;
  78671. },
  78672. enumerable: true,
  78673. configurable: true
  78674. });
  78675. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  78676. get: function () {
  78677. return this._maxPoint;
  78678. },
  78679. enumerable: true,
  78680. configurable: true
  78681. });
  78682. // Methods
  78683. OctreeBlock.prototype.addEntry = function (entry) {
  78684. if (this.blocks) {
  78685. for (var index = 0; index < this.blocks.length; index++) {
  78686. var block = this.blocks[index];
  78687. block.addEntry(entry);
  78688. }
  78689. return;
  78690. }
  78691. this._creationFunc(entry, this);
  78692. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  78693. this.createInnerBlocks();
  78694. }
  78695. };
  78696. OctreeBlock.prototype.addEntries = function (entries) {
  78697. for (var index = 0; index < entries.length; index++) {
  78698. var mesh = entries[index];
  78699. this.addEntry(mesh);
  78700. }
  78701. };
  78702. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  78703. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  78704. if (this.blocks) {
  78705. for (var index = 0; index < this.blocks.length; index++) {
  78706. var block = this.blocks[index];
  78707. block.select(frustumPlanes, selection, allowDuplicate);
  78708. }
  78709. return;
  78710. }
  78711. if (allowDuplicate) {
  78712. selection.concat(this.entries);
  78713. }
  78714. else {
  78715. selection.concatWithNoDuplicate(this.entries);
  78716. }
  78717. }
  78718. };
  78719. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  78720. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  78721. if (this.blocks) {
  78722. for (var index = 0; index < this.blocks.length; index++) {
  78723. var block = this.blocks[index];
  78724. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  78725. }
  78726. return;
  78727. }
  78728. if (allowDuplicate) {
  78729. selection.concat(this.entries);
  78730. }
  78731. else {
  78732. selection.concatWithNoDuplicate(this.entries);
  78733. }
  78734. }
  78735. };
  78736. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  78737. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  78738. if (this.blocks) {
  78739. for (var index = 0; index < this.blocks.length; index++) {
  78740. var block = this.blocks[index];
  78741. block.intersectsRay(ray, selection);
  78742. }
  78743. return;
  78744. }
  78745. selection.concatWithNoDuplicate(this.entries);
  78746. }
  78747. };
  78748. OctreeBlock.prototype.createInnerBlocks = function () {
  78749. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  78750. };
  78751. return OctreeBlock;
  78752. }());
  78753. BABYLON.OctreeBlock = OctreeBlock;
  78754. })(BABYLON || (BABYLON = {}));
  78755. //# sourceMappingURL=babylon.octreeBlock.js.map
  78756. var BABYLON;
  78757. (function (BABYLON) {
  78758. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  78759. __extends(VRDistortionCorrectionPostProcess, _super);
  78760. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  78761. var _this = _super.call(this, name, "vrDistortionCorrection", [
  78762. 'LensCenter',
  78763. 'Scale',
  78764. 'ScaleIn',
  78765. 'HmdWarpParam'
  78766. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  78767. _this._isRightEye = isRightEye;
  78768. _this._distortionFactors = vrMetrics.distortionK;
  78769. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  78770. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  78771. _this.adaptScaleToCurrentViewport = true;
  78772. _this.onSizeChangedObservable.add(function () {
  78773. _this.aspectRatio = _this.width * .5 / _this.height;
  78774. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  78775. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  78776. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  78777. });
  78778. _this.onApplyObservable.add(function (effect) {
  78779. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  78780. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  78781. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  78782. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  78783. });
  78784. return _this;
  78785. }
  78786. return VRDistortionCorrectionPostProcess;
  78787. }(BABYLON.PostProcess));
  78788. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  78789. })(BABYLON || (BABYLON = {}));
  78790. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  78791. var BABYLON;
  78792. (function (BABYLON) {
  78793. var AnaglyphPostProcess = /** @class */ (function (_super) {
  78794. __extends(AnaglyphPostProcess, _super);
  78795. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  78796. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  78797. _this._passedProcess = rigCameras[0]._rigPostProcess;
  78798. _this.onApplyObservable.add(function (effect) {
  78799. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  78800. });
  78801. return _this;
  78802. }
  78803. return AnaglyphPostProcess;
  78804. }(BABYLON.PostProcess));
  78805. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  78806. })(BABYLON || (BABYLON = {}));
  78807. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  78808. var BABYLON;
  78809. (function (BABYLON) {
  78810. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  78811. __extends(StereoscopicInterlacePostProcess, _super);
  78812. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  78813. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  78814. _this._passedProcess = rigCameras[0]._rigPostProcess;
  78815. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  78816. _this.onSizeChangedObservable.add(function () {
  78817. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  78818. });
  78819. _this.onApplyObservable.add(function (effect) {
  78820. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  78821. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  78822. });
  78823. return _this;
  78824. }
  78825. return StereoscopicInterlacePostProcess;
  78826. }(BABYLON.PostProcess));
  78827. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  78828. })(BABYLON || (BABYLON = {}));
  78829. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  78830. var BABYLON;
  78831. (function (BABYLON) {
  78832. /**
  78833. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  78834. * Screen rotation is taken into account.
  78835. */
  78836. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  78837. function FreeCameraDeviceOrientationInput() {
  78838. var _this = this;
  78839. this._screenOrientationAngle = 0;
  78840. this._screenQuaternion = new BABYLON.Quaternion();
  78841. this._alpha = 0;
  78842. this._beta = 0;
  78843. this._gamma = 0;
  78844. this._orientationChanged = function () {
  78845. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  78846. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  78847. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  78848. };
  78849. this._deviceOrientation = function (evt) {
  78850. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  78851. _this._beta = evt.beta !== null ? evt.beta : 0;
  78852. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  78853. };
  78854. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  78855. this._orientationChanged();
  78856. }
  78857. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  78858. get: function () {
  78859. return this._camera;
  78860. },
  78861. set: function (camera) {
  78862. this._camera = camera;
  78863. if (this._camera != null && !this._camera.rotationQuaternion) {
  78864. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  78865. }
  78866. },
  78867. enumerable: true,
  78868. configurable: true
  78869. });
  78870. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  78871. window.addEventListener("orientationchange", this._orientationChanged);
  78872. window.addEventListener("deviceorientation", this._deviceOrientation);
  78873. //In certain cases, the attach control is called AFTER orientation was changed,
  78874. //So this is needed.
  78875. this._orientationChanged();
  78876. };
  78877. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  78878. window.removeEventListener("orientationchange", this._orientationChanged);
  78879. window.removeEventListener("deviceorientation", this._deviceOrientation);
  78880. };
  78881. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  78882. //if no device orientation provided, don't update the rotation.
  78883. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  78884. if (!this._alpha)
  78885. return;
  78886. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  78887. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  78888. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  78889. //Mirror on XY Plane
  78890. this._camera.rotationQuaternion.z *= -1;
  78891. this._camera.rotationQuaternion.w *= -1;
  78892. };
  78893. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  78894. return "FreeCameraDeviceOrientationInput";
  78895. };
  78896. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  78897. return "deviceOrientation";
  78898. };
  78899. return FreeCameraDeviceOrientationInput;
  78900. }());
  78901. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  78902. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  78903. })(BABYLON || (BABYLON = {}));
  78904. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  78905. var BABYLON;
  78906. (function (BABYLON) {
  78907. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  78908. function ArcRotateCameraVRDeviceOrientationInput() {
  78909. this.alphaCorrection = 1;
  78910. this.betaCorrection = 1;
  78911. this.gammaCorrection = 1;
  78912. this._alpha = 0;
  78913. this._gamma = 0;
  78914. this._dirty = false;
  78915. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  78916. }
  78917. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  78918. this.camera.attachControl(element, noPreventDefault);
  78919. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  78920. };
  78921. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  78922. if (evt.alpha !== null) {
  78923. this._alpha = +evt.alpha | 0;
  78924. }
  78925. if (evt.gamma !== null) {
  78926. this._gamma = +evt.gamma | 0;
  78927. }
  78928. this._dirty = true;
  78929. };
  78930. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  78931. if (this._dirty) {
  78932. this._dirty = false;
  78933. if (this._gamma < 0) {
  78934. this._gamma = 180 + this._gamma;
  78935. }
  78936. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  78937. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  78938. }
  78939. };
  78940. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  78941. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  78942. };
  78943. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  78944. return "ArcRotateCameraVRDeviceOrientationInput";
  78945. };
  78946. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  78947. return "VRDeviceOrientation";
  78948. };
  78949. return ArcRotateCameraVRDeviceOrientationInput;
  78950. }());
  78951. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  78952. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  78953. })(BABYLON || (BABYLON = {}));
  78954. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  78955. var BABYLON;
  78956. (function (BABYLON) {
  78957. var VRCameraMetrics = /** @class */ (function () {
  78958. function VRCameraMetrics() {
  78959. this.compensateDistortion = true;
  78960. }
  78961. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  78962. get: function () {
  78963. return this.hResolution / (2 * this.vResolution);
  78964. },
  78965. enumerable: true,
  78966. configurable: true
  78967. });
  78968. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  78969. get: function () {
  78970. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  78971. },
  78972. enumerable: true,
  78973. configurable: true
  78974. });
  78975. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  78976. get: function () {
  78977. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  78978. var h = (4 * meters) / this.hScreenSize;
  78979. return BABYLON.Matrix.Translation(h, 0, 0);
  78980. },
  78981. enumerable: true,
  78982. configurable: true
  78983. });
  78984. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  78985. get: function () {
  78986. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  78987. var h = (4 * meters) / this.hScreenSize;
  78988. return BABYLON.Matrix.Translation(-h, 0, 0);
  78989. },
  78990. enumerable: true,
  78991. configurable: true
  78992. });
  78993. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  78994. get: function () {
  78995. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  78996. },
  78997. enumerable: true,
  78998. configurable: true
  78999. });
  79000. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  79001. get: function () {
  79002. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  79003. },
  79004. enumerable: true,
  79005. configurable: true
  79006. });
  79007. VRCameraMetrics.GetDefault = function () {
  79008. var result = new VRCameraMetrics();
  79009. result.hResolution = 1280;
  79010. result.vResolution = 800;
  79011. result.hScreenSize = 0.149759993;
  79012. result.vScreenSize = 0.0935999975;
  79013. result.vScreenCenter = 0.0467999987;
  79014. result.eyeToScreenDistance = 0.0410000011;
  79015. result.lensSeparationDistance = 0.0635000020;
  79016. result.interpupillaryDistance = 0.0640000030;
  79017. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  79018. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  79019. result.postProcessScaleFactor = 1.714605507808412;
  79020. result.lensCenterOffset = 0.151976421;
  79021. return result;
  79022. };
  79023. return VRCameraMetrics;
  79024. }());
  79025. BABYLON.VRCameraMetrics = VRCameraMetrics;
  79026. })(BABYLON || (BABYLON = {}));
  79027. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  79028. var BABYLON;
  79029. (function (BABYLON) {
  79030. /**
  79031. * This represents a WebVR camera.
  79032. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  79033. * @example http://doc.babylonjs.com/how_to/webvr_camera
  79034. */
  79035. var WebVRFreeCamera = /** @class */ (function (_super) {
  79036. __extends(WebVRFreeCamera, _super);
  79037. /**
  79038. * Instantiates a WebVRFreeCamera.
  79039. * @param name The name of the WebVRFreeCamera
  79040. * @param position The starting anchor position for the camera
  79041. * @param scene The scene the camera belongs to
  79042. * @param webVROptions a set of customizable options for the webVRCamera
  79043. */
  79044. function WebVRFreeCamera(name, position, scene, webVROptions) {
  79045. if (webVROptions === void 0) { webVROptions = {}; }
  79046. var _this = _super.call(this, name, position, scene) || this;
  79047. _this.webVROptions = webVROptions;
  79048. /**
  79049. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  79050. */
  79051. _this._vrDevice = null;
  79052. /**
  79053. * The rawPose of the vrDevice.
  79054. */
  79055. _this.rawPose = null;
  79056. _this._specsVersion = "1.1";
  79057. _this._attached = false;
  79058. _this._descendants = [];
  79059. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  79060. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  79061. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  79062. _this._standingMatrix = null;
  79063. /**
  79064. * Represents device position in babylon space.
  79065. */
  79066. _this.devicePosition = BABYLON.Vector3.Zero();
  79067. /**
  79068. * Represents device rotation in babylon space.
  79069. */
  79070. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  79071. /**
  79072. * The scale of the device to be used when translating from device space to babylon space.
  79073. */
  79074. _this.deviceScaleFactor = 1;
  79075. _this._deviceToWorld = BABYLON.Matrix.Identity();
  79076. _this._worldToDevice = BABYLON.Matrix.Identity();
  79077. /**
  79078. * References to the webVR controllers for the vrDevice.
  79079. */
  79080. _this.controllers = [];
  79081. /**
  79082. * Emits an event when a controller is attached.
  79083. */
  79084. _this.onControllersAttachedObservable = new BABYLON.Observable();
  79085. /**
  79086. * Emits an event when a controller's mesh has been loaded;
  79087. */
  79088. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  79089. /**
  79090. * If the rig cameras be used as parent instead of this camera.
  79091. */
  79092. _this.rigParenting = true;
  79093. _this._defaultHeight = undefined;
  79094. _this._workingVector = BABYLON.Vector3.Zero();
  79095. _this._oneVector = BABYLON.Vector3.One();
  79096. _this._workingMatrix = BABYLON.Matrix.Identity();
  79097. _this._cache.position = BABYLON.Vector3.Zero();
  79098. if (webVROptions.defaultHeight) {
  79099. _this._defaultHeight = webVROptions.defaultHeight;
  79100. _this.position.y = _this._defaultHeight;
  79101. }
  79102. _this.minZ = 0.1;
  79103. //legacy support - the compensation boolean was removed.
  79104. if (arguments.length === 5) {
  79105. _this.webVROptions = arguments[4];
  79106. }
  79107. // default webVR options
  79108. if (_this.webVROptions.trackPosition == undefined) {
  79109. _this.webVROptions.trackPosition = true;
  79110. }
  79111. if (_this.webVROptions.controllerMeshes == undefined) {
  79112. _this.webVROptions.controllerMeshes = true;
  79113. }
  79114. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  79115. _this.webVROptions.defaultLightingOnControllers = true;
  79116. }
  79117. _this.rotationQuaternion = new BABYLON.Quaternion();
  79118. if (_this.webVROptions && _this.webVROptions.positionScale) {
  79119. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  79120. }
  79121. //enable VR
  79122. var engine = _this.getEngine();
  79123. _this._onVREnabled = function (success) { if (success) {
  79124. _this.initControllers();
  79125. } };
  79126. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  79127. engine.initWebVR().add(function (event) {
  79128. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  79129. return;
  79130. }
  79131. _this._vrDevice = event.vrDisplay;
  79132. //reset the rig parameters.
  79133. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  79134. if (_this._attached) {
  79135. _this.getEngine().enableVR();
  79136. }
  79137. });
  79138. if (typeof (VRFrameData) !== "undefined")
  79139. _this._frameData = new VRFrameData();
  79140. /**
  79141. * The idea behind the following lines:
  79142. * objects that have the camera as parent should actually have the rig cameras as a parent.
  79143. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  79144. * the second will not show it correctly.
  79145. *
  79146. * To solve this - each object that has the camera as parent will be added to a protected array.
  79147. * When the rig camera renders, it will take this array and set all of those to be its children.
  79148. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  79149. * Amazing!
  79150. */
  79151. scene.onBeforeCameraRenderObservable.add(function (camera) {
  79152. if (camera.parent === _this && _this.rigParenting) {
  79153. _this._descendants = _this.getDescendants(true, function (n) {
  79154. // don't take the cameras or the controllers!
  79155. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  79156. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  79157. return !isController && !isRigCamera;
  79158. });
  79159. _this._descendants.forEach(function (node) {
  79160. node.parent = camera;
  79161. });
  79162. }
  79163. });
  79164. scene.onAfterCameraRenderObservable.add(function (camera) {
  79165. if (camera.parent === _this && _this.rigParenting) {
  79166. _this._descendants.forEach(function (node) {
  79167. node.parent = _this;
  79168. });
  79169. }
  79170. });
  79171. return _this;
  79172. }
  79173. /**
  79174. * Gets the device distance from the ground in meters.
  79175. * @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.
  79176. */
  79177. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  79178. if (this._standingMatrix) {
  79179. // Add standing matrix offset to get real offset from ground in room
  79180. this._standingMatrix.getTranslationToRef(this._workingVector);
  79181. return this._deviceRoomPosition.y + this._workingVector.y;
  79182. }
  79183. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  79184. return this._defaultHeight || 0;
  79185. };
  79186. /**
  79187. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79188. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  79189. */
  79190. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  79191. var _this = this;
  79192. if (callback === void 0) { callback = function (bool) { }; }
  79193. // Use standing matrix if available
  79194. this.getEngine().initWebVRAsync().then(function (result) {
  79195. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  79196. callback(false);
  79197. }
  79198. else {
  79199. _this._standingMatrix = new BABYLON.Matrix();
  79200. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  79201. if (!_this.getScene().useRightHandedSystem) {
  79202. [2, 6, 8, 9, 14].forEach(function (num) {
  79203. if (_this._standingMatrix) {
  79204. _this._standingMatrix.m[num] *= -1;
  79205. }
  79206. });
  79207. }
  79208. callback(true);
  79209. }
  79210. });
  79211. };
  79212. /**
  79213. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  79214. * @returns A promise with a boolean set to if the standing matrix is supported.
  79215. */
  79216. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  79217. var _this = this;
  79218. return new Promise(function (res, rej) {
  79219. _this.useStandingMatrix(function (supported) {
  79220. res(supported);
  79221. });
  79222. });
  79223. };
  79224. /**
  79225. * Disposes the camera
  79226. */
  79227. WebVRFreeCamera.prototype.dispose = function () {
  79228. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  79229. _super.prototype.dispose.call(this);
  79230. };
  79231. /**
  79232. * Gets a vrController by name.
  79233. * @param name The name of the controller to retreive
  79234. * @returns the controller matching the name specified or null if not found
  79235. */
  79236. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  79237. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  79238. var gp = _a[_i];
  79239. if (gp.hand === name) {
  79240. return gp;
  79241. }
  79242. }
  79243. return null;
  79244. };
  79245. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  79246. /**
  79247. * The controller corrisponding to the users left hand.
  79248. */
  79249. get: function () {
  79250. if (!this._leftController) {
  79251. this._leftController = this.getControllerByName("left");
  79252. }
  79253. return this._leftController;
  79254. },
  79255. enumerable: true,
  79256. configurable: true
  79257. });
  79258. ;
  79259. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  79260. /**
  79261. * The controller corrisponding to the users right hand.
  79262. */
  79263. get: function () {
  79264. if (!this._rightController) {
  79265. this._rightController = this.getControllerByName("right");
  79266. }
  79267. return this._rightController;
  79268. },
  79269. enumerable: true,
  79270. configurable: true
  79271. });
  79272. ;
  79273. /**
  79274. * Casts a ray forward from the vrCamera's gaze.
  79275. * @param length Length of the ray (default: 100)
  79276. * @returns the ray corrisponding to the gaze
  79277. */
  79278. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  79279. if (length === void 0) { length = 100; }
  79280. if (this.leftCamera) {
  79281. // Use left eye to avoid computation to compute center on every call
  79282. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  79283. }
  79284. else {
  79285. return _super.prototype.getForwardRay.call(this, length);
  79286. }
  79287. };
  79288. /**
  79289. * Updates the camera based on device's frame data
  79290. */
  79291. WebVRFreeCamera.prototype._checkInputs = function () {
  79292. if (this._vrDevice && this._vrDevice.isPresenting) {
  79293. this._vrDevice.getFrameData(this._frameData);
  79294. this.updateFromDevice(this._frameData.pose);
  79295. }
  79296. _super.prototype._checkInputs.call(this);
  79297. };
  79298. /**
  79299. * Updates the poseControlled values based on the input device pose.
  79300. * @param poseData Pose coming from the device
  79301. */
  79302. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  79303. if (poseData && poseData.orientation) {
  79304. this.rawPose = poseData;
  79305. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  79306. if (this.getScene().useRightHandedSystem) {
  79307. this._deviceRoomRotationQuaternion.z *= -1;
  79308. this._deviceRoomRotationQuaternion.w *= -1;
  79309. }
  79310. if (this.webVROptions.trackPosition && this.rawPose.position) {
  79311. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  79312. if (this.getScene().useRightHandedSystem) {
  79313. this._deviceRoomPosition.z *= -1;
  79314. }
  79315. }
  79316. }
  79317. };
  79318. /**
  79319. * WebVR's attach control will start broadcasting frames to the device.
  79320. * Note that in certain browsers (chrome for example) this function must be called
  79321. * within a user-interaction callback. Example:
  79322. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  79323. *
  79324. * @param element html element to attach the vrDevice to
  79325. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  79326. */
  79327. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  79328. _super.prototype.attachControl.call(this, element, noPreventDefault);
  79329. this._attached = true;
  79330. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  79331. if (this._vrDevice) {
  79332. this.getEngine().enableVR();
  79333. }
  79334. };
  79335. /**
  79336. * Detaches the camera from the html element and disables VR
  79337. *
  79338. * @param element html element to detach from
  79339. */
  79340. WebVRFreeCamera.prototype.detachControl = function (element) {
  79341. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  79342. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  79343. _super.prototype.detachControl.call(this, element);
  79344. this._attached = false;
  79345. this.getEngine().disableVR();
  79346. };
  79347. /**
  79348. * @returns the name of this class
  79349. */
  79350. WebVRFreeCamera.prototype.getClassName = function () {
  79351. return "WebVRFreeCamera";
  79352. };
  79353. /**
  79354. * Calls resetPose on the vrDisplay
  79355. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  79356. */
  79357. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  79358. //uses the vrDisplay's "resetPose()".
  79359. //pitch and roll won't be affected.
  79360. this._vrDevice.resetPose();
  79361. };
  79362. /**
  79363. * Updates the rig cameras (left and right eye)
  79364. */
  79365. WebVRFreeCamera.prototype._updateRigCameras = function () {
  79366. var camLeft = this._rigCameras[0];
  79367. var camRight = this._rigCameras[1];
  79368. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79369. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  79370. camLeft.position.copyFrom(this._deviceRoomPosition);
  79371. camRight.position.copyFrom(this._deviceRoomPosition);
  79372. };
  79373. /**
  79374. * Updates the cached values of the camera
  79375. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  79376. */
  79377. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  79378. var _this = this;
  79379. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  79380. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  79381. if (!this.updateCacheCalled) {
  79382. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  79383. this.updateCacheCalled = true;
  79384. this.update();
  79385. }
  79386. // Set working vector to the device position in room space rotated by the new rotation
  79387. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  79388. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  79389. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  79390. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  79391. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  79392. // Add translation from anchor position
  79393. this._deviceToWorld.getTranslationToRef(this._workingVector);
  79394. this._workingVector.addInPlace(this.position);
  79395. this._workingVector.subtractInPlace(this._cache.position);
  79396. this._deviceToWorld.setTranslation(this._workingVector);
  79397. // Set an inverted matrix to be used when updating the camera
  79398. this._deviceToWorld.invertToRef(this._worldToDevice);
  79399. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  79400. this.controllers.forEach(function (controller) {
  79401. controller._deviceToWorld = _this._deviceToWorld;
  79402. controller.update();
  79403. });
  79404. }
  79405. if (!ignoreParentClass) {
  79406. _super.prototype._updateCache.call(this);
  79407. }
  79408. this.updateCacheCalled = false;
  79409. };
  79410. /**
  79411. * Updates the current device position and rotation in the babylon world
  79412. */
  79413. WebVRFreeCamera.prototype.update = function () {
  79414. // Get current device position in babylon world
  79415. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  79416. // Get current device rotation in babylon world
  79417. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  79418. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  79419. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  79420. _super.prototype.update.call(this);
  79421. };
  79422. /**
  79423. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  79424. * @returns an identity matrix
  79425. */
  79426. WebVRFreeCamera.prototype._getViewMatrix = function () {
  79427. return BABYLON.Matrix.Identity();
  79428. };
  79429. /**
  79430. * This function is called by the two RIG cameras.
  79431. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  79432. */
  79433. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  79434. var _this = this;
  79435. //WebVR 1.1
  79436. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  79437. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  79438. if (!this.getScene().useRightHandedSystem) {
  79439. [2, 6, 8, 9, 14].forEach(function (num) {
  79440. _this._webvrViewMatrix.m[num] *= -1;
  79441. });
  79442. }
  79443. // update the camera rotation matrix
  79444. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  79445. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  79446. // Computing target and final matrix
  79447. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  79448. var parentCamera = this._cameraRigParams["parentCamera"];
  79449. // should the view matrix be updated with scale and position offset?
  79450. if (parentCamera.deviceScaleFactor !== 1) {
  79451. this._webvrViewMatrix.invert();
  79452. // scale the position, if set
  79453. if (parentCamera.deviceScaleFactor) {
  79454. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  79455. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  79456. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  79457. }
  79458. this._webvrViewMatrix.invert();
  79459. }
  79460. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  79461. return this._webvrViewMatrix;
  79462. };
  79463. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  79464. var _this = this;
  79465. var parentCamera = this.parent;
  79466. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  79467. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  79468. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  79469. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  79470. //babylon compatible matrix
  79471. if (!this.getScene().useRightHandedSystem) {
  79472. [8, 9, 10, 11].forEach(function (num) {
  79473. _this._projectionMatrix.m[num] *= -1;
  79474. });
  79475. }
  79476. return this._projectionMatrix;
  79477. };
  79478. /**
  79479. * Initializes the controllers and their meshes
  79480. */
  79481. WebVRFreeCamera.prototype.initControllers = function () {
  79482. var _this = this;
  79483. this.controllers = [];
  79484. var manager = this.getScene().gamepadManager;
  79485. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  79486. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  79487. var webVrController = gamepad;
  79488. if (webVrController.defaultModel) {
  79489. webVrController.defaultModel.setEnabled(false);
  79490. }
  79491. if (webVrController.hand === "right") {
  79492. _this._rightController = null;
  79493. }
  79494. if (webVrController.hand === "left") {
  79495. _this._rightController = null;
  79496. }
  79497. var controllerIndex = _this.controllers.indexOf(webVrController);
  79498. if (controllerIndex !== -1) {
  79499. _this.controllers.splice(controllerIndex, 1);
  79500. }
  79501. }
  79502. });
  79503. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  79504. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  79505. var webVrController_1 = gamepad;
  79506. webVrController_1._deviceToWorld = _this._deviceToWorld;
  79507. if (_this.webVROptions.controllerMeshes) {
  79508. if (webVrController_1.defaultModel) {
  79509. webVrController_1.defaultModel.setEnabled(true);
  79510. }
  79511. else {
  79512. // Load the meshes
  79513. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  79514. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  79515. if (_this.webVROptions.defaultLightingOnControllers) {
  79516. if (!_this._lightOnControllers) {
  79517. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  79518. }
  79519. var activateLightOnSubMeshes_1 = function (mesh, light) {
  79520. var children = mesh.getChildren();
  79521. if (children.length !== 0) {
  79522. children.forEach(function (mesh) {
  79523. light.includedOnlyMeshes.push(mesh);
  79524. activateLightOnSubMeshes_1(mesh, light);
  79525. });
  79526. }
  79527. };
  79528. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  79529. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  79530. }
  79531. });
  79532. }
  79533. }
  79534. webVrController_1.attachToPoseControlledCamera(_this);
  79535. // since this is async - sanity check. Is the controller already stored?
  79536. if (_this.controllers.indexOf(webVrController_1) === -1) {
  79537. //add to the controllers array
  79538. _this.controllers.push(webVrController_1);
  79539. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  79540. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  79541. // So we're overriding setting left & right manually to be sure
  79542. var firstViveWandDetected = false;
  79543. for (var i = 0; i < _this.controllers.length; i++) {
  79544. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  79545. if (!firstViveWandDetected) {
  79546. firstViveWandDetected = true;
  79547. _this.controllers[i].hand = "left";
  79548. }
  79549. else {
  79550. _this.controllers[i].hand = "right";
  79551. }
  79552. }
  79553. }
  79554. //did we find enough controllers? Great! let the developer know.
  79555. if (_this.controllers.length >= 2) {
  79556. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  79557. }
  79558. }
  79559. }
  79560. });
  79561. };
  79562. return WebVRFreeCamera;
  79563. }(BABYLON.FreeCamera));
  79564. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  79565. })(BABYLON || (BABYLON = {}));
  79566. //# sourceMappingURL=babylon.webVRCamera.js.map
  79567. var BABYLON;
  79568. (function (BABYLON) {
  79569. // We're mainly based on the logic defined into the FreeCamera code
  79570. /**
  79571. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  79572. * being tilted forward or back and left or right.
  79573. */
  79574. var DeviceOrientationCamera = /** @class */ (function (_super) {
  79575. __extends(DeviceOrientationCamera, _super);
  79576. /**
  79577. * Creates a new device orientation camera. @see DeviceOrientationCamera
  79578. * @param name The name of the camera
  79579. * @param position The start position camera
  79580. * @param scene The scene the camera belongs to
  79581. */
  79582. function DeviceOrientationCamera(name, position, scene) {
  79583. var _this = _super.call(this, name, position, scene) || this;
  79584. _this._quaternionCache = new BABYLON.Quaternion();
  79585. _this.inputs.addDeviceOrientation();
  79586. return _this;
  79587. }
  79588. /**
  79589. * Gets the current instance class name ("DeviceOrientationCamera").
  79590. * This helps avoiding instanceof at run time.
  79591. * @returns the class name
  79592. */
  79593. DeviceOrientationCamera.prototype.getClassName = function () {
  79594. return "DeviceOrientationCamera";
  79595. };
  79596. /**
  79597. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  79598. */
  79599. DeviceOrientationCamera.prototype._checkInputs = function () {
  79600. _super.prototype._checkInputs.call(this);
  79601. this._quaternionCache.copyFrom(this.rotationQuaternion);
  79602. if (this._initialQuaternion) {
  79603. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  79604. }
  79605. };
  79606. /**
  79607. * Reset the camera to its default orientation on the specified axis only.
  79608. * @param axis The axis to reset
  79609. */
  79610. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  79611. var _this = this;
  79612. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  79613. //can only work if this camera has a rotation quaternion already.
  79614. if (!this.rotationQuaternion)
  79615. return;
  79616. if (!this._initialQuaternion) {
  79617. this._initialQuaternion = new BABYLON.Quaternion();
  79618. }
  79619. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  79620. ['x', 'y', 'z'].forEach(function (axisName) {
  79621. if (!axis[axisName]) {
  79622. _this._initialQuaternion[axisName] = 0;
  79623. }
  79624. else {
  79625. _this._initialQuaternion[axisName] *= -1;
  79626. }
  79627. });
  79628. this._initialQuaternion.normalize();
  79629. //force rotation update
  79630. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  79631. };
  79632. return DeviceOrientationCamera;
  79633. }(BABYLON.FreeCamera));
  79634. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  79635. })(BABYLON || (BABYLON = {}));
  79636. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  79637. var BABYLON;
  79638. (function (BABYLON) {
  79639. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  79640. __extends(VRDeviceOrientationFreeCamera, _super);
  79641. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  79642. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79643. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79644. var _this = _super.call(this, name, position, scene) || this;
  79645. vrCameraMetrics.compensateDistortion = compensateDistortion;
  79646. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  79647. return _this;
  79648. }
  79649. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  79650. return "VRDeviceOrientationFreeCamera";
  79651. };
  79652. return VRDeviceOrientationFreeCamera;
  79653. }(BABYLON.DeviceOrientationCamera));
  79654. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  79655. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  79656. __extends(VRDeviceOrientationGamepadCamera, _super);
  79657. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  79658. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79659. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79660. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  79661. _this.inputs.addGamepad();
  79662. return _this;
  79663. }
  79664. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  79665. return "VRDeviceOrientationGamepadCamera";
  79666. };
  79667. return VRDeviceOrientationGamepadCamera;
  79668. }(VRDeviceOrientationFreeCamera));
  79669. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  79670. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  79671. __extends(VRDeviceOrientationArcRotateCamera, _super);
  79672. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  79673. if (compensateDistortion === void 0) { compensateDistortion = true; }
  79674. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  79675. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79676. vrCameraMetrics.compensateDistortion = compensateDistortion;
  79677. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  79678. _this.inputs.addVRDeviceOrientation();
  79679. return _this;
  79680. }
  79681. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  79682. return "VRDeviceOrientationArcRotateCamera";
  79683. };
  79684. return VRDeviceOrientationArcRotateCamera;
  79685. }(BABYLON.ArcRotateCamera));
  79686. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  79687. })(BABYLON || (BABYLON = {}));
  79688. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  79689. var BABYLON;
  79690. (function (BABYLON) {
  79691. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  79692. __extends(AnaglyphFreeCamera, _super);
  79693. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  79694. var _this = _super.call(this, name, position, scene) || this;
  79695. _this.interaxialDistance = interaxialDistance;
  79696. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79697. return _this;
  79698. }
  79699. AnaglyphFreeCamera.prototype.getClassName = function () {
  79700. return "AnaglyphFreeCamera";
  79701. };
  79702. return AnaglyphFreeCamera;
  79703. }(BABYLON.FreeCamera));
  79704. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  79705. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  79706. __extends(AnaglyphArcRotateCamera, _super);
  79707. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  79708. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79709. _this.interaxialDistance = interaxialDistance;
  79710. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79711. return _this;
  79712. }
  79713. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  79714. return "AnaglyphArcRotateCamera";
  79715. };
  79716. return AnaglyphArcRotateCamera;
  79717. }(BABYLON.ArcRotateCamera));
  79718. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  79719. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  79720. __extends(AnaglyphGamepadCamera, _super);
  79721. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  79722. var _this = _super.call(this, name, position, scene) || this;
  79723. _this.interaxialDistance = interaxialDistance;
  79724. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79725. return _this;
  79726. }
  79727. AnaglyphGamepadCamera.prototype.getClassName = function () {
  79728. return "AnaglyphGamepadCamera";
  79729. };
  79730. return AnaglyphGamepadCamera;
  79731. }(BABYLON.GamepadCamera));
  79732. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  79733. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  79734. __extends(AnaglyphUniversalCamera, _super);
  79735. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  79736. var _this = _super.call(this, name, position, scene) || this;
  79737. _this.interaxialDistance = interaxialDistance;
  79738. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  79739. return _this;
  79740. }
  79741. AnaglyphUniversalCamera.prototype.getClassName = function () {
  79742. return "AnaglyphUniversalCamera";
  79743. };
  79744. return AnaglyphUniversalCamera;
  79745. }(BABYLON.UniversalCamera));
  79746. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  79747. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  79748. __extends(StereoscopicFreeCamera, _super);
  79749. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  79750. var _this = _super.call(this, name, position, scene) || this;
  79751. _this.interaxialDistance = interaxialDistance;
  79752. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79753. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79754. return _this;
  79755. }
  79756. StereoscopicFreeCamera.prototype.getClassName = function () {
  79757. return "StereoscopicFreeCamera";
  79758. };
  79759. return StereoscopicFreeCamera;
  79760. }(BABYLON.FreeCamera));
  79761. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  79762. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  79763. __extends(StereoscopicArcRotateCamera, _super);
  79764. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  79765. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  79766. _this.interaxialDistance = interaxialDistance;
  79767. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79768. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79769. return _this;
  79770. }
  79771. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  79772. return "StereoscopicArcRotateCamera";
  79773. };
  79774. return StereoscopicArcRotateCamera;
  79775. }(BABYLON.ArcRotateCamera));
  79776. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  79777. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  79778. __extends(StereoscopicGamepadCamera, _super);
  79779. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  79780. var _this = _super.call(this, name, position, scene) || this;
  79781. _this.interaxialDistance = interaxialDistance;
  79782. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79783. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79784. return _this;
  79785. }
  79786. StereoscopicGamepadCamera.prototype.getClassName = function () {
  79787. return "StereoscopicGamepadCamera";
  79788. };
  79789. return StereoscopicGamepadCamera;
  79790. }(BABYLON.GamepadCamera));
  79791. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  79792. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  79793. __extends(StereoscopicUniversalCamera, _super);
  79794. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  79795. var _this = _super.call(this, name, position, scene) || this;
  79796. _this.interaxialDistance = interaxialDistance;
  79797. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  79798. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  79799. return _this;
  79800. }
  79801. StereoscopicUniversalCamera.prototype.getClassName = function () {
  79802. return "StereoscopicUniversalCamera";
  79803. };
  79804. return StereoscopicUniversalCamera;
  79805. }(BABYLON.UniversalCamera));
  79806. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  79807. })(BABYLON || (BABYLON = {}));
  79808. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  79809. var BABYLON;
  79810. (function (BABYLON) {
  79811. /**
  79812. * Helps to quickly add VR support to an existing scene.
  79813. * See http://doc.babylonjs.com/how_to/webvr_helper
  79814. */
  79815. var VRExperienceHelper = /** @class */ (function () {
  79816. /**
  79817. * Instantiates a VRExperienceHelper.
  79818. * Helps to quickly add VR support to an existing scene.
  79819. * @param scene The scene the VRExperienceHelper belongs to.
  79820. * @param webVROptions Options to modify the vr experience helper's behavior.
  79821. */
  79822. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  79823. if (webVROptions === void 0) { webVROptions = {}; }
  79824. var _this = this;
  79825. this.webVROptions = webVROptions;
  79826. // Can the system support WebVR, even if a headset isn't plugged in?
  79827. this._webVRsupported = false;
  79828. // If WebVR is supported, is a headset plugged in and are we ready to present?
  79829. this._webVRready = false;
  79830. // Are we waiting for the requestPresent callback to complete?
  79831. this._webVRrequesting = false;
  79832. // Are we presenting to the headset right now?
  79833. this._webVRpresenting = false;
  79834. // Are we presenting in the fullscreen fallback?
  79835. this._fullscreenVRpresenting = false;
  79836. /**
  79837. * Observable raised when entering VR.
  79838. */
  79839. this.onEnteringVRObservable = new BABYLON.Observable();
  79840. /**
  79841. * Observable raised when exiting VR.
  79842. */
  79843. this.onExitingVRObservable = new BABYLON.Observable();
  79844. /**
  79845. * Observable raised when controller mesh is loaded.
  79846. */
  79847. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  79848. this._useCustomVRButton = false;
  79849. this._teleportationRequested = false;
  79850. this._teleportationEnabledOnLeftController = false;
  79851. this._teleportationEnabledOnRightController = false;
  79852. this._interactionsEnabledOnLeftController = false;
  79853. this._interactionsEnabledOnRightController = false;
  79854. this._leftControllerReady = false;
  79855. this._rightControllerReady = false;
  79856. this._floorMeshesCollection = [];
  79857. this._teleportationAllowed = false;
  79858. this._rotationAllowed = true;
  79859. this._teleportationRequestInitiated = false;
  79860. this._teleportationBackRequestInitiated = false;
  79861. this.teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  79862. this._rotationRightAsked = false;
  79863. this._rotationLeftAsked = false;
  79864. this._isDefaultTeleportationTarget = true;
  79865. this._teleportationFillColor = "#444444";
  79866. this._teleportationBorderColor = "#FFFFFF";
  79867. this._rotationAngle = 0;
  79868. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  79869. this._padSensibilityUp = 0.65;
  79870. this._padSensibilityDown = 0.35;
  79871. /**
  79872. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  79873. */
  79874. this.onNewMeshSelected = new BABYLON.Observable();
  79875. /**
  79876. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  79877. */
  79878. this.onNewMeshPicked = new BABYLON.Observable();
  79879. /**
  79880. * Observable raised before camera teleportation
  79881. */
  79882. this.onBeforeCameraTeleport = new BABYLON.Observable();
  79883. /**
  79884. * Observable raised after camera teleportation
  79885. */
  79886. this.onAfterCameraTeleport = new BABYLON.Observable();
  79887. /**
  79888. * Observable raised when current selected mesh gets unselected
  79889. */
  79890. this.onSelectedMeshUnselected = new BABYLON.Observable();
  79891. /**
  79892. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  79893. */
  79894. this.teleportationEnabled = true;
  79895. this._pointerDownOnMeshAsked = false;
  79896. this._isActionableMesh = false;
  79897. this._teleportationInitialized = false;
  79898. this._interactionsEnabled = false;
  79899. this._interactionsRequested = false;
  79900. this._displayGaze = true;
  79901. this._displayLaserPointer = true;
  79902. this._dpadPressed = true;
  79903. this._onResize = function () {
  79904. _this.moveButtonToBottomRight();
  79905. if (_this._fullscreenVRpresenting && _this._webVRready) {
  79906. _this.exitVR();
  79907. }
  79908. };
  79909. this._onFullscreenChange = function () {
  79910. if (document.fullscreen !== undefined) {
  79911. _this._fullscreenVRpresenting = document.fullscreen;
  79912. }
  79913. else if (document.mozFullScreen !== undefined) {
  79914. _this._fullscreenVRpresenting = document.mozFullScreen;
  79915. }
  79916. else if (document.webkitIsFullScreen !== undefined) {
  79917. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  79918. }
  79919. else if (document.msIsFullScreen !== undefined) {
  79920. _this._fullscreenVRpresenting = document.msIsFullScreen;
  79921. }
  79922. if (!_this._fullscreenVRpresenting && _this._canvas) {
  79923. _this.exitVR();
  79924. if (!_this._useCustomVRButton) {
  79925. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  79926. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  79927. }
  79928. }
  79929. };
  79930. this.beforeRender = function () {
  79931. _this._castRayAndSelectObject();
  79932. };
  79933. this._onNewGamepadConnected = function (gamepad) {
  79934. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  79935. if (gamepad.leftStick) {
  79936. gamepad.onleftstickchanged(function (stickValues) {
  79937. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  79938. // Listening to classic/xbox gamepad only if no VR controller is active
  79939. if ((!_this._leftLaserPointer && !_this._rightLaserPointer) ||
  79940. ((_this._leftLaserPointer && !_this._leftLaserPointer.isVisible) &&
  79941. (_this._rightLaserPointer && !_this._rightLaserPointer.isVisible))) {
  79942. _this._checkTeleportWithRay(stickValues);
  79943. _this._checkTeleportBackwards(stickValues);
  79944. }
  79945. }
  79946. });
  79947. }
  79948. if (gamepad.rightStick) {
  79949. gamepad.onrightstickchanged(function (stickValues) {
  79950. if (_this._teleportationInitialized) {
  79951. _this._checkRotate(stickValues);
  79952. }
  79953. });
  79954. }
  79955. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  79956. gamepad.onbuttondown(function (buttonPressed) {
  79957. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  79958. _this._selectionPointerDown();
  79959. }
  79960. });
  79961. gamepad.onbuttonup(function (buttonPressed) {
  79962. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  79963. _this._selectionPointerUp();
  79964. }
  79965. });
  79966. }
  79967. }
  79968. else {
  79969. var webVRController = gamepad;
  79970. _this._tryEnableInteractionOnController(webVRController);
  79971. }
  79972. };
  79973. // 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
  79974. this._tryEnableInteractionOnController = function (webVRController) {
  79975. if (webVRController.hand === "left") {
  79976. _this._leftControllerReady = true;
  79977. if (_this._interactionsRequested && !_this._interactionsEnabledOnLeftController) {
  79978. _this._enableInteractionOnController(webVRController);
  79979. }
  79980. if (_this._teleportationRequested && !_this._teleportationEnabledOnLeftController) {
  79981. _this._enableTeleportationOnController(webVRController);
  79982. }
  79983. }
  79984. if (webVRController.hand === "right") {
  79985. _this._rightControllerReady = true;
  79986. if (_this._interactionsRequested && !_this._interactionsEnabledOnRightController) {
  79987. _this._enableInteractionOnController(webVRController);
  79988. }
  79989. if (_this._teleportationRequested && !_this._teleportationEnabledOnRightController) {
  79990. _this._enableTeleportationOnController(webVRController);
  79991. }
  79992. }
  79993. };
  79994. this._onNewGamepadDisconnected = function (gamepad) {
  79995. if (gamepad instanceof BABYLON.WebVRController) {
  79996. if (gamepad.hand === "left") {
  79997. _this._interactionsEnabledOnLeftController = false;
  79998. _this._teleportationEnabledOnLeftController = false;
  79999. _this._leftControllerReady = false;
  80000. if (_this._leftLaserPointer) {
  80001. _this._leftLaserPointer.dispose();
  80002. }
  80003. }
  80004. if (gamepad.hand === "right") {
  80005. _this._interactionsEnabledOnRightController = false;
  80006. _this._teleportationEnabledOnRightController = false;
  80007. _this._rightControllerReady = false;
  80008. if (_this._rightLaserPointer) {
  80009. _this._rightLaserPointer.dispose();
  80010. }
  80011. }
  80012. }
  80013. };
  80014. this._workingVector = BABYLON.Vector3.Zero();
  80015. this._workingQuaternion = BABYLON.Quaternion.Identity();
  80016. this._workingMatrix = BABYLON.Matrix.Identity();
  80017. this._scene = scene;
  80018. this._canvas = scene.getEngine().getRenderingCanvas();
  80019. // Parse options
  80020. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  80021. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  80022. }
  80023. if (webVROptions.createDeviceOrientationCamera === undefined) {
  80024. webVROptions.createDeviceOrientationCamera = true;
  80025. }
  80026. if (webVROptions.defaultHeight === undefined) {
  80027. webVROptions.defaultHeight = 1.7;
  80028. }
  80029. if (webVROptions.useCustomVRButton) {
  80030. this._useCustomVRButton = true;
  80031. if (webVROptions.customVRButton) {
  80032. this._btnVR = webVROptions.customVRButton;
  80033. }
  80034. }
  80035. if (webVROptions.rayLength) {
  80036. this._rayLength = webVROptions.rayLength;
  80037. }
  80038. this._defaultHeight = webVROptions.defaultHeight;
  80039. // Set position
  80040. if (this._scene.activeCamera) {
  80041. this._position = this._scene.activeCamera.position.clone();
  80042. }
  80043. else {
  80044. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  80045. }
  80046. // Set non-vr camera
  80047. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  80048. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  80049. // Copy data from existing camera
  80050. if (this._scene.activeCamera) {
  80051. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  80052. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  80053. // Set rotation from previous camera
  80054. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  80055. var targetCamera = this._scene.activeCamera;
  80056. if (targetCamera.rotationQuaternion) {
  80057. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  80058. }
  80059. else {
  80060. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  80061. }
  80062. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  80063. }
  80064. }
  80065. this._scene.activeCamera = this._deviceOrientationCamera;
  80066. if (this._canvas) {
  80067. this._scene.activeCamera.attachControl(this._canvas);
  80068. }
  80069. }
  80070. else {
  80071. this._existingCamera = this._scene.activeCamera;
  80072. }
  80073. // Create VR cameras
  80074. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80075. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  80076. }
  80077. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  80078. this._webVRCamera.useStandingMatrix();
  80079. // Create default button
  80080. if (!this._useCustomVRButton) {
  80081. this._btnVR = document.createElement("BUTTON");
  80082. this._btnVR.className = "babylonVRicon";
  80083. this._btnVR.id = "babylonVRiconbtn";
  80084. this._btnVR.title = "Click to switch to VR";
  80085. 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) }";
  80086. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  80087. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  80088. // css += ".babylonVRicon.vrdisplaysupported { }";
  80089. // css += ".babylonVRicon.vrdisplayready { }";
  80090. // css += ".babylonVRicon.vrdisplayrequesting { }";
  80091. var style = document.createElement('style');
  80092. style.appendChild(document.createTextNode(css));
  80093. document.getElementsByTagName('head')[0].appendChild(style);
  80094. this.moveButtonToBottomRight();
  80095. }
  80096. // VR button click event
  80097. if (this._btnVR) {
  80098. this._btnVR.addEventListener("click", function () {
  80099. if (!_this.isInVRMode) {
  80100. _this.enterVR();
  80101. }
  80102. else {
  80103. _this.exitVR();
  80104. }
  80105. });
  80106. }
  80107. // Window events
  80108. window.addEventListener("resize", this._onResize);
  80109. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  80110. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  80111. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  80112. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  80113. // Display vr button when headset is connected
  80114. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  80115. this.displayVRButton();
  80116. }
  80117. else {
  80118. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  80119. if (e.vrDisplay) {
  80120. _this.displayVRButton();
  80121. }
  80122. });
  80123. }
  80124. // Exiting VR mode using 'ESC' key on desktop
  80125. this._onKeyDown = function (event) {
  80126. if (event.keyCode === 27 && _this.isInVRMode) {
  80127. _this.exitVR();
  80128. }
  80129. };
  80130. document.addEventListener("keydown", this._onKeyDown);
  80131. // Exiting VR mode double tapping the touch screen
  80132. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  80133. if (_this.isInVRMode) {
  80134. _this.exitVR();
  80135. if (_this._fullscreenVRpresenting) {
  80136. _this._scene.getEngine().switchFullscreen(true);
  80137. }
  80138. }
  80139. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  80140. // Listen for WebVR display changes
  80141. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  80142. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  80143. this._onVRRequestPresentStart = function () {
  80144. _this._webVRrequesting = true;
  80145. _this.updateButtonVisibility();
  80146. };
  80147. this._onVRRequestPresentComplete = function (success) {
  80148. _this._webVRrequesting = false;
  80149. _this.updateButtonVisibility();
  80150. };
  80151. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  80152. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  80153. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  80154. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  80155. scene.onDisposeObservable.add(function () {
  80156. _this.dispose();
  80157. });
  80158. // Gamepad connection events
  80159. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  80160. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  80161. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  80162. this.updateButtonVisibility();
  80163. //create easing functions
  80164. this._circleEase = new BABYLON.CircleEase();
  80165. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  80166. }
  80167. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  80168. /** Return this.onEnteringVRObservable
  80169. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  80170. */
  80171. get: function () {
  80172. return this.onEnteringVRObservable;
  80173. },
  80174. enumerable: true,
  80175. configurable: true
  80176. });
  80177. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  80178. /** Return this.onExitingVRObservable
  80179. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  80180. */
  80181. get: function () {
  80182. return this.onExitingVRObservable;
  80183. },
  80184. enumerable: true,
  80185. configurable: true
  80186. });
  80187. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  80188. /** Return this.onControllerMeshLoadedObservable
  80189. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  80190. */
  80191. get: function () {
  80192. return this.onControllerMeshLoadedObservable;
  80193. },
  80194. enumerable: true,
  80195. configurable: true
  80196. });
  80197. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  80198. /**
  80199. * The mesh used to display where the user is going to teleport.
  80200. */
  80201. get: function () {
  80202. return this._teleportationTarget;
  80203. },
  80204. /**
  80205. * Sets the mesh to be used to display where the user is going to teleport.
  80206. */
  80207. set: function (value) {
  80208. if (value) {
  80209. value.name = "teleportationTarget";
  80210. this._isDefaultTeleportationTarget = false;
  80211. this._teleportationTarget = value;
  80212. }
  80213. },
  80214. enumerable: true,
  80215. configurable: true
  80216. });
  80217. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  80218. /**
  80219. * The mesh used to display where the user is selecting,
  80220. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  80221. * See http://doc.babylonjs.com/resources/baking_transformations
  80222. */
  80223. get: function () {
  80224. return this._gazeTracker;
  80225. },
  80226. set: function (value) {
  80227. if (value) {
  80228. this._gazeTracker = value;
  80229. this._gazeTracker.bakeCurrentTransformIntoVertices();
  80230. this._gazeTracker.isPickable = false;
  80231. this._gazeTracker.isVisible = false;
  80232. }
  80233. },
  80234. enumerable: true,
  80235. configurable: true
  80236. });
  80237. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  80238. /**
  80239. * If the ray of the gaze should be displayed.
  80240. */
  80241. get: function () {
  80242. return this._displayGaze;
  80243. },
  80244. /**
  80245. * Sets if the ray of the gaze should be displayed.
  80246. */
  80247. set: function (value) {
  80248. this._displayGaze = value;
  80249. if (!value) {
  80250. this._gazeTracker.isVisible = false;
  80251. }
  80252. },
  80253. enumerable: true,
  80254. configurable: true
  80255. });
  80256. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  80257. /**
  80258. * If the ray of the LaserPointer should be displayed.
  80259. */
  80260. get: function () {
  80261. return this._displayLaserPointer;
  80262. },
  80263. /**
  80264. * Sets if the ray of the LaserPointer should be displayed.
  80265. */
  80266. set: function (value) {
  80267. this._displayLaserPointer = value;
  80268. if (!value) {
  80269. if (this._rightLaserPointer) {
  80270. this._rightLaserPointer.isVisible = false;
  80271. }
  80272. if (this._leftLaserPointer) {
  80273. this._leftLaserPointer.isVisible = false;
  80274. }
  80275. }
  80276. else {
  80277. if (this._rightLaserPointer) {
  80278. this._rightLaserPointer.isVisible = true;
  80279. }
  80280. else if (this._leftLaserPointer) {
  80281. this._leftLaserPointer.isVisible = true;
  80282. }
  80283. }
  80284. },
  80285. enumerable: true,
  80286. configurable: true
  80287. });
  80288. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  80289. /**
  80290. * The deviceOrientationCamera used as the camera when not in VR.
  80291. */
  80292. get: function () {
  80293. return this._deviceOrientationCamera;
  80294. },
  80295. enumerable: true,
  80296. configurable: true
  80297. });
  80298. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  80299. /**
  80300. * Based on the current WebVR support, returns the current VR camera used.
  80301. */
  80302. get: function () {
  80303. if (this._webVRready) {
  80304. return this._webVRCamera;
  80305. }
  80306. else {
  80307. return this._scene.activeCamera;
  80308. }
  80309. },
  80310. enumerable: true,
  80311. configurable: true
  80312. });
  80313. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  80314. /**
  80315. * The webVRCamera which is used when in VR.
  80316. */
  80317. get: function () {
  80318. return this._webVRCamera;
  80319. },
  80320. enumerable: true,
  80321. configurable: true
  80322. });
  80323. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  80324. /**
  80325. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  80326. */
  80327. get: function () {
  80328. return this._vrDeviceOrientationCamera;
  80329. },
  80330. enumerable: true,
  80331. configurable: true
  80332. });
  80333. // Raised when one of the controller has loaded successfully its associated default mesh
  80334. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  80335. this._tryEnableInteractionOnController(webVRController);
  80336. try {
  80337. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  80338. }
  80339. catch (err) {
  80340. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  80341. }
  80342. };
  80343. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  80344. /**
  80345. * Gets a value indicating if we are currently in VR mode.
  80346. */
  80347. get: function () {
  80348. return this._webVRpresenting || this._fullscreenVRpresenting;
  80349. },
  80350. enumerable: true,
  80351. configurable: true
  80352. });
  80353. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  80354. var vrDisplay = this._scene.getEngine().getVRDevice();
  80355. if (vrDisplay) {
  80356. var wasPresenting = this._webVRpresenting;
  80357. // A VR display is connected
  80358. this._webVRpresenting = vrDisplay.isPresenting;
  80359. if (wasPresenting && !this._webVRpresenting)
  80360. this.exitVR();
  80361. }
  80362. else {
  80363. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  80364. }
  80365. this.updateButtonVisibility();
  80366. };
  80367. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  80368. this._webVRsupported = eventArgs.vrSupported;
  80369. this._webVRready = !!eventArgs.vrDisplay;
  80370. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  80371. this.updateButtonVisibility();
  80372. };
  80373. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  80374. if (this._canvas && !this._useCustomVRButton) {
  80375. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  80376. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  80377. }
  80378. };
  80379. VRExperienceHelper.prototype.displayVRButton = function () {
  80380. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  80381. document.body.appendChild(this._btnVR);
  80382. this._btnVRDisplayed = true;
  80383. }
  80384. };
  80385. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  80386. if (!this._btnVR || this._useCustomVRButton) {
  80387. return;
  80388. }
  80389. this._btnVR.className = "babylonVRicon";
  80390. if (this.isInVRMode) {
  80391. this._btnVR.className += " vrdisplaypresenting";
  80392. }
  80393. else {
  80394. if (this._webVRready)
  80395. this._btnVR.className += " vrdisplayready";
  80396. if (this._webVRsupported)
  80397. this._btnVR.className += " vrdisplaysupported";
  80398. if (this._webVRrequesting)
  80399. this._btnVR.className += " vrdisplayrequesting";
  80400. }
  80401. };
  80402. /**
  80403. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  80404. * Otherwise, will use the fullscreen API.
  80405. */
  80406. VRExperienceHelper.prototype.enterVR = function () {
  80407. if (this.onEnteringVRObservable) {
  80408. try {
  80409. this.onEnteringVRObservable.notifyObservers(this);
  80410. }
  80411. catch (err) {
  80412. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  80413. }
  80414. }
  80415. if (this._scene.activeCamera) {
  80416. this._position = this._scene.activeCamera.position.clone();
  80417. // make sure that we return to the last active camera
  80418. this._existingCamera = this._scene.activeCamera;
  80419. }
  80420. if (this._webVRrequesting)
  80421. return;
  80422. // If WebVR is supported and a headset is connected
  80423. if (this._webVRready) {
  80424. if (!this._webVRpresenting) {
  80425. this._webVRCamera.position = this._position;
  80426. this._scene.activeCamera = this._webVRCamera;
  80427. }
  80428. }
  80429. else if (this._vrDeviceOrientationCamera) {
  80430. this._vrDeviceOrientationCamera.position = this._position;
  80431. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  80432. this._scene.getEngine().switchFullscreen(true);
  80433. this.updateButtonVisibility();
  80434. }
  80435. if (this._scene.activeCamera && this._canvas) {
  80436. this._scene.activeCamera.attachControl(this._canvas);
  80437. }
  80438. if (this._interactionsEnabled) {
  80439. this._scene.registerBeforeRender(this.beforeRender);
  80440. }
  80441. };
  80442. /**
  80443. * Attempt to exit VR, or fullscreen.
  80444. */
  80445. VRExperienceHelper.prototype.exitVR = function () {
  80446. if (this.onExitingVRObservable) {
  80447. try {
  80448. this.onExitingVRObservable.notifyObservers(this);
  80449. }
  80450. catch (err) {
  80451. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  80452. }
  80453. }
  80454. if (this._webVRpresenting) {
  80455. this._scene.getEngine().disableVR();
  80456. }
  80457. if (this._scene.activeCamera) {
  80458. this._position = this._scene.activeCamera.position.clone();
  80459. }
  80460. if (this._deviceOrientationCamera) {
  80461. this._deviceOrientationCamera.position = this._position;
  80462. this._scene.activeCamera = this._deviceOrientationCamera;
  80463. if (this._canvas) {
  80464. this._scene.activeCamera.attachControl(this._canvas);
  80465. }
  80466. }
  80467. else if (this._existingCamera) {
  80468. this._existingCamera.position = this._position;
  80469. this._scene.activeCamera = this._existingCamera;
  80470. }
  80471. this.updateButtonVisibility();
  80472. if (this._interactionsEnabled) {
  80473. this._scene.unregisterBeforeRender(this.beforeRender);
  80474. }
  80475. };
  80476. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  80477. /**
  80478. * The position of the vr experience helper.
  80479. */
  80480. get: function () {
  80481. return this._position;
  80482. },
  80483. /**
  80484. * Sets the position of the vr experience helper.
  80485. */
  80486. set: function (value) {
  80487. this._position = value;
  80488. if (this._scene.activeCamera) {
  80489. this._scene.activeCamera.position = value;
  80490. }
  80491. },
  80492. enumerable: true,
  80493. configurable: true
  80494. });
  80495. /**
  80496. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  80497. */
  80498. VRExperienceHelper.prototype.enableInteractions = function () {
  80499. var _this = this;
  80500. if (!this._interactionsEnabled) {
  80501. this._interactionsRequested = true;
  80502. if (this._leftControllerReady && this._webVRCamera.leftController) {
  80503. this._enableInteractionOnController(this._webVRCamera.leftController);
  80504. }
  80505. if (this._rightControllerReady && this._webVRCamera.rightController) {
  80506. this._enableInteractionOnController(this._webVRCamera.rightController);
  80507. }
  80508. if (!this._gazeTracker) {
  80509. this._createGazeTracker();
  80510. }
  80511. this.raySelectionPredicate = function (mesh) {
  80512. return mesh.isVisible;
  80513. };
  80514. this.meshSelectionPredicate = function (mesh) {
  80515. return true;
  80516. };
  80517. this._raySelectionPredicate = function (mesh) {
  80518. if (_this._isTeleportationFloor(mesh) || (mesh != _this._gazeTracker
  80519. && mesh.name.indexOf("teleportationTarget") === -1
  80520. && mesh.name.indexOf("torusTeleportation") === -1
  80521. && mesh.name.indexOf("laserPointer") === -1)) {
  80522. return _this.raySelectionPredicate(mesh);
  80523. }
  80524. return false;
  80525. };
  80526. this._interactionsEnabled = true;
  80527. }
  80528. };
  80529. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  80530. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  80531. if (this._floorMeshesCollection[i].id === mesh.id) {
  80532. return true;
  80533. }
  80534. }
  80535. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  80536. return true;
  80537. }
  80538. return false;
  80539. };
  80540. /**
  80541. * Adds a floor mesh to be used for teleportation.
  80542. * @param floorMesh the mesh to be used for teleportation.
  80543. */
  80544. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  80545. if (!this._floorMeshesCollection) {
  80546. return;
  80547. }
  80548. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  80549. return;
  80550. }
  80551. this._floorMeshesCollection.push(floorMesh);
  80552. };
  80553. /**
  80554. * Removes a floor mesh from being used for teleportation.
  80555. * @param floorMesh the mesh to be removed.
  80556. */
  80557. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  80558. if (!this._floorMeshesCollection) {
  80559. return;
  80560. }
  80561. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  80562. if (meshIndex !== -1) {
  80563. this._floorMeshesCollection.splice(meshIndex, 1);
  80564. }
  80565. };
  80566. /**
  80567. * Enables interactions and teleportation using the VR controllers and gaze.
  80568. * @param vrTeleportationOptions options to modify teleportation behavior.
  80569. */
  80570. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  80571. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  80572. if (!this._teleportationInitialized) {
  80573. this._teleportationRequested = true;
  80574. this.enableInteractions();
  80575. if (vrTeleportationOptions.floorMeshName) {
  80576. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  80577. }
  80578. if (vrTeleportationOptions.floorMeshes) {
  80579. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  80580. }
  80581. if (this._leftControllerReady && this._webVRCamera.leftController) {
  80582. this._enableTeleportationOnController(this._webVRCamera.leftController);
  80583. }
  80584. if (this._rightControllerReady && this._webVRCamera.rightController) {
  80585. this._enableTeleportationOnController(this._webVRCamera.rightController);
  80586. }
  80587. // Creates an image processing post process for the vignette not relying
  80588. // on the main scene configuration for image processing to reduce setup and spaces
  80589. // (gamma/linear) conflicts.
  80590. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  80591. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  80592. imageProcessingConfiguration.vignetteEnabled = true;
  80593. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  80594. this._webVRCamera.detachPostProcess(this._postProcessMove);
  80595. this._teleportationInitialized = true;
  80596. if (this._isDefaultTeleportationTarget) {
  80597. this._createTeleportationCircles();
  80598. }
  80599. }
  80600. };
  80601. VRExperienceHelper.prototype._enableInteractionOnController = function (webVRController) {
  80602. var _this = this;
  80603. var controllerMesh = webVRController.mesh;
  80604. if (controllerMesh) {
  80605. var makeNotPick = function (root) {
  80606. root.name += " laserPointer";
  80607. root.getChildMeshes().forEach(function (c) {
  80608. makeNotPick(c);
  80609. });
  80610. };
  80611. makeNotPick(controllerMesh);
  80612. var childMeshes = controllerMesh.getChildMeshes();
  80613. for (var i = 0; i < childMeshes.length; i++) {
  80614. if (childMeshes[i].name && childMeshes[i].name.indexOf("POINTING_POSE") >= 0) {
  80615. controllerMesh = childMeshes[i];
  80616. break;
  80617. }
  80618. }
  80619. var laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, this._scene, false);
  80620. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", this._scene);
  80621. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80622. laserPointerMaterial.alpha = 0.6;
  80623. laserPointer.material = laserPointerMaterial;
  80624. laserPointer.rotation.x = Math.PI / 2;
  80625. laserPointer.parent = controllerMesh;
  80626. laserPointer.position.z = -0.5;
  80627. laserPointer.isVisible = false;
  80628. if (webVRController.hand === "left") {
  80629. this._leftLaserPointer = laserPointer;
  80630. this._interactionsEnabledOnLeftController = true;
  80631. if (!this._rightLaserPointer) {
  80632. this._leftLaserPointer.isVisible = true;
  80633. }
  80634. }
  80635. else {
  80636. this._rightLaserPointer = laserPointer;
  80637. this._interactionsEnabledOnRightController = true;
  80638. if (!this._leftLaserPointer) {
  80639. this._rightLaserPointer.isVisible = true;
  80640. }
  80641. }
  80642. webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  80643. // Enabling / disabling laserPointer
  80644. if (_this._displayLaserPointer && stateObject.value === 1) {
  80645. laserPointer.isVisible = !laserPointer.isVisible;
  80646. // Laser pointer can only be active on left or right, not both at the same time
  80647. if (webVRController.hand === "left" && _this._rightLaserPointer) {
  80648. _this._rightLaserPointer.isVisible = false;
  80649. }
  80650. else if (_this._leftLaserPointer) {
  80651. _this._leftLaserPointer.isVisible = false;
  80652. }
  80653. }
  80654. });
  80655. webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  80656. if (!_this._pointerDownOnMeshAsked) {
  80657. if (stateObject.value > _this._padSensibilityUp) {
  80658. _this._selectionPointerDown();
  80659. }
  80660. }
  80661. else if (stateObject.value < _this._padSensibilityDown) {
  80662. _this._selectionPointerUp();
  80663. }
  80664. });
  80665. }
  80666. };
  80667. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, webVRController) {
  80668. if (webVRController === void 0) { webVRController = null; }
  80669. if (!this._teleportationRequestInitiated) {
  80670. if (stateObject.y < -this._padSensibilityUp && this._dpadPressed) {
  80671. if (webVRController) {
  80672. // If laser pointer wasn't enabled yet
  80673. if (this._displayLaserPointer && webVRController.hand === "left" && this._leftLaserPointer) {
  80674. this._leftLaserPointer.isVisible = true;
  80675. if (this._rightLaserPointer) {
  80676. this._rightLaserPointer.isVisible = false;
  80677. }
  80678. }
  80679. else if (this._displayLaserPointer && this._rightLaserPointer) {
  80680. this._rightLaserPointer.isVisible = true;
  80681. if (this._leftLaserPointer) {
  80682. this._leftLaserPointer.isVisible = false;
  80683. }
  80684. }
  80685. }
  80686. this._teleportationRequestInitiated = true;
  80687. }
  80688. }
  80689. else {
  80690. // Listening to the proper controller values changes to confirm teleportation
  80691. if (webVRController == null
  80692. || (webVRController.hand === "left" && this._leftLaserPointer && this._leftLaserPointer.isVisible)
  80693. || (webVRController.hand === "right" && this._rightLaserPointer && this._rightLaserPointer.isVisible)) {
  80694. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  80695. if (this._teleportationAllowed) {
  80696. this._teleportationAllowed = false;
  80697. this._teleportCamera();
  80698. }
  80699. this._teleportationRequestInitiated = false;
  80700. }
  80701. }
  80702. }
  80703. };
  80704. VRExperienceHelper.prototype._selectionPointerDown = function () {
  80705. this._pointerDownOnMeshAsked = true;
  80706. if (this._currentMeshSelected && this._currentHit) {
  80707. this._scene.simulatePointerDown(this._currentHit);
  80708. }
  80709. };
  80710. VRExperienceHelper.prototype._selectionPointerUp = function () {
  80711. if (this._currentMeshSelected && this._currentHit) {
  80712. this._scene.simulatePointerUp(this._currentHit);
  80713. }
  80714. this._pointerDownOnMeshAsked = false;
  80715. };
  80716. VRExperienceHelper.prototype._checkRotate = function (stateObject) {
  80717. // Only rotate when user is not currently selecting a teleportation location
  80718. if (this._teleportationRequestInitiated) {
  80719. return;
  80720. }
  80721. if (!this._rotationLeftAsked) {
  80722. if (stateObject.x < -this._padSensibilityUp && this._dpadPressed) {
  80723. this._rotationLeftAsked = true;
  80724. if (this._rotationAllowed) {
  80725. this._rotateCamera(false);
  80726. }
  80727. }
  80728. }
  80729. else {
  80730. if (stateObject.x > -this._padSensibilityDown) {
  80731. this._rotationLeftAsked = false;
  80732. }
  80733. }
  80734. if (!this._rotationRightAsked) {
  80735. if (stateObject.x > this._padSensibilityUp && this._dpadPressed) {
  80736. this._rotationRightAsked = true;
  80737. if (this._rotationAllowed) {
  80738. this._rotateCamera(true);
  80739. }
  80740. }
  80741. }
  80742. else {
  80743. if (stateObject.x < this._padSensibilityDown) {
  80744. this._rotationRightAsked = false;
  80745. }
  80746. }
  80747. };
  80748. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject) {
  80749. // Only teleport backwards when user is not currently selecting a teleportation location
  80750. if (this._teleportationRequestInitiated) {
  80751. return;
  80752. }
  80753. // Teleport backwards
  80754. if (stateObject.y > this._padSensibilityUp && this._dpadPressed) {
  80755. if (!this._teleportationBackRequestInitiated) {
  80756. if (!this.currentVRCamera) {
  80757. return;
  80758. }
  80759. // Get rotation and position of the current camera
  80760. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  80761. var position = this.currentVRCamera.position;
  80762. // If the camera has device position, use that instead
  80763. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  80764. rotation = this.currentVRCamera.deviceRotationQuaternion;
  80765. position = this.currentVRCamera.devicePosition;
  80766. }
  80767. // Get matrix with only the y rotation of the device rotation
  80768. rotation.toEulerAnglesToRef(this._workingVector);
  80769. this._workingVector.z = 0;
  80770. this._workingVector.x = 0;
  80771. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  80772. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  80773. // Rotate backwards ray by device rotation to cast at the ground behind the user
  80774. BABYLON.Vector3.TransformCoordinatesToRef(this.teleportBackwardsVector, this._workingMatrix, this._workingVector);
  80775. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  80776. var ray = new BABYLON.Ray(position, this._workingVector);
  80777. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  80778. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  80779. this._teleportCamera(hit.pickedPoint);
  80780. }
  80781. this._teleportationBackRequestInitiated = true;
  80782. }
  80783. }
  80784. else {
  80785. this._teleportationBackRequestInitiated = false;
  80786. }
  80787. };
  80788. VRExperienceHelper.prototype._enableTeleportationOnController = function (webVRController) {
  80789. var _this = this;
  80790. var controllerMesh = webVRController.mesh;
  80791. if (controllerMesh) {
  80792. if (webVRController.hand === "left") {
  80793. if (!this._interactionsEnabledOnLeftController) {
  80794. this._enableInteractionOnController(webVRController);
  80795. }
  80796. this._teleportationEnabledOnLeftController = true;
  80797. }
  80798. else {
  80799. if (!this._interactionsEnabledOnRightController) {
  80800. this._enableInteractionOnController(webVRController);
  80801. }
  80802. this._teleportationEnabledOnRightController = true;
  80803. }
  80804. if (webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  80805. this._dpadPressed = false;
  80806. webVRController.onPadStateChangedObservable.add(function (stateObject) {
  80807. _this._dpadPressed = stateObject.pressed;
  80808. if (!_this._dpadPressed) {
  80809. _this._rotationLeftAsked = false;
  80810. _this._rotationRightAsked = false;
  80811. _this._teleportationBackRequestInitiated = false;
  80812. }
  80813. });
  80814. }
  80815. webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  80816. if (_this.teleportationEnabled) {
  80817. _this._checkTeleportBackwards(stateObject);
  80818. _this._checkTeleportWithRay(stateObject, webVRController);
  80819. }
  80820. _this._checkRotate(stateObject);
  80821. });
  80822. }
  80823. };
  80824. // Gaze support used to point to teleport or to interact with an object
  80825. VRExperienceHelper.prototype._createGazeTracker = function () {
  80826. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, this._scene, false);
  80827. this._gazeTracker.bakeCurrentTransformIntoVertices();
  80828. this._gazeTracker.isPickable = false;
  80829. this._gazeTracker.isVisible = false;
  80830. var targetMat = new BABYLON.StandardMaterial("targetMat", this._scene);
  80831. targetMat.specularColor = BABYLON.Color3.Black();
  80832. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  80833. targetMat.backFaceCulling = false;
  80834. this._gazeTracker.material = targetMat;
  80835. };
  80836. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  80837. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  80838. this._teleportationTarget.isPickable = false;
  80839. var length = 512;
  80840. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  80841. dynamicTexture.hasAlpha = true;
  80842. var context = dynamicTexture.getContext();
  80843. var centerX = length / 2;
  80844. var centerY = length / 2;
  80845. var radius = 200;
  80846. context.beginPath();
  80847. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  80848. context.fillStyle = this._teleportationFillColor;
  80849. context.fill();
  80850. context.lineWidth = 10;
  80851. context.strokeStyle = this._teleportationBorderColor;
  80852. context.stroke();
  80853. context.closePath();
  80854. dynamicTexture.update();
  80855. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  80856. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  80857. this._teleportationTarget.material = teleportationCircleMaterial;
  80858. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  80859. torus.isPickable = false;
  80860. torus.parent = this._teleportationTarget;
  80861. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  80862. var keys = [];
  80863. keys.push({
  80864. frame: 0,
  80865. value: 0
  80866. });
  80867. keys.push({
  80868. frame: 30,
  80869. value: 0.4
  80870. });
  80871. keys.push({
  80872. frame: 60,
  80873. value: 0
  80874. });
  80875. animationInnerCircle.setKeys(keys);
  80876. var easingFunction = new BABYLON.SineEase();
  80877. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  80878. animationInnerCircle.setEasingFunction(easingFunction);
  80879. torus.animations = [];
  80880. torus.animations.push(animationInnerCircle);
  80881. this._scene.beginAnimation(torus, 0, 60, true);
  80882. this._hideTeleportationTarget();
  80883. };
  80884. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  80885. if (this._teleportationInitialized) {
  80886. this._teleportationTarget.isVisible = true;
  80887. if (this._isDefaultTeleportationTarget) {
  80888. this._teleportationTarget.getChildren()[0].isVisible = true;
  80889. }
  80890. }
  80891. };
  80892. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  80893. if (this._teleportationInitialized) {
  80894. this._teleportationTarget.isVisible = false;
  80895. if (this._isDefaultTeleportationTarget) {
  80896. this._teleportationTarget.getChildren()[0].isVisible = false;
  80897. }
  80898. }
  80899. };
  80900. VRExperienceHelper.prototype._rotateCamera = function (right) {
  80901. var _this = this;
  80902. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  80903. return;
  80904. }
  80905. if (right) {
  80906. this._rotationAngle++;
  80907. }
  80908. else {
  80909. this._rotationAngle--;
  80910. }
  80911. this.currentVRCamera.animations = [];
  80912. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  80913. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80914. var animationRotationKeys = [];
  80915. animationRotationKeys.push({
  80916. frame: 0,
  80917. value: this.currentVRCamera.rotationQuaternion
  80918. });
  80919. animationRotationKeys.push({
  80920. frame: 6,
  80921. value: target
  80922. });
  80923. animationRotation.setKeys(animationRotationKeys);
  80924. animationRotation.setEasingFunction(this._circleEase);
  80925. this.currentVRCamera.animations.push(animationRotation);
  80926. this._postProcessMove.animations = [];
  80927. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80928. var vignetteWeightKeys = [];
  80929. vignetteWeightKeys.push({
  80930. frame: 0,
  80931. value: 0
  80932. });
  80933. vignetteWeightKeys.push({
  80934. frame: 3,
  80935. value: 4
  80936. });
  80937. vignetteWeightKeys.push({
  80938. frame: 6,
  80939. value: 0
  80940. });
  80941. animationPP.setKeys(vignetteWeightKeys);
  80942. animationPP.setEasingFunction(this._circleEase);
  80943. this._postProcessMove.animations.push(animationPP);
  80944. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  80945. var vignetteStretchKeys = [];
  80946. vignetteStretchKeys.push({
  80947. frame: 0,
  80948. value: 0
  80949. });
  80950. vignetteStretchKeys.push({
  80951. frame: 3,
  80952. value: 10
  80953. });
  80954. vignetteStretchKeys.push({
  80955. frame: 6,
  80956. value: 0
  80957. });
  80958. animationPP2.setKeys(vignetteStretchKeys);
  80959. animationPP2.setEasingFunction(this._circleEase);
  80960. this._postProcessMove.animations.push(animationPP2);
  80961. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  80962. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  80963. this._postProcessMove.samples = 4;
  80964. this._webVRCamera.attachPostProcess(this._postProcessMove);
  80965. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  80966. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  80967. });
  80968. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  80969. };
  80970. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit) {
  80971. if (hit.pickedPoint) {
  80972. this._teleportationAllowed = true;
  80973. if (this._teleportationRequestInitiated) {
  80974. this._displayTeleportationTarget();
  80975. }
  80976. else {
  80977. this._hideTeleportationTarget();
  80978. }
  80979. this._haloCenter.copyFrom(hit.pickedPoint);
  80980. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  80981. var pickNormal = hit.getNormal(true, false);
  80982. if (pickNormal) {
  80983. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  80984. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  80985. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  80986. }
  80987. this._teleportationTarget.position.y += 0.1;
  80988. }
  80989. };
  80990. VRExperienceHelper.prototype._teleportCamera = function (location) {
  80991. var _this = this;
  80992. if (location === void 0) { location = null; }
  80993. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  80994. return;
  80995. }
  80996. if (!location) {
  80997. location = this._haloCenter;
  80998. }
  80999. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  81000. // offset of the headset from the anchor.
  81001. if (this.webVRCamera.leftCamera) {
  81002. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  81003. this._workingVector.subtractInPlace(this.webVRCamera.position);
  81004. location.subtractToRef(this._workingVector, this._workingVector);
  81005. }
  81006. else {
  81007. this._workingVector.copyFrom(location);
  81008. }
  81009. // Add height to account for user's height offset
  81010. if (this.isInVRMode) {
  81011. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround();
  81012. }
  81013. else {
  81014. this._workingVector.y += this._defaultHeight;
  81015. }
  81016. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  81017. // Create animation from the camera's position to the new location
  81018. this.currentVRCamera.animations = [];
  81019. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81020. var animationCameraTeleportationKeys = [{
  81021. frame: 0,
  81022. value: this.currentVRCamera.position
  81023. },
  81024. {
  81025. frame: 11,
  81026. value: this._workingVector
  81027. }
  81028. ];
  81029. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  81030. animationCameraTeleportation.setEasingFunction(this._circleEase);
  81031. this.currentVRCamera.animations.push(animationCameraTeleportation);
  81032. this._postProcessMove.animations = [];
  81033. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81034. var vignetteWeightKeys = [];
  81035. vignetteWeightKeys.push({
  81036. frame: 0,
  81037. value: 0
  81038. });
  81039. vignetteWeightKeys.push({
  81040. frame: 5,
  81041. value: 8
  81042. });
  81043. vignetteWeightKeys.push({
  81044. frame: 11,
  81045. value: 0
  81046. });
  81047. animationPP.setKeys(vignetteWeightKeys);
  81048. this._postProcessMove.animations.push(animationPP);
  81049. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  81050. var vignetteStretchKeys = [];
  81051. vignetteStretchKeys.push({
  81052. frame: 0,
  81053. value: 0
  81054. });
  81055. vignetteStretchKeys.push({
  81056. frame: 5,
  81057. value: 10
  81058. });
  81059. vignetteStretchKeys.push({
  81060. frame: 11,
  81061. value: 0
  81062. });
  81063. animationPP2.setKeys(vignetteStretchKeys);
  81064. this._postProcessMove.animations.push(animationPP2);
  81065. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  81066. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  81067. this._webVRCamera.attachPostProcess(this._postProcessMove);
  81068. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  81069. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  81070. });
  81071. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  81072. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  81073. });
  81074. };
  81075. VRExperienceHelper.prototype._castRayAndSelectObject = function () {
  81076. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  81077. return;
  81078. }
  81079. var ray;
  81080. if (this._leftLaserPointer && this._leftLaserPointer.isVisible && this.currentVRCamera.leftController) {
  81081. ray = this.currentVRCamera.leftController.getForwardRay(this._rayLength);
  81082. }
  81083. else if (this._rightLaserPointer && this._rightLaserPointer.isVisible && this.currentVRCamera.rightController) {
  81084. ray = this.currentVRCamera.rightController.getForwardRay(this._rayLength);
  81085. }
  81086. else {
  81087. ray = this.currentVRCamera.getForwardRay(this._rayLength);
  81088. }
  81089. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  81090. // Moving the gazeTracker on the mesh face targetted
  81091. if (hit && hit.pickedPoint) {
  81092. if (this._displayGaze) {
  81093. var multiplier = 1;
  81094. this._gazeTracker.isVisible = true;
  81095. if (this._isActionableMesh) {
  81096. multiplier = 3;
  81097. }
  81098. this._gazeTracker.scaling.x = hit.distance * multiplier;
  81099. this._gazeTracker.scaling.y = hit.distance * multiplier;
  81100. this._gazeTracker.scaling.z = hit.distance * multiplier;
  81101. var pickNormal = hit.getNormal();
  81102. // To avoid z-fighting
  81103. var deltaFighting = 0.002;
  81104. if (pickNormal) {
  81105. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  81106. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  81107. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._gazeTracker.rotation);
  81108. }
  81109. this._gazeTracker.position.copyFrom(hit.pickedPoint);
  81110. if (this._gazeTracker.position.x < 0) {
  81111. this._gazeTracker.position.x += deltaFighting;
  81112. }
  81113. else {
  81114. this._gazeTracker.position.x -= deltaFighting;
  81115. }
  81116. if (this._gazeTracker.position.y < 0) {
  81117. this._gazeTracker.position.y += deltaFighting;
  81118. }
  81119. else {
  81120. this._gazeTracker.position.y -= deltaFighting;
  81121. }
  81122. if (this._gazeTracker.position.z < 0) {
  81123. this._gazeTracker.position.z += deltaFighting;
  81124. }
  81125. else {
  81126. this._gazeTracker.position.z -= deltaFighting;
  81127. }
  81128. }
  81129. // Changing the size of the laser pointer based on the distance from the targetted point
  81130. if (this._rightLaserPointer && this._rightLaserPointer.isVisible) {
  81131. this._rightLaserPointer.scaling.y = hit.distance;
  81132. this._rightLaserPointer.position.z = -hit.distance / 2;
  81133. }
  81134. if (this._leftLaserPointer && this._leftLaserPointer.isVisible) {
  81135. this._leftLaserPointer.scaling.y = hit.distance;
  81136. this._leftLaserPointer.position.z = -hit.distance / 2;
  81137. }
  81138. }
  81139. else {
  81140. this._gazeTracker.isVisible = false;
  81141. }
  81142. if (hit && hit.pickedMesh) {
  81143. this._currentHit = hit;
  81144. if (this._pointerDownOnMeshAsked) {
  81145. this._scene.simulatePointerMove(this._currentHit);
  81146. }
  81147. // The object selected is the floor, we're in a teleportation scenario
  81148. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  81149. // Moving the teleportation area to this targetted point
  81150. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  81151. if (this._currentMeshSelected && !this._isTeleportationFloor(this._currentMeshSelected)) {
  81152. this._notifySelectedMeshUnselected();
  81153. }
  81154. this._currentMeshSelected = null;
  81155. this._moveTeleportationSelectorTo(hit);
  81156. return;
  81157. }
  81158. // If not, we're in a selection scenario
  81159. this._hideTeleportationTarget();
  81160. this._teleportationAllowed = false;
  81161. if (hit.pickedMesh !== this._currentMeshSelected) {
  81162. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  81163. this.onNewMeshPicked.notifyObservers(hit);
  81164. this._currentMeshSelected = hit.pickedMesh;
  81165. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  81166. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  81167. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  81168. this._isActionableMesh = true;
  81169. }
  81170. else {
  81171. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81172. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81173. this._isActionableMesh = false;
  81174. }
  81175. try {
  81176. this.onNewMeshSelected.notifyObservers(this._currentMeshSelected);
  81177. }
  81178. catch (err) {
  81179. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  81180. }
  81181. }
  81182. else {
  81183. this._notifySelectedMeshUnselected();
  81184. this._currentMeshSelected = null;
  81185. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81186. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81187. }
  81188. }
  81189. }
  81190. else {
  81191. this._currentHit = null;
  81192. this._notifySelectedMeshUnselected();
  81193. this._currentMeshSelected = null;
  81194. this._teleportationAllowed = false;
  81195. this._hideTeleportationTarget();
  81196. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81197. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  81198. }
  81199. };
  81200. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function () {
  81201. if (this._currentMeshSelected) {
  81202. this.onSelectedMeshUnselected.notifyObservers(this._currentMeshSelected);
  81203. }
  81204. };
  81205. /**
  81206. * Sets the color of the laser ray from the vr controllers.
  81207. * @param color new color for the ray.
  81208. */
  81209. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  81210. if (this._leftLaserPointer && this._leftLaserPointer.material) {
  81211. this._leftLaserPointer.material.emissiveColor = color;
  81212. }
  81213. if (this._rightLaserPointer && this._rightLaserPointer.material) {
  81214. this._rightLaserPointer.material.emissiveColor = color;
  81215. }
  81216. };
  81217. /**
  81218. * Sets the color of the ray from the vr headsets gaze.
  81219. * @param color new color for the ray.
  81220. */
  81221. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  81222. if (this._gazeTracker.material) {
  81223. this._gazeTracker.material.emissiveColor = color;
  81224. }
  81225. };
  81226. /**
  81227. * Exits VR and disposes of the vr experience helper
  81228. */
  81229. VRExperienceHelper.prototype.dispose = function () {
  81230. if (this.isInVRMode) {
  81231. this.exitVR();
  81232. }
  81233. if (this._postProcessMove) {
  81234. this._postProcessMove.dispose();
  81235. }
  81236. if (this._webVRCamera) {
  81237. this._webVRCamera.dispose();
  81238. }
  81239. if (this._vrDeviceOrientationCamera) {
  81240. this._vrDeviceOrientationCamera.dispose();
  81241. }
  81242. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  81243. document.body.removeChild(this._btnVR);
  81244. }
  81245. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  81246. this._deviceOrientationCamera.dispose();
  81247. }
  81248. if (this._gazeTracker) {
  81249. this._gazeTracker.dispose();
  81250. }
  81251. if (this._teleportationTarget) {
  81252. this._teleportationTarget.dispose();
  81253. }
  81254. this._floorMeshesCollection = [];
  81255. document.removeEventListener("keydown", this._onKeyDown);
  81256. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81257. window.removeEventListener("resize", this._onResize);
  81258. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  81259. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  81260. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  81261. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  81262. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  81263. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  81264. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  81265. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  81266. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  81267. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  81268. this._scene.unregisterBeforeRender(this.beforeRender);
  81269. };
  81270. /**
  81271. * Gets the name of the VRExperienceHelper class
  81272. * @returns "VRExperienceHelper"
  81273. */
  81274. VRExperienceHelper.prototype.getClassName = function () {
  81275. return "VRExperienceHelper";
  81276. };
  81277. return VRExperienceHelper;
  81278. }());
  81279. BABYLON.VRExperienceHelper = VRExperienceHelper;
  81280. })(BABYLON || (BABYLON = {}));
  81281. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  81282. // Mainly based on these 2 articles :
  81283. // 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
  81284. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  81285. var BABYLON;
  81286. (function (BABYLON) {
  81287. var JoystickAxis;
  81288. (function (JoystickAxis) {
  81289. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  81290. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  81291. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  81292. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  81293. var VirtualJoystick = /** @class */ (function () {
  81294. function VirtualJoystick(leftJoystick) {
  81295. var _this = this;
  81296. if (leftJoystick) {
  81297. this._leftJoystick = true;
  81298. }
  81299. else {
  81300. this._leftJoystick = false;
  81301. }
  81302. VirtualJoystick._globalJoystickIndex++;
  81303. // By default left & right arrow keys are moving the X
  81304. // and up & down keys are moving the Y
  81305. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  81306. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  81307. this.reverseLeftRight = false;
  81308. this.reverseUpDown = false;
  81309. // collections of pointers
  81310. this._touches = new BABYLON.StringDictionary();
  81311. this.deltaPosition = BABYLON.Vector3.Zero();
  81312. this._joystickSensibility = 25;
  81313. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  81314. this._onResize = function (evt) {
  81315. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81316. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81317. if (VirtualJoystick.vjCanvas) {
  81318. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  81319. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  81320. }
  81321. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  81322. };
  81323. // injecting a canvas element on top of the canvas 3D game
  81324. if (!VirtualJoystick.vjCanvas) {
  81325. window.addEventListener("resize", this._onResize, false);
  81326. VirtualJoystick.vjCanvas = document.createElement("canvas");
  81327. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  81328. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  81329. VirtualJoystick.vjCanvas.width = window.innerWidth;
  81330. VirtualJoystick.vjCanvas.height = window.innerHeight;
  81331. VirtualJoystick.vjCanvas.style.width = "100%";
  81332. VirtualJoystick.vjCanvas.style.height = "100%";
  81333. VirtualJoystick.vjCanvas.style.position = "absolute";
  81334. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  81335. VirtualJoystick.vjCanvas.style.top = "0px";
  81336. VirtualJoystick.vjCanvas.style.left = "0px";
  81337. VirtualJoystick.vjCanvas.style.zIndex = "5";
  81338. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  81339. // Support for jQuery PEP polyfill
  81340. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  81341. var context = VirtualJoystick.vjCanvas.getContext('2d');
  81342. if (!context) {
  81343. throw new Error("Unable to create canvas for virtual joystick");
  81344. }
  81345. VirtualJoystick.vjCanvasContext = context;
  81346. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  81347. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  81348. document.body.appendChild(VirtualJoystick.vjCanvas);
  81349. }
  81350. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  81351. this.pressed = false;
  81352. // default joystick color
  81353. this._joystickColor = "cyan";
  81354. this._joystickPointerID = -1;
  81355. // current joystick position
  81356. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  81357. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  81358. // origin joystick position
  81359. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  81360. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  81361. this._onPointerDownHandlerRef = function (evt) {
  81362. _this._onPointerDown(evt);
  81363. };
  81364. this._onPointerMoveHandlerRef = function (evt) {
  81365. _this._onPointerMove(evt);
  81366. };
  81367. this._onPointerUpHandlerRef = function (evt) {
  81368. _this._onPointerUp(evt);
  81369. };
  81370. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  81371. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  81372. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  81373. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  81374. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  81375. evt.preventDefault(); // Disables system menu
  81376. }, false);
  81377. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  81378. }
  81379. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  81380. this._joystickSensibility = newJoystickSensibility;
  81381. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  81382. };
  81383. VirtualJoystick.prototype._onPointerDown = function (e) {
  81384. var positionOnScreenCondition;
  81385. e.preventDefault();
  81386. if (this._leftJoystick === true) {
  81387. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  81388. }
  81389. else {
  81390. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  81391. }
  81392. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  81393. // First contact will be dedicated to the virtual joystick
  81394. this._joystickPointerID = e.pointerId;
  81395. this._joystickPointerStartPos.x = e.clientX;
  81396. this._joystickPointerStartPos.y = e.clientY;
  81397. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  81398. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  81399. this._deltaJoystickVector.x = 0;
  81400. this._deltaJoystickVector.y = 0;
  81401. this.pressed = true;
  81402. this._touches.add(e.pointerId.toString(), e);
  81403. }
  81404. else {
  81405. // You can only trigger the action buttons with a joystick declared
  81406. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  81407. this._action();
  81408. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  81409. }
  81410. }
  81411. };
  81412. VirtualJoystick.prototype._onPointerMove = function (e) {
  81413. // If the current pointer is the one associated to the joystick (first touch contact)
  81414. if (this._joystickPointerID == e.pointerId) {
  81415. this._joystickPointerPos.x = e.clientX;
  81416. this._joystickPointerPos.y = e.clientY;
  81417. this._deltaJoystickVector = this._joystickPointerPos.clone();
  81418. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  81419. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  81420. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  81421. switch (this._axisTargetedByLeftAndRight) {
  81422. case JoystickAxis.X:
  81423. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  81424. break;
  81425. case JoystickAxis.Y:
  81426. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  81427. break;
  81428. case JoystickAxis.Z:
  81429. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  81430. break;
  81431. }
  81432. var directionUpDown = this.reverseUpDown ? 1 : -1;
  81433. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  81434. switch (this._axisTargetedByUpAndDown) {
  81435. case JoystickAxis.X:
  81436. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  81437. break;
  81438. case JoystickAxis.Y:
  81439. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  81440. break;
  81441. case JoystickAxis.Z:
  81442. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  81443. break;
  81444. }
  81445. }
  81446. else {
  81447. var data = this._touches.get(e.pointerId.toString());
  81448. if (data) {
  81449. data.x = e.clientX;
  81450. data.y = e.clientY;
  81451. }
  81452. }
  81453. };
  81454. VirtualJoystick.prototype._onPointerUp = function (e) {
  81455. if (this._joystickPointerID == e.pointerId) {
  81456. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  81457. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  81458. this._joystickPointerID = -1;
  81459. this.pressed = false;
  81460. }
  81461. else {
  81462. var touch = this._touches.get(e.pointerId.toString());
  81463. if (touch) {
  81464. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  81465. }
  81466. }
  81467. this._deltaJoystickVector.x = 0;
  81468. this._deltaJoystickVector.y = 0;
  81469. this._touches.remove(e.pointerId.toString());
  81470. };
  81471. /**
  81472. * Change the color of the virtual joystick
  81473. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  81474. */
  81475. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  81476. this._joystickColor = newColor;
  81477. };
  81478. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  81479. this._action = action;
  81480. };
  81481. // Define which axis you'd like to control for left & right
  81482. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  81483. switch (axis) {
  81484. case JoystickAxis.X:
  81485. case JoystickAxis.Y:
  81486. case JoystickAxis.Z:
  81487. this._axisTargetedByLeftAndRight = axis;
  81488. break;
  81489. default:
  81490. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  81491. break;
  81492. }
  81493. };
  81494. // Define which axis you'd like to control for up & down
  81495. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  81496. switch (axis) {
  81497. case JoystickAxis.X:
  81498. case JoystickAxis.Y:
  81499. case JoystickAxis.Z:
  81500. this._axisTargetedByUpAndDown = axis;
  81501. break;
  81502. default:
  81503. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  81504. break;
  81505. }
  81506. };
  81507. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  81508. var _this = this;
  81509. if (this.pressed) {
  81510. this._touches.forEach(function (key, touch) {
  81511. if (touch.pointerId === _this._joystickPointerID) {
  81512. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  81513. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  81514. VirtualJoystick.vjCanvasContext.beginPath();
  81515. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  81516. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81517. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  81518. VirtualJoystick.vjCanvasContext.stroke();
  81519. VirtualJoystick.vjCanvasContext.closePath();
  81520. VirtualJoystick.vjCanvasContext.beginPath();
  81521. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81522. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  81523. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  81524. VirtualJoystick.vjCanvasContext.stroke();
  81525. VirtualJoystick.vjCanvasContext.closePath();
  81526. VirtualJoystick.vjCanvasContext.beginPath();
  81527. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  81528. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  81529. VirtualJoystick.vjCanvasContext.stroke();
  81530. VirtualJoystick.vjCanvasContext.closePath();
  81531. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  81532. }
  81533. else {
  81534. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  81535. VirtualJoystick.vjCanvasContext.beginPath();
  81536. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  81537. VirtualJoystick.vjCanvasContext.beginPath();
  81538. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  81539. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  81540. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  81541. VirtualJoystick.vjCanvasContext.stroke();
  81542. VirtualJoystick.vjCanvasContext.closePath();
  81543. touch.prevX = touch.x;
  81544. touch.prevY = touch.y;
  81545. }
  81546. ;
  81547. });
  81548. }
  81549. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  81550. };
  81551. VirtualJoystick.prototype.releaseCanvas = function () {
  81552. if (VirtualJoystick.vjCanvas) {
  81553. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  81554. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  81555. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  81556. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  81557. window.removeEventListener("resize", this._onResize);
  81558. document.body.removeChild(VirtualJoystick.vjCanvas);
  81559. VirtualJoystick.vjCanvas = null;
  81560. }
  81561. };
  81562. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  81563. VirtualJoystick._globalJoystickIndex = 0;
  81564. return VirtualJoystick;
  81565. }());
  81566. BABYLON.VirtualJoystick = VirtualJoystick;
  81567. })(BABYLON || (BABYLON = {}));
  81568. //# sourceMappingURL=babylon.virtualJoystick.js.map
  81569. var BABYLON;
  81570. (function (BABYLON) {
  81571. // We're mainly based on the logic defined into the FreeCamera code
  81572. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  81573. __extends(VirtualJoysticksCamera, _super);
  81574. function VirtualJoysticksCamera(name, position, scene) {
  81575. var _this = _super.call(this, name, position, scene) || this;
  81576. _this.inputs.addVirtualJoystick();
  81577. return _this;
  81578. }
  81579. VirtualJoysticksCamera.prototype.getClassName = function () {
  81580. return "VirtualJoysticksCamera";
  81581. };
  81582. return VirtualJoysticksCamera;
  81583. }(BABYLON.FreeCamera));
  81584. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  81585. })(BABYLON || (BABYLON = {}));
  81586. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  81587. var BABYLON;
  81588. (function (BABYLON) {
  81589. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  81590. function FreeCameraVirtualJoystickInput() {
  81591. }
  81592. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  81593. return this._leftjoystick;
  81594. };
  81595. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  81596. return this._rightjoystick;
  81597. };
  81598. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  81599. if (this._leftjoystick) {
  81600. var camera = this.camera;
  81601. var speed = camera._computeLocalCameraSpeed() * 50;
  81602. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  81603. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  81604. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  81605. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  81606. if (!this._leftjoystick.pressed) {
  81607. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  81608. }
  81609. if (!this._rightjoystick.pressed) {
  81610. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  81611. }
  81612. }
  81613. };
  81614. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  81615. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  81616. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  81617. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  81618. this._leftjoystick.setJoystickSensibility(0.15);
  81619. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  81620. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  81621. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  81622. this._rightjoystick.reverseUpDown = true;
  81623. this._rightjoystick.setJoystickSensibility(0.05);
  81624. this._rightjoystick.setJoystickColor("yellow");
  81625. };
  81626. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  81627. this._leftjoystick.releaseCanvas();
  81628. this._rightjoystick.releaseCanvas();
  81629. };
  81630. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  81631. return "FreeCameraVirtualJoystickInput";
  81632. };
  81633. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  81634. return "virtualJoystick";
  81635. };
  81636. return FreeCameraVirtualJoystickInput;
  81637. }());
  81638. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  81639. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  81640. })(BABYLON || (BABYLON = {}));
  81641. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  81642. var BABYLON;
  81643. (function (BABYLON) {
  81644. var SimplificationSettings = /** @class */ (function () {
  81645. function SimplificationSettings(quality, distance, optimizeMesh) {
  81646. this.quality = quality;
  81647. this.distance = distance;
  81648. this.optimizeMesh = optimizeMesh;
  81649. }
  81650. return SimplificationSettings;
  81651. }());
  81652. BABYLON.SimplificationSettings = SimplificationSettings;
  81653. var SimplificationQueue = /** @class */ (function () {
  81654. function SimplificationQueue() {
  81655. this.running = false;
  81656. this._simplificationArray = [];
  81657. }
  81658. SimplificationQueue.prototype.addTask = function (task) {
  81659. this._simplificationArray.push(task);
  81660. };
  81661. SimplificationQueue.prototype.executeNext = function () {
  81662. var task = this._simplificationArray.pop();
  81663. if (task) {
  81664. this.running = true;
  81665. this.runSimplification(task);
  81666. }
  81667. else {
  81668. this.running = false;
  81669. }
  81670. };
  81671. SimplificationQueue.prototype.runSimplification = function (task) {
  81672. var _this = this;
  81673. if (task.parallelProcessing) {
  81674. //parallel simplifier
  81675. task.settings.forEach(function (setting) {
  81676. var simplifier = _this.getSimplifier(task);
  81677. simplifier.simplify(setting, function (newMesh) {
  81678. task.mesh.addLODLevel(setting.distance, newMesh);
  81679. newMesh.isVisible = true;
  81680. //check if it is the last
  81681. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  81682. //all done, run the success callback.
  81683. task.successCallback();
  81684. }
  81685. _this.executeNext();
  81686. });
  81687. });
  81688. }
  81689. else {
  81690. //single simplifier.
  81691. var simplifier = this.getSimplifier(task);
  81692. var runDecimation = function (setting, callback) {
  81693. simplifier.simplify(setting, function (newMesh) {
  81694. task.mesh.addLODLevel(setting.distance, newMesh);
  81695. newMesh.isVisible = true;
  81696. //run the next quality level
  81697. callback();
  81698. });
  81699. };
  81700. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  81701. runDecimation(task.settings[loop.index], function () {
  81702. loop.executeNext();
  81703. });
  81704. }, function () {
  81705. //execution ended, run the success callback.
  81706. if (task.successCallback) {
  81707. task.successCallback();
  81708. }
  81709. _this.executeNext();
  81710. });
  81711. }
  81712. };
  81713. SimplificationQueue.prototype.getSimplifier = function (task) {
  81714. switch (task.simplificationType) {
  81715. case SimplificationType.QUADRATIC:
  81716. default:
  81717. return new QuadraticErrorSimplification(task.mesh);
  81718. }
  81719. };
  81720. return SimplificationQueue;
  81721. }());
  81722. BABYLON.SimplificationQueue = SimplificationQueue;
  81723. /**
  81724. * The implemented types of simplification.
  81725. * At the moment only Quadratic Error Decimation is implemented.
  81726. */
  81727. var SimplificationType;
  81728. (function (SimplificationType) {
  81729. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  81730. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  81731. var DecimationTriangle = /** @class */ (function () {
  81732. function DecimationTriangle(vertices) {
  81733. this.vertices = vertices;
  81734. this.error = new Array(4);
  81735. this.deleted = false;
  81736. this.isDirty = false;
  81737. this.deletePending = false;
  81738. this.borderFactor = 0;
  81739. }
  81740. return DecimationTriangle;
  81741. }());
  81742. BABYLON.DecimationTriangle = DecimationTriangle;
  81743. var DecimationVertex = /** @class */ (function () {
  81744. function DecimationVertex(position, id) {
  81745. this.position = position;
  81746. this.id = id;
  81747. this.isBorder = true;
  81748. this.q = new QuadraticMatrix();
  81749. this.triangleCount = 0;
  81750. this.triangleStart = 0;
  81751. this.originalOffsets = [];
  81752. }
  81753. DecimationVertex.prototype.updatePosition = function (newPosition) {
  81754. this.position.copyFrom(newPosition);
  81755. };
  81756. return DecimationVertex;
  81757. }());
  81758. BABYLON.DecimationVertex = DecimationVertex;
  81759. var QuadraticMatrix = /** @class */ (function () {
  81760. function QuadraticMatrix(data) {
  81761. this.data = new Array(10);
  81762. for (var i = 0; i < 10; ++i) {
  81763. if (data && data[i]) {
  81764. this.data[i] = data[i];
  81765. }
  81766. else {
  81767. this.data[i] = 0;
  81768. }
  81769. }
  81770. }
  81771. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  81772. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  81773. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  81774. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  81775. return det;
  81776. };
  81777. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  81778. for (var i = 0; i < 10; ++i) {
  81779. this.data[i] += matrix.data[i];
  81780. }
  81781. };
  81782. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  81783. for (var i = 0; i < 10; ++i) {
  81784. this.data[i] += data[i];
  81785. }
  81786. };
  81787. QuadraticMatrix.prototype.add = function (matrix) {
  81788. var m = new QuadraticMatrix();
  81789. for (var i = 0; i < 10; ++i) {
  81790. m.data[i] = this.data[i] + matrix.data[i];
  81791. }
  81792. return m;
  81793. };
  81794. QuadraticMatrix.FromData = function (a, b, c, d) {
  81795. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  81796. };
  81797. //returning an array to avoid garbage collection
  81798. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  81799. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  81800. };
  81801. return QuadraticMatrix;
  81802. }());
  81803. BABYLON.QuadraticMatrix = QuadraticMatrix;
  81804. var Reference = /** @class */ (function () {
  81805. function Reference(vertexId, triangleId) {
  81806. this.vertexId = vertexId;
  81807. this.triangleId = triangleId;
  81808. }
  81809. return Reference;
  81810. }());
  81811. BABYLON.Reference = Reference;
  81812. /**
  81813. * An implementation of the Quadratic Error simplification algorithm.
  81814. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  81815. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  81816. * @author RaananW
  81817. */
  81818. var QuadraticErrorSimplification = /** @class */ (function () {
  81819. function QuadraticErrorSimplification(_mesh) {
  81820. this._mesh = _mesh;
  81821. this.syncIterations = 5000;
  81822. this.aggressiveness = 7;
  81823. this.decimationIterations = 100;
  81824. this.boundingBoxEpsilon = BABYLON.Epsilon;
  81825. }
  81826. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  81827. var _this = this;
  81828. this.initDecimatedMesh();
  81829. //iterating through the submeshes array, one after the other.
  81830. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  81831. _this.initWithMesh(loop.index, function () {
  81832. _this.runDecimation(settings, loop.index, function () {
  81833. loop.executeNext();
  81834. });
  81835. }, settings.optimizeMesh);
  81836. }, function () {
  81837. setTimeout(function () {
  81838. successCallback(_this._reconstructedMesh);
  81839. }, 0);
  81840. });
  81841. };
  81842. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  81843. var _this = this;
  81844. var targetCount = ~~(this.triangles.length * settings.quality);
  81845. var deletedTriangles = 0;
  81846. var triangleCount = this.triangles.length;
  81847. var iterationFunction = function (iteration, callback) {
  81848. setTimeout(function () {
  81849. if (iteration % 5 === 0) {
  81850. _this.updateMesh(iteration === 0);
  81851. }
  81852. for (var i = 0; i < _this.triangles.length; ++i) {
  81853. _this.triangles[i].isDirty = false;
  81854. }
  81855. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  81856. var trianglesIterator = function (i) {
  81857. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  81858. var t = _this.triangles[tIdx];
  81859. if (!t)
  81860. return;
  81861. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  81862. return;
  81863. }
  81864. for (var j = 0; j < 3; ++j) {
  81865. if (t.error[j] < threshold) {
  81866. var deleted0 = [];
  81867. var deleted1 = [];
  81868. var v0 = t.vertices[j];
  81869. var v1 = t.vertices[(j + 1) % 3];
  81870. if (v0.isBorder || v1.isBorder)
  81871. continue;
  81872. var p = BABYLON.Vector3.Zero();
  81873. var n = BABYLON.Vector3.Zero();
  81874. var uv = BABYLON.Vector2.Zero();
  81875. var color = new BABYLON.Color4(0, 0, 0, 1);
  81876. _this.calculateError(v0, v1, p, n, uv, color);
  81877. var delTr = new Array();
  81878. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  81879. continue;
  81880. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  81881. continue;
  81882. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  81883. continue;
  81884. var uniqueArray = new Array();
  81885. delTr.forEach(function (deletedT) {
  81886. if (uniqueArray.indexOf(deletedT) === -1) {
  81887. deletedT.deletePending = true;
  81888. uniqueArray.push(deletedT);
  81889. }
  81890. });
  81891. if (uniqueArray.length % 2 !== 0) {
  81892. continue;
  81893. }
  81894. v0.q = v1.q.add(v0.q);
  81895. v0.updatePosition(p);
  81896. var tStart = _this.references.length;
  81897. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  81898. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  81899. var tCount = _this.references.length - tStart;
  81900. if (tCount <= v0.triangleCount) {
  81901. if (tCount) {
  81902. for (var c = 0; c < tCount; c++) {
  81903. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  81904. }
  81905. }
  81906. }
  81907. else {
  81908. v0.triangleStart = tStart;
  81909. }
  81910. v0.triangleCount = tCount;
  81911. break;
  81912. }
  81913. }
  81914. };
  81915. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  81916. }, 0);
  81917. };
  81918. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  81919. if (triangleCount - deletedTriangles <= targetCount)
  81920. loop.breakLoop();
  81921. else {
  81922. iterationFunction(loop.index, function () {
  81923. loop.executeNext();
  81924. });
  81925. }
  81926. }, function () {
  81927. setTimeout(function () {
  81928. //reconstruct this part of the mesh
  81929. _this.reconstructMesh(submeshIndex);
  81930. successCallback();
  81931. }, 0);
  81932. });
  81933. };
  81934. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  81935. var _this = this;
  81936. this.vertices = [];
  81937. this.triangles = [];
  81938. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  81939. var indices = this._mesh.getIndices();
  81940. var submesh = this._mesh.subMeshes[submeshIndex];
  81941. var findInVertices = function (positionToSearch) {
  81942. if (optimizeMesh) {
  81943. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  81944. if (_this.vertices[ii].position.equals(positionToSearch)) {
  81945. return _this.vertices[ii];
  81946. }
  81947. }
  81948. }
  81949. return null;
  81950. };
  81951. var vertexReferences = [];
  81952. var vertexInit = function (i) {
  81953. if (!positionData) {
  81954. return;
  81955. }
  81956. var offset = i + submesh.verticesStart;
  81957. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  81958. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  81959. vertex.originalOffsets.push(offset);
  81960. if (vertex.id === _this.vertices.length) {
  81961. _this.vertices.push(vertex);
  81962. }
  81963. vertexReferences.push(vertex.id);
  81964. };
  81965. //var totalVertices = mesh.getTotalVertices();
  81966. var totalVertices = submesh.verticesCount;
  81967. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  81968. var indicesInit = function (i) {
  81969. if (!indices) {
  81970. return;
  81971. }
  81972. var offset = (submesh.indexStart / 3) + i;
  81973. var pos = (offset * 3);
  81974. var i0 = indices[pos + 0];
  81975. var i1 = indices[pos + 1];
  81976. var i2 = indices[pos + 2];
  81977. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  81978. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  81979. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  81980. var triangle = new DecimationTriangle([v0, v1, v2]);
  81981. triangle.originalOffset = pos;
  81982. _this.triangles.push(triangle);
  81983. };
  81984. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  81985. _this.init(callback);
  81986. });
  81987. });
  81988. };
  81989. QuadraticErrorSimplification.prototype.init = function (callback) {
  81990. var _this = this;
  81991. var triangleInit1 = function (i) {
  81992. var t = _this.triangles[i];
  81993. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  81994. for (var j = 0; j < 3; j++) {
  81995. 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))));
  81996. }
  81997. };
  81998. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  81999. var triangleInit2 = function (i) {
  82000. var t = _this.triangles[i];
  82001. for (var j = 0; j < 3; ++j) {
  82002. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  82003. }
  82004. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82005. };
  82006. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  82007. callback();
  82008. });
  82009. });
  82010. };
  82011. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  82012. var newTriangles = [];
  82013. var i;
  82014. for (i = 0; i < this.vertices.length; ++i) {
  82015. this.vertices[i].triangleCount = 0;
  82016. }
  82017. var t;
  82018. var j;
  82019. for (i = 0; i < this.triangles.length; ++i) {
  82020. if (!this.triangles[i].deleted) {
  82021. t = this.triangles[i];
  82022. for (j = 0; j < 3; ++j) {
  82023. t.vertices[j].triangleCount = 1;
  82024. }
  82025. newTriangles.push(t);
  82026. }
  82027. }
  82028. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  82029. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  82030. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  82031. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  82032. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  82033. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  82034. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  82035. var vertexCount = 0;
  82036. for (i = 0; i < this.vertices.length; ++i) {
  82037. var vertex = this.vertices[i];
  82038. vertex.id = vertexCount;
  82039. if (vertex.triangleCount) {
  82040. vertex.originalOffsets.forEach(function (originalOffset) {
  82041. if (!normalData) {
  82042. return;
  82043. }
  82044. newPositionData.push(vertex.position.x);
  82045. newPositionData.push(vertex.position.y);
  82046. newPositionData.push(vertex.position.z);
  82047. newNormalData.push(normalData[originalOffset * 3]);
  82048. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  82049. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  82050. if (uvs && uvs.length) {
  82051. newUVsData.push(uvs[(originalOffset * 2)]);
  82052. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  82053. }
  82054. else if (colorsData && colorsData.length) {
  82055. newColorsData.push(colorsData[(originalOffset * 4)]);
  82056. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  82057. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  82058. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  82059. }
  82060. ++vertexCount;
  82061. });
  82062. }
  82063. }
  82064. var startingIndex = this._reconstructedMesh.getTotalIndices();
  82065. var startingVertex = this._reconstructedMesh.getTotalVertices();
  82066. var submeshesArray = this._reconstructedMesh.subMeshes;
  82067. this._reconstructedMesh.subMeshes = [];
  82068. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  82069. var originalIndices = this._mesh.getIndices();
  82070. for (i = 0; i < newTriangles.length; ++i) {
  82071. t = newTriangles[i]; //now get the new referencing point for each vertex
  82072. [0, 1, 2].forEach(function (idx) {
  82073. var id = originalIndices[t.originalOffset + idx];
  82074. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  82075. if (offset < 0)
  82076. offset = 0;
  82077. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  82078. });
  82079. }
  82080. //overwriting the old vertex buffers and indices.
  82081. this._reconstructedMesh.setIndices(newIndicesArray);
  82082. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  82083. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  82084. if (newUVsData.length > 0)
  82085. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  82086. if (newColorsData.length > 0)
  82087. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  82088. //create submesh
  82089. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  82090. if (submeshIndex > 0) {
  82091. this._reconstructedMesh.subMeshes = [];
  82092. submeshesArray.forEach(function (submesh) {
  82093. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  82094. });
  82095. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  82096. }
  82097. };
  82098. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  82099. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  82100. this._reconstructedMesh.material = this._mesh.material;
  82101. this._reconstructedMesh.parent = this._mesh.parent;
  82102. this._reconstructedMesh.isVisible = false;
  82103. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  82104. };
  82105. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  82106. for (var i = 0; i < vertex1.triangleCount; ++i) {
  82107. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  82108. if (t.deleted)
  82109. continue;
  82110. var s = this.references[vertex1.triangleStart + i].vertexId;
  82111. var v1 = t.vertices[(s + 1) % 3];
  82112. var v2 = t.vertices[(s + 2) % 3];
  82113. if ((v1 === vertex2 || v2 === vertex2)) {
  82114. deletedArray[i] = true;
  82115. delTr.push(t);
  82116. continue;
  82117. }
  82118. var d1 = v1.position.subtract(point);
  82119. d1 = d1.normalize();
  82120. var d2 = v2.position.subtract(point);
  82121. d2 = d2.normalize();
  82122. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  82123. return true;
  82124. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  82125. deletedArray[i] = false;
  82126. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  82127. return true;
  82128. }
  82129. return false;
  82130. };
  82131. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  82132. var newDeleted = deletedTriangles;
  82133. for (var i = 0; i < vertex.triangleCount; ++i) {
  82134. var ref = this.references[vertex.triangleStart + i];
  82135. var t = this.triangles[ref.triangleId];
  82136. if (t.deleted)
  82137. continue;
  82138. if (deletedArray[i] && t.deletePending) {
  82139. t.deleted = true;
  82140. newDeleted++;
  82141. continue;
  82142. }
  82143. t.vertices[ref.vertexId] = origVertex;
  82144. t.isDirty = true;
  82145. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  82146. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  82147. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  82148. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  82149. this.references.push(ref);
  82150. }
  82151. return newDeleted;
  82152. };
  82153. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  82154. for (var i = 0; i < this.vertices.length; ++i) {
  82155. var vCount = [];
  82156. var vId = [];
  82157. var v = this.vertices[i];
  82158. var j;
  82159. for (j = 0; j < v.triangleCount; ++j) {
  82160. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  82161. for (var ii = 0; ii < 3; ii++) {
  82162. var ofs = 0;
  82163. var vv = triangle.vertices[ii];
  82164. while (ofs < vCount.length) {
  82165. if (vId[ofs] === vv.id)
  82166. break;
  82167. ++ofs;
  82168. }
  82169. if (ofs === vCount.length) {
  82170. vCount.push(1);
  82171. vId.push(vv.id);
  82172. }
  82173. else {
  82174. vCount[ofs]++;
  82175. }
  82176. }
  82177. }
  82178. for (j = 0; j < vCount.length; ++j) {
  82179. if (vCount[j] === 1) {
  82180. this.vertices[vId[j]].isBorder = true;
  82181. }
  82182. else {
  82183. this.vertices[vId[j]].isBorder = false;
  82184. }
  82185. }
  82186. }
  82187. };
  82188. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  82189. if (identifyBorders === void 0) { identifyBorders = false; }
  82190. var i;
  82191. if (!identifyBorders) {
  82192. var newTrianglesVector = [];
  82193. for (i = 0; i < this.triangles.length; ++i) {
  82194. if (!this.triangles[i].deleted) {
  82195. newTrianglesVector.push(this.triangles[i]);
  82196. }
  82197. }
  82198. this.triangles = newTrianglesVector;
  82199. }
  82200. for (i = 0; i < this.vertices.length; ++i) {
  82201. this.vertices[i].triangleCount = 0;
  82202. this.vertices[i].triangleStart = 0;
  82203. }
  82204. var t;
  82205. var j;
  82206. var v;
  82207. for (i = 0; i < this.triangles.length; ++i) {
  82208. t = this.triangles[i];
  82209. for (j = 0; j < 3; ++j) {
  82210. v = t.vertices[j];
  82211. v.triangleCount++;
  82212. }
  82213. }
  82214. var tStart = 0;
  82215. for (i = 0; i < this.vertices.length; ++i) {
  82216. this.vertices[i].triangleStart = tStart;
  82217. tStart += this.vertices[i].triangleCount;
  82218. this.vertices[i].triangleCount = 0;
  82219. }
  82220. var newReferences = new Array(this.triangles.length * 3);
  82221. for (i = 0; i < this.triangles.length; ++i) {
  82222. t = this.triangles[i];
  82223. for (j = 0; j < 3; ++j) {
  82224. v = t.vertices[j];
  82225. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  82226. v.triangleCount++;
  82227. }
  82228. }
  82229. this.references = newReferences;
  82230. if (identifyBorders) {
  82231. this.identifyBorder();
  82232. }
  82233. };
  82234. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  82235. var x = point.x;
  82236. var y = point.y;
  82237. var z = point.z;
  82238. 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
  82239. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  82240. };
  82241. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  82242. var q = vertex1.q.add(vertex2.q);
  82243. var border = vertex1.isBorder && vertex2.isBorder;
  82244. var error = 0;
  82245. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  82246. if (qDet !== 0 && !border) {
  82247. if (!pointResult) {
  82248. pointResult = BABYLON.Vector3.Zero();
  82249. }
  82250. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  82251. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  82252. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  82253. error = this.vertexError(q, pointResult);
  82254. }
  82255. else {
  82256. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  82257. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  82258. var error1 = this.vertexError(q, vertex1.position);
  82259. var error2 = this.vertexError(q, vertex2.position);
  82260. var error3 = this.vertexError(q, p3);
  82261. error = Math.min(error1, error2, error3);
  82262. if (error === error1) {
  82263. if (pointResult) {
  82264. pointResult.copyFrom(vertex1.position);
  82265. }
  82266. }
  82267. else if (error === error2) {
  82268. if (pointResult) {
  82269. pointResult.copyFrom(vertex2.position);
  82270. }
  82271. }
  82272. else {
  82273. if (pointResult) {
  82274. pointResult.copyFrom(p3);
  82275. }
  82276. }
  82277. }
  82278. return error;
  82279. };
  82280. return QuadraticErrorSimplification;
  82281. }());
  82282. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  82283. })(BABYLON || (BABYLON = {}));
  82284. //# sourceMappingURL=babylon.meshSimplification.js.map
  82285. var BABYLON;
  82286. (function (BABYLON) {
  82287. var MeshLODLevel = /** @class */ (function () {
  82288. function MeshLODLevel(distance, mesh) {
  82289. this.distance = distance;
  82290. this.mesh = mesh;
  82291. }
  82292. return MeshLODLevel;
  82293. }());
  82294. BABYLON.MeshLODLevel = MeshLODLevel;
  82295. })(BABYLON || (BABYLON = {}));
  82296. //# sourceMappingURL=babylon.meshLODLevel.js.map
  82297. var BABYLON;
  82298. (function (BABYLON) {
  82299. /**
  82300. * Defines the root class used to create scene optimization to use with SceneOptimizer
  82301. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82302. */
  82303. var SceneOptimization = /** @class */ (function () {
  82304. /**
  82305. * Creates the SceneOptimization object
  82306. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82307. * @param desc defines the description associated with the optimization
  82308. */
  82309. function SceneOptimization(
  82310. /**
  82311. * Defines the priority of this optimization (0 by default which means first in the list)
  82312. */
  82313. priority) {
  82314. if (priority === void 0) { priority = 0; }
  82315. this.priority = priority;
  82316. }
  82317. /**
  82318. * Gets a string describing the action executed by the current optimization
  82319. * @returns description string
  82320. */
  82321. SceneOptimization.prototype.getDescription = function () {
  82322. return "";
  82323. };
  82324. /**
  82325. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82326. * @param scene defines the current scene where to apply this optimization
  82327. * @param optimizer defines the current optimizer
  82328. * @returns true if everything that can be done was applied
  82329. */
  82330. SceneOptimization.prototype.apply = function (scene, optimizer) {
  82331. return true;
  82332. };
  82333. ;
  82334. return SceneOptimization;
  82335. }());
  82336. BABYLON.SceneOptimization = SceneOptimization;
  82337. /**
  82338. * Defines an optimization used to reduce the size of render target textures
  82339. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82340. */
  82341. var TextureOptimization = /** @class */ (function (_super) {
  82342. __extends(TextureOptimization, _super);
  82343. /**
  82344. * Creates the TextureOptimization object
  82345. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82346. * @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
  82347. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  82348. */
  82349. function TextureOptimization(
  82350. /**
  82351. * Defines the priority of this optimization (0 by default which means first in the list)
  82352. */
  82353. priority,
  82354. /**
  82355. * 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
  82356. */
  82357. maximumSize,
  82358. /**
  82359. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  82360. */
  82361. step) {
  82362. if (priority === void 0) { priority = 0; }
  82363. if (maximumSize === void 0) { maximumSize = 1024; }
  82364. if (step === void 0) { step = 0.5; }
  82365. var _this = _super.call(this, priority) || this;
  82366. _this.priority = priority;
  82367. _this.maximumSize = maximumSize;
  82368. _this.step = step;
  82369. return _this;
  82370. }
  82371. /**
  82372. * Gets a string describing the action executed by the current optimization
  82373. * @returns description string
  82374. */
  82375. TextureOptimization.prototype.getDescription = function () {
  82376. return "Reducing render target texture size to " + this.maximumSize;
  82377. };
  82378. /**
  82379. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82380. * @param scene defines the current scene where to apply this optimization
  82381. * @param optimizer defines the current optimizer
  82382. * @returns true if everything that can be done was applied
  82383. */
  82384. TextureOptimization.prototype.apply = function (scene, optimizer) {
  82385. var allDone = true;
  82386. for (var index = 0; index < scene.textures.length; index++) {
  82387. var texture = scene.textures[index];
  82388. if (!texture.canRescale || texture.getContext) {
  82389. continue;
  82390. }
  82391. var currentSize = texture.getSize();
  82392. var maxDimension = Math.max(currentSize.width, currentSize.height);
  82393. if (maxDimension > this.maximumSize) {
  82394. texture.scale(this.step);
  82395. allDone = false;
  82396. }
  82397. }
  82398. return allDone;
  82399. };
  82400. return TextureOptimization;
  82401. }(SceneOptimization));
  82402. BABYLON.TextureOptimization = TextureOptimization;
  82403. /**
  82404. * Defines an optimization used to increase or decrease the rendering resolution
  82405. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82406. */
  82407. var HardwareScalingOptimization = /** @class */ (function (_super) {
  82408. __extends(HardwareScalingOptimization, _super);
  82409. /**
  82410. * Creates the HardwareScalingOptimization object
  82411. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82412. * @param maximumScale defines the maximum scale to use (2 by default)
  82413. * @param step defines the step to use between two passes (0.5 by default)
  82414. */
  82415. function HardwareScalingOptimization(
  82416. /**
  82417. * Defines the priority of this optimization (0 by default which means first in the list)
  82418. */
  82419. priority,
  82420. /**
  82421. * Defines the maximum scale to use (2 by default)
  82422. */
  82423. maximumScale,
  82424. /**
  82425. * Defines the step to use between two passes (0.5 by default)
  82426. */
  82427. step) {
  82428. if (priority === void 0) { priority = 0; }
  82429. if (maximumScale === void 0) { maximumScale = 2; }
  82430. if (step === void 0) { step = 0.25; }
  82431. var _this = _super.call(this, priority) || this;
  82432. _this.priority = priority;
  82433. _this.maximumScale = maximumScale;
  82434. _this.step = step;
  82435. _this._currentScale = -1;
  82436. _this._directionOffset = 1;
  82437. return _this;
  82438. }
  82439. /**
  82440. * Gets a string describing the action executed by the current optimization
  82441. * @return description string
  82442. */
  82443. HardwareScalingOptimization.prototype.getDescription = function () {
  82444. return "Setting hardware scaling level to " + this._currentScale;
  82445. };
  82446. /**
  82447. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82448. * @param scene defines the current scene where to apply this optimization
  82449. * @param optimizer defines the current optimizer
  82450. * @returns true if everything that can be done was applied
  82451. */
  82452. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  82453. if (this._currentScale === -1) {
  82454. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  82455. if (this._currentScale > this.maximumScale) {
  82456. this._directionOffset = -1;
  82457. }
  82458. }
  82459. this._currentScale += this._directionOffset * this.step;
  82460. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  82461. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  82462. };
  82463. ;
  82464. return HardwareScalingOptimization;
  82465. }(SceneOptimization));
  82466. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  82467. /**
  82468. * Defines an optimization used to remove shadows
  82469. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82470. */
  82471. var ShadowsOptimization = /** @class */ (function (_super) {
  82472. __extends(ShadowsOptimization, _super);
  82473. function ShadowsOptimization() {
  82474. return _super !== null && _super.apply(this, arguments) || this;
  82475. }
  82476. /**
  82477. * Gets a string describing the action executed by the current optimization
  82478. * @return description string
  82479. */
  82480. ShadowsOptimization.prototype.getDescription = function () {
  82481. return "Turning shadows on/off";
  82482. };
  82483. /**
  82484. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82485. * @param scene defines the current scene where to apply this optimization
  82486. * @param optimizer defines the current optimizer
  82487. * @returns true if everything that can be done was applied
  82488. */
  82489. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  82490. scene.shadowsEnabled = optimizer.isInImprovementMode;
  82491. return true;
  82492. };
  82493. ;
  82494. return ShadowsOptimization;
  82495. }(SceneOptimization));
  82496. BABYLON.ShadowsOptimization = ShadowsOptimization;
  82497. /**
  82498. * Defines an optimization used to turn post-processes off
  82499. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82500. */
  82501. var PostProcessesOptimization = /** @class */ (function (_super) {
  82502. __extends(PostProcessesOptimization, _super);
  82503. function PostProcessesOptimization() {
  82504. return _super !== null && _super.apply(this, arguments) || this;
  82505. }
  82506. /**
  82507. * Gets a string describing the action executed by the current optimization
  82508. * @return description string
  82509. */
  82510. PostProcessesOptimization.prototype.getDescription = function () {
  82511. return "Turning post-processes on/off";
  82512. };
  82513. /**
  82514. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82515. * @param scene defines the current scene where to apply this optimization
  82516. * @param optimizer defines the current optimizer
  82517. * @returns true if everything that can be done was applied
  82518. */
  82519. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  82520. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  82521. return true;
  82522. };
  82523. ;
  82524. return PostProcessesOptimization;
  82525. }(SceneOptimization));
  82526. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  82527. /**
  82528. * Defines an optimization used to turn lens flares off
  82529. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82530. */
  82531. var LensFlaresOptimization = /** @class */ (function (_super) {
  82532. __extends(LensFlaresOptimization, _super);
  82533. function LensFlaresOptimization() {
  82534. return _super !== null && _super.apply(this, arguments) || this;
  82535. }
  82536. /**
  82537. * Gets a string describing the action executed by the current optimization
  82538. * @return description string
  82539. */
  82540. LensFlaresOptimization.prototype.getDescription = function () {
  82541. return "Turning lens flares on/off";
  82542. };
  82543. /**
  82544. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82545. * @param scene defines the current scene where to apply this optimization
  82546. * @param optimizer defines the current optimizer
  82547. * @returns true if everything that can be done was applied
  82548. */
  82549. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  82550. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  82551. return true;
  82552. };
  82553. ;
  82554. return LensFlaresOptimization;
  82555. }(SceneOptimization));
  82556. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  82557. /**
  82558. * Defines an optimization based on user defined callback.
  82559. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82560. */
  82561. var CustomOptimization = /** @class */ (function (_super) {
  82562. __extends(CustomOptimization, _super);
  82563. function CustomOptimization() {
  82564. return _super !== null && _super.apply(this, arguments) || this;
  82565. }
  82566. /**
  82567. * Gets a string describing the action executed by the current optimization
  82568. * @returns description string
  82569. */
  82570. CustomOptimization.prototype.getDescription = function () {
  82571. if (this.onGetDescription) {
  82572. return this.onGetDescription();
  82573. }
  82574. return "Running user defined callback";
  82575. };
  82576. /**
  82577. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82578. * @param scene defines the current scene where to apply this optimization
  82579. * @param optimizer defines the current optimizer
  82580. * @returns true if everything that can be done was applied
  82581. */
  82582. CustomOptimization.prototype.apply = function (scene, optimizer) {
  82583. if (this.onApply) {
  82584. return this.onApply(scene, optimizer);
  82585. }
  82586. return true;
  82587. };
  82588. ;
  82589. return CustomOptimization;
  82590. }(SceneOptimization));
  82591. BABYLON.CustomOptimization = CustomOptimization;
  82592. /**
  82593. * Defines an optimization used to turn particles off
  82594. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82595. */
  82596. var ParticlesOptimization = /** @class */ (function (_super) {
  82597. __extends(ParticlesOptimization, _super);
  82598. function ParticlesOptimization() {
  82599. return _super !== null && _super.apply(this, arguments) || this;
  82600. }
  82601. /**
  82602. * Gets a string describing the action executed by the current optimization
  82603. * @return description string
  82604. */
  82605. ParticlesOptimization.prototype.getDescription = function () {
  82606. return "Turning particles on/off";
  82607. };
  82608. /**
  82609. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82610. * @param scene defines the current scene where to apply this optimization
  82611. * @param optimizer defines the current optimizer
  82612. * @returns true if everything that can be done was applied
  82613. */
  82614. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  82615. scene.particlesEnabled = optimizer.isInImprovementMode;
  82616. return true;
  82617. };
  82618. ;
  82619. return ParticlesOptimization;
  82620. }(SceneOptimization));
  82621. BABYLON.ParticlesOptimization = ParticlesOptimization;
  82622. /**
  82623. * Defines an optimization used to turn render targets off
  82624. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82625. */
  82626. var RenderTargetsOptimization = /** @class */ (function (_super) {
  82627. __extends(RenderTargetsOptimization, _super);
  82628. function RenderTargetsOptimization() {
  82629. return _super !== null && _super.apply(this, arguments) || this;
  82630. }
  82631. /**
  82632. * Gets a string describing the action executed by the current optimization
  82633. * @return description string
  82634. */
  82635. RenderTargetsOptimization.prototype.getDescription = function () {
  82636. return "Turning render targets off";
  82637. };
  82638. /**
  82639. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82640. * @param scene defines the current scene where to apply this optimization
  82641. * @param optimizer defines the current optimizer
  82642. * @returns true if everything that can be done was applied
  82643. */
  82644. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  82645. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  82646. return true;
  82647. };
  82648. ;
  82649. return RenderTargetsOptimization;
  82650. }(SceneOptimization));
  82651. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  82652. /**
  82653. * Defines an optimization used to merge meshes with compatible materials
  82654. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82655. */
  82656. var MergeMeshesOptimization = /** @class */ (function (_super) {
  82657. __extends(MergeMeshesOptimization, _super);
  82658. function MergeMeshesOptimization() {
  82659. var _this = _super !== null && _super.apply(this, arguments) || this;
  82660. _this._canBeMerged = function (abstractMesh) {
  82661. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  82662. return false;
  82663. }
  82664. var mesh = abstractMesh;
  82665. if (!mesh.isVisible || !mesh.isEnabled()) {
  82666. return false;
  82667. }
  82668. if (mesh.instances.length > 0) {
  82669. return false;
  82670. }
  82671. if (mesh.skeleton || mesh.hasLODLevels) {
  82672. return false;
  82673. }
  82674. if (mesh.parent) {
  82675. return false;
  82676. }
  82677. return true;
  82678. };
  82679. return _this;
  82680. }
  82681. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  82682. /**
  82683. * Gets or sets a boolean which defines if optimization octree has to be updated
  82684. */
  82685. get: function () {
  82686. return MergeMeshesOptimization._UpdateSelectionTree;
  82687. },
  82688. /**
  82689. * Gets or sets a boolean which defines if optimization octree has to be updated
  82690. */
  82691. set: function (value) {
  82692. MergeMeshesOptimization._UpdateSelectionTree = value;
  82693. },
  82694. enumerable: true,
  82695. configurable: true
  82696. });
  82697. /**
  82698. * Gets a string describing the action executed by the current optimization
  82699. * @return description string
  82700. */
  82701. MergeMeshesOptimization.prototype.getDescription = function () {
  82702. return "Merging similar meshes together";
  82703. };
  82704. /**
  82705. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  82706. * @param scene defines the current scene where to apply this optimization
  82707. * @param optimizer defines the current optimizer
  82708. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  82709. * @returns true if everything that can be done was applied
  82710. */
  82711. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  82712. var globalPool = scene.meshes.slice(0);
  82713. var globalLength = globalPool.length;
  82714. for (var index = 0; index < globalLength; index++) {
  82715. var currentPool = new Array();
  82716. var current = globalPool[index];
  82717. // Checks
  82718. if (!this._canBeMerged(current)) {
  82719. continue;
  82720. }
  82721. currentPool.push(current);
  82722. // Find compatible meshes
  82723. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  82724. var otherMesh = globalPool[subIndex];
  82725. if (!this._canBeMerged(otherMesh)) {
  82726. continue;
  82727. }
  82728. if (otherMesh.material !== current.material) {
  82729. continue;
  82730. }
  82731. if (otherMesh.checkCollisions !== current.checkCollisions) {
  82732. continue;
  82733. }
  82734. currentPool.push(otherMesh);
  82735. globalLength--;
  82736. globalPool.splice(subIndex, 1);
  82737. subIndex--;
  82738. }
  82739. if (currentPool.length < 2) {
  82740. continue;
  82741. }
  82742. // Merge meshes
  82743. BABYLON.Mesh.MergeMeshes(currentPool);
  82744. }
  82745. if (updateSelectionTree != undefined) {
  82746. if (updateSelectionTree) {
  82747. scene.createOrUpdateSelectionOctree();
  82748. }
  82749. }
  82750. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  82751. scene.createOrUpdateSelectionOctree();
  82752. }
  82753. return true;
  82754. };
  82755. ;
  82756. MergeMeshesOptimization._UpdateSelectionTree = false;
  82757. return MergeMeshesOptimization;
  82758. }(SceneOptimization));
  82759. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  82760. /**
  82761. * Defines a list of options used by SceneOptimizer
  82762. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82763. */
  82764. var SceneOptimizerOptions = /** @class */ (function () {
  82765. /**
  82766. * Creates a new list of options used by SceneOptimizer
  82767. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  82768. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  82769. */
  82770. function SceneOptimizerOptions(
  82771. /**
  82772. * Defines the target frame rate to reach (60 by default)
  82773. */
  82774. targetFrameRate,
  82775. /**
  82776. * Defines the interval between two checkes (2000ms by default)
  82777. */
  82778. trackerDuration) {
  82779. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  82780. if (trackerDuration === void 0) { trackerDuration = 2000; }
  82781. this.targetFrameRate = targetFrameRate;
  82782. this.trackerDuration = trackerDuration;
  82783. /**
  82784. * Gets the list of optimizations to apply
  82785. */
  82786. this.optimizations = new Array();
  82787. }
  82788. /**
  82789. * Add a new optimization
  82790. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  82791. * @returns the current SceneOptimizerOptions
  82792. */
  82793. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  82794. this.optimizations.push(optimization);
  82795. return this;
  82796. };
  82797. /**
  82798. * Add a new custom optimization
  82799. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  82800. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  82801. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  82802. * @returns the current SceneOptimizerOptions
  82803. */
  82804. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  82805. if (priority === void 0) { priority = 0; }
  82806. var optimization = new CustomOptimization(priority);
  82807. optimization.onApply = onApply;
  82808. optimization.onGetDescription = onGetDescription;
  82809. this.optimizations.push(optimization);
  82810. return this;
  82811. };
  82812. /**
  82813. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  82814. * @param targetFrameRate defines the target frame rate (60 by default)
  82815. * @returns a SceneOptimizerOptions object
  82816. */
  82817. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  82818. var result = new SceneOptimizerOptions(targetFrameRate);
  82819. var priority = 0;
  82820. result.addOptimization(new MergeMeshesOptimization(priority));
  82821. result.addOptimization(new ShadowsOptimization(priority));
  82822. result.addOptimization(new LensFlaresOptimization(priority));
  82823. // Next priority
  82824. priority++;
  82825. result.addOptimization(new PostProcessesOptimization(priority));
  82826. result.addOptimization(new ParticlesOptimization(priority));
  82827. // Next priority
  82828. priority++;
  82829. result.addOptimization(new TextureOptimization(priority, 1024));
  82830. return result;
  82831. };
  82832. /**
  82833. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  82834. * @param targetFrameRate defines the target frame rate (60 by default)
  82835. * @returns a SceneOptimizerOptions object
  82836. */
  82837. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  82838. var result = new SceneOptimizerOptions(targetFrameRate);
  82839. var priority = 0;
  82840. result.addOptimization(new MergeMeshesOptimization(priority));
  82841. result.addOptimization(new ShadowsOptimization(priority));
  82842. result.addOptimization(new LensFlaresOptimization(priority));
  82843. // Next priority
  82844. priority++;
  82845. result.addOptimization(new PostProcessesOptimization(priority));
  82846. result.addOptimization(new ParticlesOptimization(priority));
  82847. // Next priority
  82848. priority++;
  82849. result.addOptimization(new TextureOptimization(priority, 512));
  82850. // Next priority
  82851. priority++;
  82852. result.addOptimization(new RenderTargetsOptimization(priority));
  82853. // Next priority
  82854. priority++;
  82855. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  82856. return result;
  82857. };
  82858. /**
  82859. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  82860. * @param targetFrameRate defines the target frame rate (60 by default)
  82861. * @returns a SceneOptimizerOptions object
  82862. */
  82863. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  82864. var result = new SceneOptimizerOptions(targetFrameRate);
  82865. var priority = 0;
  82866. result.addOptimization(new MergeMeshesOptimization(priority));
  82867. result.addOptimization(new ShadowsOptimization(priority));
  82868. result.addOptimization(new LensFlaresOptimization(priority));
  82869. // Next priority
  82870. priority++;
  82871. result.addOptimization(new PostProcessesOptimization(priority));
  82872. result.addOptimization(new ParticlesOptimization(priority));
  82873. // Next priority
  82874. priority++;
  82875. result.addOptimization(new TextureOptimization(priority, 256));
  82876. // Next priority
  82877. priority++;
  82878. result.addOptimization(new RenderTargetsOptimization(priority));
  82879. // Next priority
  82880. priority++;
  82881. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  82882. return result;
  82883. };
  82884. return SceneOptimizerOptions;
  82885. }());
  82886. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  82887. /**
  82888. * Class used to run optimizations in order to reach a target frame rate
  82889. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  82890. */
  82891. var SceneOptimizer = /** @class */ (function () {
  82892. /**
  82893. * Creates a new SceneOptimizer
  82894. * @param scene defines the scene to work on
  82895. * @param options defines the options to use with the SceneOptimizer
  82896. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  82897. * @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)
  82898. */
  82899. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  82900. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  82901. if (improvementMode === void 0) { improvementMode = false; }
  82902. var _this = this;
  82903. this._isRunning = false;
  82904. this._currentPriorityLevel = 0;
  82905. this._targetFrameRate = 60;
  82906. this._trackerDuration = 2000;
  82907. this._currentFrameRate = 0;
  82908. this._improvementMode = false;
  82909. /**
  82910. * Defines an observable called when the optimizer reaches the target frame rate
  82911. */
  82912. this.onSuccessObservable = new BABYLON.Observable();
  82913. /**
  82914. * Defines an observable called when the optimizer enables an optimization
  82915. */
  82916. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  82917. /**
  82918. * Defines an observable called when the optimizer is not able to reach the target frame rate
  82919. */
  82920. this.onFailureObservable = new BABYLON.Observable();
  82921. if (!options) {
  82922. this._options = new SceneOptimizerOptions();
  82923. }
  82924. else {
  82925. this._options = options;
  82926. }
  82927. if (this._options.targetFrameRate) {
  82928. this._targetFrameRate = this._options.targetFrameRate;
  82929. }
  82930. if (this._options.trackerDuration) {
  82931. this._trackerDuration = this._options.trackerDuration;
  82932. }
  82933. if (autoGeneratePriorities) {
  82934. var priority = 0;
  82935. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  82936. var optim = _a[_i];
  82937. optim.priority = priority++;
  82938. }
  82939. }
  82940. this._improvementMode = improvementMode;
  82941. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  82942. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  82943. _this._sceneDisposeObserver = null;
  82944. _this.dispose();
  82945. });
  82946. }
  82947. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  82948. /**
  82949. * Gets a boolean indicating if the optimizer is in improvement mode
  82950. */
  82951. get: function () {
  82952. return this._improvementMode;
  82953. },
  82954. enumerable: true,
  82955. configurable: true
  82956. });
  82957. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  82958. /**
  82959. * Gets the current priority level (0 at start)
  82960. */
  82961. get: function () {
  82962. return this._currentPriorityLevel;
  82963. },
  82964. enumerable: true,
  82965. configurable: true
  82966. });
  82967. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  82968. /**
  82969. * Gets the current frame rate checked by the SceneOptimizer
  82970. */
  82971. get: function () {
  82972. return this._currentFrameRate;
  82973. },
  82974. enumerable: true,
  82975. configurable: true
  82976. });
  82977. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  82978. /**
  82979. * Gets or sets the current target frame rate (60 by default)
  82980. */
  82981. get: function () {
  82982. return this._targetFrameRate;
  82983. },
  82984. /**
  82985. * Gets or sets the current target frame rate (60 by default)
  82986. */
  82987. set: function (value) {
  82988. this._targetFrameRate = value;
  82989. },
  82990. enumerable: true,
  82991. configurable: true
  82992. });
  82993. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  82994. /**
  82995. * Gets or sets the current interval between two checks (every 2000ms by default)
  82996. */
  82997. get: function () {
  82998. return this._trackerDuration;
  82999. },
  83000. /**
  83001. * Gets or sets the current interval between two checks (every 2000ms by default)
  83002. */
  83003. set: function (value) {
  83004. this._trackerDuration = value;
  83005. },
  83006. enumerable: true,
  83007. configurable: true
  83008. });
  83009. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  83010. /**
  83011. * Gets the list of active optimizations
  83012. */
  83013. get: function () {
  83014. return this._options.optimizations;
  83015. },
  83016. enumerable: true,
  83017. configurable: true
  83018. });
  83019. /**
  83020. * Stops the current optimizer
  83021. */
  83022. SceneOptimizer.prototype.stop = function () {
  83023. this._isRunning = false;
  83024. };
  83025. /**
  83026. * Reset the optimizer to initial step (current priority level = 0)
  83027. */
  83028. SceneOptimizer.prototype.reset = function () {
  83029. this._currentPriorityLevel = 0;
  83030. };
  83031. /**
  83032. * Start the optimizer. By default it will try to reach a specific framerate
  83033. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  83034. */
  83035. SceneOptimizer.prototype.start = function () {
  83036. var _this = this;
  83037. if (this._isRunning) {
  83038. return;
  83039. }
  83040. this._isRunning = true;
  83041. // Let's wait for the scene to be ready before running our check
  83042. this._scene.executeWhenReady(function () {
  83043. setTimeout(function () {
  83044. _this._checkCurrentState();
  83045. }, _this._trackerDuration);
  83046. });
  83047. };
  83048. SceneOptimizer.prototype._checkCurrentState = function () {
  83049. var _this = this;
  83050. if (!this._isRunning) {
  83051. return;
  83052. }
  83053. var scene = this._scene;
  83054. var options = this._options;
  83055. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  83056. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  83057. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  83058. this._isRunning = false;
  83059. this.onSuccessObservable.notifyObservers(this);
  83060. return;
  83061. }
  83062. // Apply current level of optimizations
  83063. var allDone = true;
  83064. var noOptimizationApplied = true;
  83065. for (var index = 0; index < options.optimizations.length; index++) {
  83066. var optimization = options.optimizations[index];
  83067. if (optimization.priority === this._currentPriorityLevel) {
  83068. noOptimizationApplied = false;
  83069. allDone = allDone && optimization.apply(scene, this);
  83070. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  83071. }
  83072. }
  83073. // If no optimization was applied, this is a failure :(
  83074. if (noOptimizationApplied) {
  83075. this._isRunning = false;
  83076. this.onFailureObservable.notifyObservers(this);
  83077. return;
  83078. }
  83079. // If all optimizations were done, move to next level
  83080. if (allDone) {
  83081. this._currentPriorityLevel++;
  83082. }
  83083. // Let's the system running for a specific amount of time before checking FPS
  83084. scene.executeWhenReady(function () {
  83085. setTimeout(function () {
  83086. _this._checkCurrentState();
  83087. }, _this._trackerDuration);
  83088. });
  83089. };
  83090. /**
  83091. * Release all resources
  83092. */
  83093. SceneOptimizer.prototype.dispose = function () {
  83094. this.stop();
  83095. this.onSuccessObservable.clear();
  83096. this.onFailureObservable.clear();
  83097. this.onNewOptimizationAppliedObservable.clear();
  83098. if (this._sceneDisposeObserver) {
  83099. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  83100. }
  83101. };
  83102. /**
  83103. * Helper function to create a SceneOptimizer with one single line of code
  83104. * @param scene defines the scene to work on
  83105. * @param options defines the options to use with the SceneOptimizer
  83106. * @param onSuccess defines a callback to call on success
  83107. * @param onFailure defines a callback to call on failure
  83108. * @returns the new SceneOptimizer object
  83109. */
  83110. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  83111. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  83112. if (onSuccess) {
  83113. optimizer.onSuccessObservable.add(function () {
  83114. onSuccess();
  83115. });
  83116. }
  83117. if (onFailure) {
  83118. optimizer.onFailureObservable.add(function () {
  83119. onFailure();
  83120. });
  83121. }
  83122. optimizer.start();
  83123. return optimizer;
  83124. };
  83125. return SceneOptimizer;
  83126. }());
  83127. BABYLON.SceneOptimizer = SceneOptimizer;
  83128. })(BABYLON || (BABYLON = {}));
  83129. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  83130. var BABYLON;
  83131. (function (BABYLON) {
  83132. var OutlineRenderer = /** @class */ (function () {
  83133. function OutlineRenderer(scene) {
  83134. this.zOffset = 1;
  83135. this._scene = scene;
  83136. }
  83137. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  83138. var _this = this;
  83139. if (useOverlay === void 0) { useOverlay = false; }
  83140. var scene = this._scene;
  83141. var engine = this._scene.getEngine();
  83142. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  83143. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  83144. return;
  83145. }
  83146. var mesh = subMesh.getRenderingMesh();
  83147. var material = subMesh.getMaterial();
  83148. if (!material || !scene.activeCamera) {
  83149. return;
  83150. }
  83151. engine.enableEffect(this._effect);
  83152. // Logarithmic depth
  83153. if (material.useLogarithmicDepth) {
  83154. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  83155. }
  83156. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  83157. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  83158. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83159. // Bones
  83160. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83161. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83162. }
  83163. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  83164. // Alpha test
  83165. if (material && material.needAlphaTesting()) {
  83166. var alphaTexture = material.getAlphaTestTexture();
  83167. if (alphaTexture) {
  83168. this._effect.setTexture("diffuseSampler", alphaTexture);
  83169. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83170. }
  83171. }
  83172. engine.setZOffset(-this.zOffset);
  83173. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  83174. engine.setZOffset(0);
  83175. };
  83176. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  83177. var defines = [];
  83178. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  83179. var mesh = subMesh.getMesh();
  83180. var material = subMesh.getMaterial();
  83181. if (material) {
  83182. // Alpha test
  83183. if (material.needAlphaTesting()) {
  83184. defines.push("#define ALPHATEST");
  83185. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83186. attribs.push(BABYLON.VertexBuffer.UVKind);
  83187. defines.push("#define UV1");
  83188. }
  83189. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83190. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83191. defines.push("#define UV2");
  83192. }
  83193. }
  83194. //Logarithmic depth
  83195. if (material.useLogarithmicDepth) {
  83196. defines.push("#define LOGARITHMICDEPTH");
  83197. }
  83198. }
  83199. // Bones
  83200. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83201. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83202. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83203. if (mesh.numBoneInfluencers > 4) {
  83204. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83205. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83206. }
  83207. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83208. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83209. }
  83210. else {
  83211. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83212. }
  83213. // Instances
  83214. if (useInstances) {
  83215. defines.push("#define INSTANCES");
  83216. attribs.push("world0");
  83217. attribs.push("world1");
  83218. attribs.push("world2");
  83219. attribs.push("world3");
  83220. }
  83221. // Get correct effect
  83222. var join = defines.join("\n");
  83223. if (this._cachedDefines !== join) {
  83224. this._cachedDefines = join;
  83225. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  83226. }
  83227. return this._effect.isReady();
  83228. };
  83229. return OutlineRenderer;
  83230. }());
  83231. BABYLON.OutlineRenderer = OutlineRenderer;
  83232. })(BABYLON || (BABYLON = {}));
  83233. //# sourceMappingURL=babylon.outlineRenderer.js.map
  83234. var BABYLON;
  83235. (function (BABYLON) {
  83236. var FaceAdjacencies = /** @class */ (function () {
  83237. function FaceAdjacencies() {
  83238. this.edges = new Array();
  83239. this.edgesConnectedCount = 0;
  83240. }
  83241. return FaceAdjacencies;
  83242. }());
  83243. var EdgesRenderer = /** @class */ (function () {
  83244. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  83245. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  83246. if (epsilon === void 0) { epsilon = 0.95; }
  83247. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  83248. this.edgesWidthScalerForOrthographic = 1000.0;
  83249. this.edgesWidthScalerForPerspective = 50.0;
  83250. this._linesPositions = new Array();
  83251. this._linesNormals = new Array();
  83252. this._linesIndices = new Array();
  83253. this._buffers = {};
  83254. this._checkVerticesInsteadOfIndices = false;
  83255. this._source = source;
  83256. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  83257. this._epsilon = epsilon;
  83258. this._prepareRessources();
  83259. this._generateEdgesLines();
  83260. }
  83261. EdgesRenderer.prototype._prepareRessources = function () {
  83262. if (this._lineShader) {
  83263. return;
  83264. }
  83265. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  83266. attributes: ["position", "normal"],
  83267. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  83268. });
  83269. this._lineShader.disableDepthWrite = true;
  83270. this._lineShader.backFaceCulling = false;
  83271. };
  83272. EdgesRenderer.prototype._rebuild = function () {
  83273. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83274. if (buffer) {
  83275. buffer._rebuild();
  83276. }
  83277. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83278. if (buffer) {
  83279. buffer._rebuild();
  83280. }
  83281. var scene = this._source.getScene();
  83282. var engine = scene.getEngine();
  83283. this._ib = engine.createIndexBuffer(this._linesIndices);
  83284. };
  83285. EdgesRenderer.prototype.dispose = function () {
  83286. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  83287. if (buffer) {
  83288. buffer.dispose();
  83289. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  83290. }
  83291. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  83292. if (buffer) {
  83293. buffer.dispose();
  83294. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  83295. }
  83296. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  83297. this._lineShader.dispose();
  83298. };
  83299. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  83300. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  83301. return 0;
  83302. }
  83303. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  83304. return 1;
  83305. }
  83306. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  83307. return 2;
  83308. }
  83309. return -1;
  83310. };
  83311. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  83312. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  83313. return 0;
  83314. }
  83315. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  83316. return 1;
  83317. }
  83318. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  83319. return 2;
  83320. }
  83321. return -1;
  83322. };
  83323. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  83324. var needToCreateLine;
  83325. if (edge === undefined) {
  83326. needToCreateLine = true;
  83327. }
  83328. else {
  83329. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  83330. needToCreateLine = dotProduct < this._epsilon;
  83331. }
  83332. if (needToCreateLine) {
  83333. var offset = this._linesPositions.length / 3;
  83334. var normal = p0.subtract(p1);
  83335. normal.normalize();
  83336. // Positions
  83337. this._linesPositions.push(p0.x);
  83338. this._linesPositions.push(p0.y);
  83339. this._linesPositions.push(p0.z);
  83340. this._linesPositions.push(p0.x);
  83341. this._linesPositions.push(p0.y);
  83342. this._linesPositions.push(p0.z);
  83343. this._linesPositions.push(p1.x);
  83344. this._linesPositions.push(p1.y);
  83345. this._linesPositions.push(p1.z);
  83346. this._linesPositions.push(p1.x);
  83347. this._linesPositions.push(p1.y);
  83348. this._linesPositions.push(p1.z);
  83349. // Normals
  83350. this._linesNormals.push(p1.x);
  83351. this._linesNormals.push(p1.y);
  83352. this._linesNormals.push(p1.z);
  83353. this._linesNormals.push(-1);
  83354. this._linesNormals.push(p1.x);
  83355. this._linesNormals.push(p1.y);
  83356. this._linesNormals.push(p1.z);
  83357. this._linesNormals.push(1);
  83358. this._linesNormals.push(p0.x);
  83359. this._linesNormals.push(p0.y);
  83360. this._linesNormals.push(p0.z);
  83361. this._linesNormals.push(-1);
  83362. this._linesNormals.push(p0.x);
  83363. this._linesNormals.push(p0.y);
  83364. this._linesNormals.push(p0.z);
  83365. this._linesNormals.push(1);
  83366. // Indices
  83367. this._linesIndices.push(offset);
  83368. this._linesIndices.push(offset + 1);
  83369. this._linesIndices.push(offset + 2);
  83370. this._linesIndices.push(offset);
  83371. this._linesIndices.push(offset + 2);
  83372. this._linesIndices.push(offset + 3);
  83373. }
  83374. };
  83375. EdgesRenderer.prototype._generateEdgesLines = function () {
  83376. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  83377. var indices = this._source.getIndices();
  83378. if (!indices || !positions) {
  83379. return;
  83380. }
  83381. // First let's find adjacencies
  83382. var adjacencies = new Array();
  83383. var faceNormals = new Array();
  83384. var index;
  83385. var faceAdjacencies;
  83386. // Prepare faces
  83387. for (index = 0; index < indices.length; index += 3) {
  83388. faceAdjacencies = new FaceAdjacencies();
  83389. var p0Index = indices[index];
  83390. var p1Index = indices[index + 1];
  83391. var p2Index = indices[index + 2];
  83392. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  83393. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  83394. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  83395. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  83396. faceNormal.normalize();
  83397. faceNormals.push(faceNormal);
  83398. adjacencies.push(faceAdjacencies);
  83399. }
  83400. // Scan
  83401. for (index = 0; index < adjacencies.length; index++) {
  83402. faceAdjacencies = adjacencies[index];
  83403. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  83404. var otherFaceAdjacencies = adjacencies[otherIndex];
  83405. if (faceAdjacencies.edgesConnectedCount === 3) {
  83406. break;
  83407. }
  83408. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  83409. continue;
  83410. }
  83411. var otherP0 = indices[otherIndex * 3];
  83412. var otherP1 = indices[otherIndex * 3 + 1];
  83413. var otherP2 = indices[otherIndex * 3 + 2];
  83414. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  83415. var otherEdgeIndex = 0;
  83416. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  83417. continue;
  83418. }
  83419. switch (edgeIndex) {
  83420. case 0:
  83421. if (this._checkVerticesInsteadOfIndices) {
  83422. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83423. }
  83424. else {
  83425. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  83426. }
  83427. break;
  83428. case 1:
  83429. if (this._checkVerticesInsteadOfIndices) {
  83430. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83431. }
  83432. else {
  83433. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  83434. }
  83435. break;
  83436. case 2:
  83437. if (this._checkVerticesInsteadOfIndices) {
  83438. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  83439. }
  83440. else {
  83441. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  83442. }
  83443. break;
  83444. }
  83445. if (otherEdgeIndex === -1) {
  83446. continue;
  83447. }
  83448. faceAdjacencies.edges[edgeIndex] = otherIndex;
  83449. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  83450. faceAdjacencies.edgesConnectedCount++;
  83451. otherFaceAdjacencies.edgesConnectedCount++;
  83452. if (faceAdjacencies.edgesConnectedCount === 3) {
  83453. break;
  83454. }
  83455. }
  83456. }
  83457. }
  83458. // Create lines
  83459. for (index = 0; index < adjacencies.length; index++) {
  83460. // 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
  83461. var current = adjacencies[index];
  83462. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  83463. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  83464. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  83465. }
  83466. // Merge into a single mesh
  83467. var engine = this._source.getScene().getEngine();
  83468. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  83469. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  83470. this._ib = engine.createIndexBuffer(this._linesIndices);
  83471. this._indicesCount = this._linesIndices.length;
  83472. };
  83473. EdgesRenderer.prototype.render = function () {
  83474. var scene = this._source.getScene();
  83475. if (!this._lineShader.isReady() || !scene.activeCamera) {
  83476. return;
  83477. }
  83478. var engine = scene.getEngine();
  83479. this._lineShader._preBind();
  83480. // VBOs
  83481. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  83482. scene.resetCachedMaterial();
  83483. this._lineShader.setColor4("color", this._source.edgesColor);
  83484. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  83485. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  83486. }
  83487. else {
  83488. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  83489. }
  83490. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  83491. this._lineShader.bind(this._source.getWorldMatrix());
  83492. // Draw order
  83493. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  83494. this._lineShader.unbind();
  83495. engine.setDepthWrite(true);
  83496. };
  83497. return EdgesRenderer;
  83498. }());
  83499. BABYLON.EdgesRenderer = EdgesRenderer;
  83500. })(BABYLON || (BABYLON = {}));
  83501. //# sourceMappingURL=babylon.edgesRenderer.js.map
  83502. var __assign = (this && this.__assign) || Object.assign || function(t) {
  83503. for (var s, i = 1, n = arguments.length; i < n; i++) {
  83504. s = arguments[i];
  83505. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  83506. t[p] = s[p];
  83507. }
  83508. return t;
  83509. };
  83510. var BABYLON;
  83511. (function (BABYLON) {
  83512. /**
  83513. * The effect layer Helps adding post process effect blended with the main pass.
  83514. *
  83515. * This can be for instance use to generate glow or higlight effects on the scene.
  83516. *
  83517. * The effect layer class can not be used directly and is intented to inherited from to be
  83518. * customized per effects.
  83519. */
  83520. var EffectLayer = /** @class */ (function () {
  83521. /**
  83522. * Instantiates a new effect Layer and references it in the scene.
  83523. * @param name The name of the layer
  83524. * @param scene The scene to use the layer in
  83525. */
  83526. function EffectLayer(
  83527. /** The Friendly of the effect in the scene */
  83528. name, scene) {
  83529. this.name = name;
  83530. this._vertexBuffers = {};
  83531. this._maxSize = 0;
  83532. this._mainTextureDesiredSize = { width: 0, height: 0 };
  83533. this._shouldRender = true;
  83534. this._postProcesses = [];
  83535. this._textures = [];
  83536. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  83537. /**
  83538. * The clear color of the texture used to generate the glow map.
  83539. */
  83540. this.neutralColor = new BABYLON.Color4();
  83541. /**
  83542. * Specifies wether the highlight layer is enabled or not.
  83543. */
  83544. this.isEnabled = true;
  83545. /**
  83546. * An event triggered when the effect layer has been disposed.
  83547. */
  83548. this.onDisposeObservable = new BABYLON.Observable();
  83549. /**
  83550. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  83551. */
  83552. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  83553. /**
  83554. * An event triggered when the generated texture is being merged in the scene.
  83555. */
  83556. this.onBeforeComposeObservable = new BABYLON.Observable();
  83557. /**
  83558. * An event triggered when the generated texture has been merged in the scene.
  83559. */
  83560. this.onAfterComposeObservable = new BABYLON.Observable();
  83561. /**
  83562. * An event triggered when the efffect layer changes its size.
  83563. */
  83564. this.onSizeChangedObservable = new BABYLON.Observable();
  83565. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83566. this._engine = scene.getEngine();
  83567. this._maxSize = this._engine.getCaps().maxTextureSize;
  83568. this._scene.effectLayers.push(this);
  83569. // Generate Buffers
  83570. this._generateIndexBuffer();
  83571. this._genrateVertexBuffer();
  83572. }
  83573. Object.defineProperty(EffectLayer.prototype, "camera", {
  83574. /**
  83575. * Gets the camera attached to the layer.
  83576. */
  83577. get: function () {
  83578. return this._effectLayerOptions.camera;
  83579. },
  83580. enumerable: true,
  83581. configurable: true
  83582. });
  83583. /**
  83584. * Initializes the effect layer with the required options.
  83585. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  83586. */
  83587. EffectLayer.prototype._init = function (options) {
  83588. // Adapt options
  83589. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  83590. this._setMainTextureSize();
  83591. this._createMainTexture();
  83592. this._createTextureAndPostProcesses();
  83593. this._mergeEffect = this._createMergeEffect();
  83594. };
  83595. /**
  83596. * Generates the index buffer of the full screen quad blending to the main canvas.
  83597. */
  83598. EffectLayer.prototype._generateIndexBuffer = function () {
  83599. // Indices
  83600. var indices = [];
  83601. indices.push(0);
  83602. indices.push(1);
  83603. indices.push(2);
  83604. indices.push(0);
  83605. indices.push(2);
  83606. indices.push(3);
  83607. this._indexBuffer = this._engine.createIndexBuffer(indices);
  83608. };
  83609. /**
  83610. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  83611. */
  83612. EffectLayer.prototype._genrateVertexBuffer = function () {
  83613. // VBO
  83614. var vertices = [];
  83615. vertices.push(1, 1);
  83616. vertices.push(-1, 1);
  83617. vertices.push(-1, -1);
  83618. vertices.push(1, -1);
  83619. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  83620. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  83621. };
  83622. /**
  83623. * Sets the main texture desired size which is the closest power of two
  83624. * of the engine canvas size.
  83625. */
  83626. EffectLayer.prototype._setMainTextureSize = function () {
  83627. if (this._effectLayerOptions.mainTextureFixedSize) {
  83628. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  83629. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  83630. }
  83631. else {
  83632. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  83633. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  83634. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  83635. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  83636. }
  83637. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  83638. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  83639. };
  83640. /**
  83641. * Creates the main texture for the effect layer.
  83642. */
  83643. EffectLayer.prototype._createMainTexture = function () {
  83644. var _this = this;
  83645. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  83646. width: this._mainTextureDesiredSize.width,
  83647. height: this._mainTextureDesiredSize.height
  83648. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  83649. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  83650. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83651. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83652. this._mainTexture.anisotropicFilteringLevel = 1;
  83653. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  83654. this._mainTexture.renderParticles = false;
  83655. this._mainTexture.renderList = null;
  83656. this._mainTexture.ignoreCameraViewport = true;
  83657. // Custom render function
  83658. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83659. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  83660. var index;
  83661. var engine = _this._scene.getEngine();
  83662. if (depthOnlySubMeshes.length) {
  83663. engine.setColorWrite(false);
  83664. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83665. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  83666. }
  83667. engine.setColorWrite(true);
  83668. }
  83669. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83670. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  83671. }
  83672. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83673. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  83674. }
  83675. for (index = 0; index < transparentSubMeshes.length; index++) {
  83676. _this._renderSubMesh(transparentSubMeshes.data[index]);
  83677. }
  83678. };
  83679. this._mainTexture.onClearObservable.add(function (engine) {
  83680. engine.clear(_this.neutralColor, true, true, true);
  83681. });
  83682. };
  83683. /**
  83684. * Checks for the readiness of the element composing the layer.
  83685. * @param subMesh the mesh to check for
  83686. * @param useInstances specify wether or not to use instances to render the mesh
  83687. * @param emissiveTexture the associated emissive texture used to generate the glow
  83688. * @return true if ready otherwise, false
  83689. */
  83690. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  83691. var material = subMesh.getMaterial();
  83692. if (!material) {
  83693. return false;
  83694. }
  83695. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  83696. return false;
  83697. }
  83698. var defines = [];
  83699. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83700. var mesh = subMesh.getMesh();
  83701. var uv1 = false;
  83702. var uv2 = false;
  83703. // Alpha test
  83704. if (material && material.needAlphaTesting()) {
  83705. var alphaTexture = material.getAlphaTestTexture();
  83706. if (alphaTexture) {
  83707. defines.push("#define ALPHATEST");
  83708. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  83709. alphaTexture.coordinatesIndex === 1) {
  83710. defines.push("#define DIFFUSEUV2");
  83711. uv2 = true;
  83712. }
  83713. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83714. defines.push("#define DIFFUSEUV1");
  83715. uv1 = true;
  83716. }
  83717. }
  83718. }
  83719. // Emissive
  83720. if (emissiveTexture) {
  83721. defines.push("#define EMISSIVE");
  83722. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  83723. emissiveTexture.coordinatesIndex === 1) {
  83724. defines.push("#define EMISSIVEUV2");
  83725. uv2 = true;
  83726. }
  83727. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83728. defines.push("#define EMISSIVEUV1");
  83729. uv1 = true;
  83730. }
  83731. }
  83732. if (uv1) {
  83733. attribs.push(BABYLON.VertexBuffer.UVKind);
  83734. defines.push("#define UV1");
  83735. }
  83736. if (uv2) {
  83737. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83738. defines.push("#define UV2");
  83739. }
  83740. // Bones
  83741. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83742. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83743. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83744. if (mesh.numBoneInfluencers > 4) {
  83745. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83746. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83747. }
  83748. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83749. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  83750. }
  83751. else {
  83752. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83753. }
  83754. // Instances
  83755. if (useInstances) {
  83756. defines.push("#define INSTANCES");
  83757. attribs.push("world0");
  83758. attribs.push("world1");
  83759. attribs.push("world2");
  83760. attribs.push("world3");
  83761. }
  83762. // Get correct effect
  83763. var join = defines.join("\n");
  83764. if (this._cachedDefines !== join) {
  83765. this._cachedDefines = join;
  83766. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  83767. }
  83768. return this._effectLayerMapGenerationEffect.isReady();
  83769. };
  83770. /**
  83771. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  83772. */
  83773. EffectLayer.prototype.render = function () {
  83774. var currentEffect = this._mergeEffect;
  83775. // Check
  83776. if (!currentEffect.isReady())
  83777. return;
  83778. for (var i = 0; i < this._postProcesses.length; i++) {
  83779. if (!this._postProcesses[i].isReady()) {
  83780. return;
  83781. }
  83782. }
  83783. var engine = this._scene.getEngine();
  83784. this.onBeforeComposeObservable.notifyObservers(this);
  83785. // Render
  83786. engine.enableEffect(currentEffect);
  83787. engine.setState(false);
  83788. // VBOs
  83789. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  83790. // Cache
  83791. var previousAlphaMode = engine.getAlphaMode();
  83792. // Go Blend.
  83793. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  83794. // Blends the map on the main canvas.
  83795. this._internalRender(currentEffect);
  83796. // Restore Alpha
  83797. engine.setAlphaMode(previousAlphaMode);
  83798. this.onAfterComposeObservable.notifyObservers(this);
  83799. // Handle size changes.
  83800. var size = this._mainTexture.getSize();
  83801. this._setMainTextureSize();
  83802. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  83803. // Recreate RTT and post processes on size change.
  83804. this.onSizeChangedObservable.notifyObservers(this);
  83805. this._disposeTextureAndPostProcesses();
  83806. this._createMainTexture();
  83807. this._createTextureAndPostProcesses();
  83808. }
  83809. };
  83810. /**
  83811. * Determine if a given mesh will be used in the current effect.
  83812. * @param mesh mesh to test
  83813. * @returns true if the mesh will be used
  83814. */
  83815. EffectLayer.prototype.hasMesh = function (mesh) {
  83816. return true;
  83817. };
  83818. /**
  83819. * Returns true if the layer contains information to display, otherwise false.
  83820. * @returns true if the glow layer should be rendered
  83821. */
  83822. EffectLayer.prototype.shouldRender = function () {
  83823. return this.isEnabled && this._shouldRender;
  83824. };
  83825. /**
  83826. * Returns true if the mesh should render, otherwise false.
  83827. * @param mesh The mesh to render
  83828. * @returns true if it should render otherwise false
  83829. */
  83830. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  83831. return true;
  83832. };
  83833. /**
  83834. * Returns true if the mesh should render, otherwise false.
  83835. * @param mesh The mesh to render
  83836. * @returns true if it should render otherwise false
  83837. */
  83838. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  83839. return true;
  83840. };
  83841. /**
  83842. * Renders the submesh passed in parameter to the generation map.
  83843. */
  83844. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  83845. var _this = this;
  83846. if (!this.shouldRender()) {
  83847. return;
  83848. }
  83849. var material = subMesh.getMaterial();
  83850. var mesh = subMesh.getRenderingMesh();
  83851. var scene = this._scene;
  83852. var engine = scene.getEngine();
  83853. if (!material) {
  83854. return;
  83855. }
  83856. // Do not block in blend mode.
  83857. if (material.needAlphaBlendingForMesh(mesh)) {
  83858. return;
  83859. }
  83860. // Culling
  83861. engine.setState(material.backFaceCulling);
  83862. // Managing instances
  83863. var batch = mesh._getInstancesRenderList(subMesh._id);
  83864. if (batch.mustReturn) {
  83865. return;
  83866. }
  83867. // Early Exit per mesh
  83868. if (!this._shouldRenderMesh(mesh)) {
  83869. return;
  83870. }
  83871. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  83872. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  83873. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  83874. engine.enableEffect(this._effectLayerMapGenerationEffect);
  83875. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  83876. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  83877. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  83878. // Alpha test
  83879. if (material && material.needAlphaTesting()) {
  83880. var alphaTexture = material.getAlphaTestTexture();
  83881. if (alphaTexture) {
  83882. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  83883. var textureMatrix = alphaTexture.getTextureMatrix();
  83884. if (textureMatrix) {
  83885. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  83886. }
  83887. }
  83888. }
  83889. // Glow emissive only
  83890. if (this._emissiveTextureAndColor.texture) {
  83891. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  83892. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  83893. }
  83894. // Bones
  83895. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83896. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83897. }
  83898. // Draw
  83899. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  83900. }
  83901. else {
  83902. // Need to reset refresh rate of the shadowMap
  83903. this._mainTexture.resetRefreshCounter();
  83904. }
  83905. };
  83906. /**
  83907. * Rebuild the required buffers.
  83908. * @ignore Internal use only.
  83909. */
  83910. EffectLayer.prototype._rebuild = function () {
  83911. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83912. if (vb) {
  83913. vb._rebuild();
  83914. }
  83915. this._generateIndexBuffer();
  83916. };
  83917. /**
  83918. * Dispose only the render target textures and post process.
  83919. */
  83920. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  83921. this._mainTexture.dispose();
  83922. for (var i = 0; i < this._postProcesses.length; i++) {
  83923. if (this._postProcesses[i]) {
  83924. this._postProcesses[i].dispose();
  83925. }
  83926. }
  83927. this._postProcesses = [];
  83928. for (var i = 0; i < this._textures.length; i++) {
  83929. if (this._textures[i]) {
  83930. this._textures[i].dispose();
  83931. }
  83932. }
  83933. this._textures = [];
  83934. };
  83935. /**
  83936. * Dispose the highlight layer and free resources.
  83937. */
  83938. EffectLayer.prototype.dispose = function () {
  83939. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  83940. if (vertexBuffer) {
  83941. vertexBuffer.dispose();
  83942. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  83943. }
  83944. if (this._indexBuffer) {
  83945. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  83946. this._indexBuffer = null;
  83947. }
  83948. // Clean textures and post processes
  83949. this._disposeTextureAndPostProcesses();
  83950. // Remove from scene
  83951. var index = this._scene.effectLayers.indexOf(this, 0);
  83952. if (index > -1) {
  83953. this._scene.effectLayers.splice(index, 1);
  83954. }
  83955. // Callback
  83956. this.onDisposeObservable.notifyObservers(this);
  83957. this.onDisposeObservable.clear();
  83958. this.onBeforeRenderMainTextureObservable.clear();
  83959. this.onBeforeComposeObservable.clear();
  83960. this.onAfterComposeObservable.clear();
  83961. this.onSizeChangedObservable.clear();
  83962. };
  83963. return EffectLayer;
  83964. }());
  83965. BABYLON.EffectLayer = EffectLayer;
  83966. })(BABYLON || (BABYLON = {}));
  83967. //# sourceMappingURL=babylon.effectLayer.js.map
  83968. var BABYLON;
  83969. (function (BABYLON) {
  83970. /**
  83971. * Special Glow Blur post process only blurring the alpha channel
  83972. * It enforces keeping the most luminous color in the color channel.
  83973. */
  83974. var GlowBlurPostProcess = /** @class */ (function (_super) {
  83975. __extends(GlowBlurPostProcess, _super);
  83976. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  83977. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  83978. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  83979. _this.direction = direction;
  83980. _this.kernel = kernel;
  83981. _this.onApplyObservable.add(function (effect) {
  83982. effect.setFloat2("screenSize", _this.width, _this.height);
  83983. effect.setVector2("direction", _this.direction);
  83984. effect.setFloat("blurWidth", _this.kernel);
  83985. });
  83986. return _this;
  83987. }
  83988. return GlowBlurPostProcess;
  83989. }(BABYLON.PostProcess));
  83990. /**
  83991. * The highlight layer Helps adding a glow effect around a mesh.
  83992. *
  83993. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  83994. * glowy meshes to your scene.
  83995. *
  83996. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  83997. */
  83998. var HighlightLayer = /** @class */ (function (_super) {
  83999. __extends(HighlightLayer, _super);
  84000. /**
  84001. * Instantiates a new highlight Layer and references it to the scene..
  84002. * @param name The name of the layer
  84003. * @param scene The scene to use the layer in
  84004. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  84005. */
  84006. function HighlightLayer(name, scene, options) {
  84007. var _this = _super.call(this, name, scene) || this;
  84008. _this.name = name;
  84009. /**
  84010. * Specifies whether or not the inner glow is ACTIVE in the layer.
  84011. */
  84012. _this.innerGlow = true;
  84013. /**
  84014. * Specifies whether or not the outer glow is ACTIVE in the layer.
  84015. */
  84016. _this.outerGlow = true;
  84017. /**
  84018. * An event triggered when the highlight layer is being blurred.
  84019. */
  84020. _this.onBeforeBlurObservable = new BABYLON.Observable();
  84021. /**
  84022. * An event triggered when the highlight layer has been blurred.
  84023. */
  84024. _this.onAfterBlurObservable = new BABYLON.Observable();
  84025. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  84026. _this._meshes = {};
  84027. _this._excludedMeshes = {};
  84028. _this.neutralColor = HighlightLayer.NeutralColor;
  84029. // Warn on stencil
  84030. if (!_this._engine.isStencilEnable) {
  84031. 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 }");
  84032. }
  84033. // Adapt options
  84034. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  84035. // Initialize the layer
  84036. _this._init({
  84037. alphaBlendingMode: _this._options.alphaBlendingMode,
  84038. camera: _this._options.camera,
  84039. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84040. mainTextureRatio: _this._options.mainTextureRatio
  84041. });
  84042. // Do not render as long as no meshes have been added
  84043. _this._shouldRender = false;
  84044. return _this;
  84045. }
  84046. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  84047. /**
  84048. * Gets the horizontal size of the blur.
  84049. */
  84050. get: function () {
  84051. return this._horizontalBlurPostprocess.kernel;
  84052. },
  84053. /**
  84054. * Specifies the horizontal size of the blur.
  84055. */
  84056. set: function (value) {
  84057. this._horizontalBlurPostprocess.kernel = value;
  84058. },
  84059. enumerable: true,
  84060. configurable: true
  84061. });
  84062. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  84063. /**
  84064. * Gets the vertical size of the blur.
  84065. */
  84066. get: function () {
  84067. return this._verticalBlurPostprocess.kernel;
  84068. },
  84069. /**
  84070. * Specifies the vertical size of the blur.
  84071. */
  84072. set: function (value) {
  84073. this._verticalBlurPostprocess.kernel = value;
  84074. },
  84075. enumerable: true,
  84076. configurable: true
  84077. });
  84078. /**
  84079. * Get the effect name of the layer.
  84080. * @return The effect name
  84081. */
  84082. HighlightLayer.prototype.getEffectName = function () {
  84083. return HighlightLayer.EffectName;
  84084. };
  84085. /**
  84086. * Create the merge effect. This is the shader use to blit the information back
  84087. * to the main canvas at the end of the scene rendering.
  84088. */
  84089. HighlightLayer.prototype._createMergeEffect = function () {
  84090. // Effect
  84091. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  84092. };
  84093. /**
  84094. * Creates the render target textures and post processes used in the highlight layer.
  84095. */
  84096. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  84097. var _this = this;
  84098. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  84099. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  84100. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  84101. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  84102. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  84103. width: blurTextureWidth,
  84104. height: blurTextureHeight
  84105. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84106. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84107. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84108. this._blurTexture.anisotropicFilteringLevel = 16;
  84109. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84110. this._blurTexture.renderParticles = false;
  84111. this._blurTexture.ignoreCameraViewport = true;
  84112. this._textures = [this._blurTexture];
  84113. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  84114. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84115. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  84116. effect.setTexture("textureSampler", _this._mainTexture);
  84117. });
  84118. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84119. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84120. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84121. });
  84122. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  84123. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  84124. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  84125. });
  84126. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84127. }
  84128. else {
  84129. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  84130. width: blurTextureWidth,
  84131. height: blurTextureHeight
  84132. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84133. this._horizontalBlurPostprocess.width = blurTextureWidth;
  84134. this._horizontalBlurPostprocess.height = blurTextureHeight;
  84135. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  84136. effect.setTexture("textureSampler", _this._mainTexture);
  84137. });
  84138. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  84139. width: blurTextureWidth,
  84140. height: blurTextureHeight
  84141. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84142. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  84143. }
  84144. this._mainTexture.onAfterUnbindObservable.add(function () {
  84145. _this.onBeforeBlurObservable.notifyObservers(_this);
  84146. var internalTexture = _this._blurTexture.getInternalTexture();
  84147. if (internalTexture) {
  84148. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  84149. }
  84150. _this.onAfterBlurObservable.notifyObservers(_this);
  84151. });
  84152. // Prevent autoClear.
  84153. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  84154. };
  84155. /**
  84156. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  84157. */
  84158. HighlightLayer.prototype.needStencil = function () {
  84159. return true;
  84160. };
  84161. /**
  84162. * Checks for the readiness of the element composing the layer.
  84163. * @param subMesh the mesh to check for
  84164. * @param useInstances specify wether or not to use instances to render the mesh
  84165. * @param emissiveTexture the associated emissive texture used to generate the glow
  84166. * @return true if ready otherwise, false
  84167. */
  84168. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  84169. var material = subMesh.getMaterial();
  84170. var mesh = subMesh.getRenderingMesh();
  84171. if (!material || !mesh || !this._meshes) {
  84172. return false;
  84173. }
  84174. var emissiveTexture = null;
  84175. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84176. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84177. emissiveTexture = material.emissiveTexture;
  84178. }
  84179. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  84180. };
  84181. /**
  84182. * Implementation specific of rendering the generating effect on the main canvas.
  84183. * @param effect The effect used to render through
  84184. */
  84185. HighlightLayer.prototype._internalRender = function (effect) {
  84186. // Texture
  84187. effect.setTexture("textureSampler", this._blurTexture);
  84188. // Cache
  84189. var engine = this._engine;
  84190. var previousStencilBuffer = engine.getStencilBuffer();
  84191. var previousStencilFunction = engine.getStencilFunction();
  84192. var previousStencilMask = engine.getStencilMask();
  84193. var previousStencilOperationPass = engine.getStencilOperationPass();
  84194. var previousStencilOperationFail = engine.getStencilOperationFail();
  84195. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  84196. var previousStencilReference = engine.getStencilFunctionReference();
  84197. // Stencil operations
  84198. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  84199. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  84200. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  84201. // Draw order
  84202. engine.setStencilMask(0x00);
  84203. engine.setStencilBuffer(true);
  84204. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  84205. // 2 passes inner outer
  84206. if (this.outerGlow) {
  84207. effect.setFloat("offset", 0);
  84208. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  84209. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84210. }
  84211. if (this.innerGlow) {
  84212. effect.setFloat("offset", 1);
  84213. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  84214. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84215. }
  84216. // Restore Cache
  84217. engine.setStencilFunction(previousStencilFunction);
  84218. engine.setStencilMask(previousStencilMask);
  84219. engine.setStencilBuffer(previousStencilBuffer);
  84220. engine.setStencilOperationPass(previousStencilOperationPass);
  84221. engine.setStencilOperationFail(previousStencilOperationFail);
  84222. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  84223. engine.setStencilFunctionReference(previousStencilReference);
  84224. };
  84225. /**
  84226. * Returns true if the layer contains information to display, otherwise false.
  84227. */
  84228. HighlightLayer.prototype.shouldRender = function () {
  84229. if (_super.prototype.shouldRender.call(this)) {
  84230. return this._meshes ? true : false;
  84231. }
  84232. return false;
  84233. };
  84234. /**
  84235. * Returns true if the mesh should render, otherwise false.
  84236. * @param mesh The mesh to render
  84237. * @returns true if it should render otherwise false
  84238. */
  84239. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  84240. // Excluded Mesh
  84241. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  84242. return false;
  84243. }
  84244. ;
  84245. return true;
  84246. };
  84247. /**
  84248. * Sets the required values for both the emissive texture and and the main color.
  84249. */
  84250. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  84251. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  84252. if (highlightLayerMesh) {
  84253. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  84254. }
  84255. else {
  84256. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  84257. }
  84258. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  84259. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  84260. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  84261. }
  84262. else {
  84263. this._emissiveTextureAndColor.texture = null;
  84264. }
  84265. };
  84266. /**
  84267. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  84268. * @param mesh The mesh to exclude from the highlight layer
  84269. */
  84270. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  84271. if (!this._excludedMeshes) {
  84272. return;
  84273. }
  84274. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84275. if (!meshExcluded) {
  84276. this._excludedMeshes[mesh.uniqueId] = {
  84277. mesh: mesh,
  84278. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  84279. mesh.getEngine().setStencilBuffer(false);
  84280. }),
  84281. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  84282. mesh.getEngine().setStencilBuffer(true);
  84283. }),
  84284. };
  84285. }
  84286. };
  84287. /**
  84288. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  84289. * @param mesh The mesh to highlight
  84290. */
  84291. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  84292. if (!this._excludedMeshes) {
  84293. return;
  84294. }
  84295. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  84296. if (meshExcluded) {
  84297. if (meshExcluded.beforeRender) {
  84298. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  84299. }
  84300. if (meshExcluded.afterRender) {
  84301. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  84302. }
  84303. }
  84304. this._excludedMeshes[mesh.uniqueId] = null;
  84305. };
  84306. /**
  84307. * Determine if a given mesh will be highlighted by the current HighlightLayer
  84308. * @param mesh mesh to test
  84309. * @returns true if the mesh will be highlighted by the current HighlightLayer
  84310. */
  84311. HighlightLayer.prototype.hasMesh = function (mesh) {
  84312. if (!this._meshes) {
  84313. return false;
  84314. }
  84315. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  84316. };
  84317. /**
  84318. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  84319. * @param mesh The mesh to highlight
  84320. * @param color The color of the highlight
  84321. * @param glowEmissiveOnly Extract the glow from the emissive texture
  84322. */
  84323. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  84324. var _this = this;
  84325. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  84326. if (!this._meshes) {
  84327. return;
  84328. }
  84329. var meshHighlight = this._meshes[mesh.uniqueId];
  84330. if (meshHighlight) {
  84331. meshHighlight.color = color;
  84332. }
  84333. else {
  84334. this._meshes[mesh.uniqueId] = {
  84335. mesh: mesh,
  84336. color: color,
  84337. // Lambda required for capture due to Observable this context
  84338. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  84339. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  84340. _this._defaultStencilReference(mesh);
  84341. }
  84342. else {
  84343. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  84344. }
  84345. }),
  84346. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  84347. glowEmissiveOnly: glowEmissiveOnly
  84348. };
  84349. }
  84350. this._shouldRender = true;
  84351. };
  84352. /**
  84353. * Remove a mesh from the highlight layer in order to make it stop glowing.
  84354. * @param mesh The mesh to highlight
  84355. */
  84356. HighlightLayer.prototype.removeMesh = function (mesh) {
  84357. if (!this._meshes) {
  84358. return;
  84359. }
  84360. var meshHighlight = this._meshes[mesh.uniqueId];
  84361. if (meshHighlight) {
  84362. if (meshHighlight.observerHighlight) {
  84363. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  84364. }
  84365. if (meshHighlight.observerDefault) {
  84366. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  84367. }
  84368. delete this._meshes[mesh.uniqueId];
  84369. }
  84370. this._shouldRender = false;
  84371. for (var meshHighlightToCheck in this._meshes) {
  84372. if (this._meshes[meshHighlightToCheck]) {
  84373. this._shouldRender = true;
  84374. break;
  84375. }
  84376. }
  84377. };
  84378. /**
  84379. * Force the stencil to the normal expected value for none glowing parts
  84380. */
  84381. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  84382. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  84383. };
  84384. /**
  84385. * Free any resources and references associated to a mesh.
  84386. * Internal use
  84387. * @param mesh The mesh to free.
  84388. */
  84389. HighlightLayer.prototype._disposeMesh = function (mesh) {
  84390. this.removeMesh(mesh);
  84391. this.removeExcludedMesh(mesh);
  84392. };
  84393. /**
  84394. * Dispose the highlight layer and free resources.
  84395. */
  84396. HighlightLayer.prototype.dispose = function () {
  84397. if (this._meshes) {
  84398. // Clean mesh references
  84399. for (var id in this._meshes) {
  84400. var meshHighlight = this._meshes[id];
  84401. if (meshHighlight && meshHighlight.mesh) {
  84402. if (meshHighlight.observerHighlight) {
  84403. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  84404. }
  84405. if (meshHighlight.observerDefault) {
  84406. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  84407. }
  84408. }
  84409. }
  84410. this._meshes = null;
  84411. }
  84412. if (this._excludedMeshes) {
  84413. for (var id in this._excludedMeshes) {
  84414. var meshHighlight = this._excludedMeshes[id];
  84415. if (meshHighlight) {
  84416. if (meshHighlight.beforeRender) {
  84417. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  84418. }
  84419. if (meshHighlight.afterRender) {
  84420. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  84421. }
  84422. }
  84423. }
  84424. this._excludedMeshes = null;
  84425. }
  84426. _super.prototype.dispose.call(this);
  84427. };
  84428. /**
  84429. * Effect Name of the highlight layer.
  84430. */
  84431. HighlightLayer.EffectName = "HighlightLayer";
  84432. /**
  84433. * The neutral color used during the preparation of the glow effect.
  84434. * This is black by default as the blend operation is a blend operation.
  84435. */
  84436. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  84437. /**
  84438. * Stencil value used for glowing meshes.
  84439. */
  84440. HighlightLayer.GlowingMeshStencilReference = 0x02;
  84441. /**
  84442. * Stencil value used for the other meshes in the scene.
  84443. */
  84444. HighlightLayer.NormalMeshStencilReference = 0x01;
  84445. return HighlightLayer;
  84446. }(BABYLON.EffectLayer));
  84447. BABYLON.HighlightLayer = HighlightLayer;
  84448. })(BABYLON || (BABYLON = {}));
  84449. //# sourceMappingURL=babylon.highlightLayer.js.map
  84450. var BABYLON;
  84451. (function (BABYLON) {
  84452. /**
  84453. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  84454. *
  84455. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  84456. * glowy meshes to your scene.
  84457. *
  84458. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  84459. */
  84460. var GlowLayer = /** @class */ (function (_super) {
  84461. __extends(GlowLayer, _super);
  84462. /**
  84463. * Instantiates a new glow Layer and references it to the scene.
  84464. * @param name The name of the layer
  84465. * @param scene The scene to use the layer in
  84466. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  84467. */
  84468. function GlowLayer(name, scene, options) {
  84469. var _this = _super.call(this, name, scene) || this;
  84470. _this.name = name;
  84471. _this._intensity = 1.0;
  84472. _this._includedOnlyMeshes = [];
  84473. _this._excludedMeshes = [];
  84474. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  84475. // Adapt options
  84476. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  84477. // Initialize the layer
  84478. _this._init({
  84479. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  84480. camera: _this._options.camera,
  84481. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  84482. mainTextureRatio: _this._options.mainTextureRatio
  84483. });
  84484. return _this;
  84485. }
  84486. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  84487. /**
  84488. * Gets the kernel size of the blur.
  84489. */
  84490. get: function () {
  84491. return this._horizontalBlurPostprocess1.kernel;
  84492. },
  84493. /**
  84494. * Sets the kernel size of the blur.
  84495. */
  84496. set: function (value) {
  84497. this._horizontalBlurPostprocess1.kernel = value;
  84498. this._verticalBlurPostprocess1.kernel = value;
  84499. this._horizontalBlurPostprocess2.kernel = value;
  84500. this._verticalBlurPostprocess2.kernel = value;
  84501. },
  84502. enumerable: true,
  84503. configurable: true
  84504. });
  84505. Object.defineProperty(GlowLayer.prototype, "intensity", {
  84506. /**
  84507. * Gets the glow intensity.
  84508. */
  84509. get: function () {
  84510. return this._intensity;
  84511. },
  84512. /**
  84513. * Sets the glow intensity.
  84514. */
  84515. set: function (value) {
  84516. this._intensity = value;
  84517. },
  84518. enumerable: true,
  84519. configurable: true
  84520. });
  84521. /**
  84522. * Get the effect name of the layer.
  84523. * @return The effect name
  84524. */
  84525. GlowLayer.prototype.getEffectName = function () {
  84526. return GlowLayer.EffectName;
  84527. };
  84528. /**
  84529. * Create the merge effect. This is the shader use to blit the information back
  84530. * to the main canvas at the end of the scene rendering.
  84531. */
  84532. GlowLayer.prototype._createMergeEffect = function () {
  84533. // Effect
  84534. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  84535. };
  84536. /**
  84537. * Creates the render target textures and post processes used in the glow layer.
  84538. */
  84539. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  84540. var _this = this;
  84541. var blurTextureWidth = this._mainTextureDesiredSize.width;
  84542. var blurTextureHeight = this._mainTextureDesiredSize.height;
  84543. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  84544. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  84545. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  84546. width: blurTextureWidth,
  84547. height: blurTextureHeight
  84548. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84549. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84550. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84551. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84552. this._blurTexture1.renderParticles = false;
  84553. this._blurTexture1.ignoreCameraViewport = true;
  84554. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  84555. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  84556. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  84557. width: blurTextureWidth2,
  84558. height: blurTextureHeight2
  84559. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84560. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84561. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  84562. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84563. this._blurTexture2.renderParticles = false;
  84564. this._blurTexture2.ignoreCameraViewport = true;
  84565. this._textures = [this._blurTexture1, this._blurTexture2];
  84566. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  84567. width: blurTextureWidth,
  84568. height: blurTextureHeight
  84569. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84570. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  84571. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  84572. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  84573. effect.setTexture("textureSampler", _this._mainTexture);
  84574. });
  84575. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  84576. width: blurTextureWidth,
  84577. height: blurTextureHeight
  84578. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84579. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  84580. width: blurTextureWidth2,
  84581. height: blurTextureHeight2
  84582. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84583. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  84584. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  84585. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  84586. effect.setTexture("textureSampler", _this._blurTexture1);
  84587. });
  84588. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  84589. width: blurTextureWidth2,
  84590. height: blurTextureHeight2
  84591. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  84592. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  84593. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  84594. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  84595. this._mainTexture.samples = this._options.mainTextureSamples;
  84596. this._mainTexture.onAfterUnbindObservable.add(function () {
  84597. var internalTexture = _this._blurTexture1.getInternalTexture();
  84598. if (internalTexture) {
  84599. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  84600. internalTexture = _this._blurTexture2.getInternalTexture();
  84601. if (internalTexture) {
  84602. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  84603. }
  84604. }
  84605. });
  84606. // Prevent autoClear.
  84607. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  84608. };
  84609. /**
  84610. * Checks for the readiness of the element composing the layer.
  84611. * @param subMesh the mesh to check for
  84612. * @param useInstances specify wether or not to use instances to render the mesh
  84613. * @param emissiveTexture the associated emissive texture used to generate the glow
  84614. * @return true if ready otherwise, false
  84615. */
  84616. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  84617. var material = subMesh.getMaterial();
  84618. var mesh = subMesh.getRenderingMesh();
  84619. if (!material || !mesh) {
  84620. return false;
  84621. }
  84622. var emissiveTexture = material.emissiveTexture;
  84623. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  84624. };
  84625. /**
  84626. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  84627. */
  84628. GlowLayer.prototype.needStencil = function () {
  84629. return false;
  84630. };
  84631. /**
  84632. * Implementation specific of rendering the generating effect on the main canvas.
  84633. * @param effect The effect used to render through
  84634. */
  84635. GlowLayer.prototype._internalRender = function (effect) {
  84636. // Texture
  84637. effect.setTexture("textureSampler", this._blurTexture1);
  84638. effect.setTexture("textureSampler2", this._blurTexture2);
  84639. effect.setFloat("offset", this._intensity);
  84640. // Cache
  84641. var engine = this._engine;
  84642. var previousStencilBuffer = engine.getStencilBuffer();
  84643. // Draw order
  84644. engine.setStencilBuffer(false);
  84645. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84646. // Draw order
  84647. engine.setStencilBuffer(previousStencilBuffer);
  84648. };
  84649. /**
  84650. * Sets the required values for both the emissive texture and and the main color.
  84651. */
  84652. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  84653. var textureLevel = 1.0;
  84654. if (this.customEmissiveTextureSelector) {
  84655. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  84656. }
  84657. else {
  84658. if (material) {
  84659. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  84660. if (this._emissiveTextureAndColor.texture) {
  84661. textureLevel = this._emissiveTextureAndColor.texture.level;
  84662. }
  84663. }
  84664. else {
  84665. this._emissiveTextureAndColor.texture = null;
  84666. }
  84667. }
  84668. if (this.customEmissiveColorSelector) {
  84669. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  84670. }
  84671. else {
  84672. if (material.emissiveColor) {
  84673. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  84674. }
  84675. else {
  84676. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  84677. }
  84678. }
  84679. };
  84680. /**
  84681. * Returns true if the mesh should render, otherwise false.
  84682. * @param mesh The mesh to render
  84683. * @returns true if it should render otherwise false
  84684. */
  84685. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  84686. return this.hasMesh(mesh);
  84687. };
  84688. /**
  84689. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  84690. * @param mesh The mesh to exclude from the glow layer
  84691. */
  84692. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  84693. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  84694. this._excludedMeshes.push(mesh.uniqueId);
  84695. }
  84696. };
  84697. /**
  84698. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  84699. * @param mesh The mesh to remove
  84700. */
  84701. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  84702. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  84703. if (index !== -1) {
  84704. this._excludedMeshes.splice(index, 1);
  84705. }
  84706. };
  84707. /**
  84708. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  84709. * @param mesh The mesh to include in the glow layer
  84710. */
  84711. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  84712. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  84713. this._includedOnlyMeshes.push(mesh.uniqueId);
  84714. }
  84715. };
  84716. /**
  84717. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  84718. * @param mesh The mesh to remove
  84719. */
  84720. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  84721. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  84722. if (index !== -1) {
  84723. this._includedOnlyMeshes.splice(index, 1);
  84724. }
  84725. };
  84726. /**
  84727. * Determine if a given mesh will be used in the glow layer
  84728. * @param mesh The mesh to test
  84729. * @returns true if the mesh will be highlighted by the current glow layer
  84730. */
  84731. GlowLayer.prototype.hasMesh = function (mesh) {
  84732. // Included Mesh
  84733. if (this._includedOnlyMeshes.length) {
  84734. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  84735. }
  84736. ;
  84737. // Excluded Mesh
  84738. if (this._excludedMeshes.length) {
  84739. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  84740. }
  84741. ;
  84742. return true;
  84743. };
  84744. /**
  84745. * Free any resources and references associated to a mesh.
  84746. * Internal use
  84747. * @param mesh The mesh to free.
  84748. */
  84749. GlowLayer.prototype._disposeMesh = function (mesh) {
  84750. this.removeIncludedOnlyMesh(mesh);
  84751. this.removeExcludedMesh(mesh);
  84752. };
  84753. /**
  84754. * Effect Name of the layer.
  84755. */
  84756. GlowLayer.EffectName = "GlowLayer";
  84757. /**
  84758. * The default blur kernel size used for the glow.
  84759. */
  84760. GlowLayer.DefaultBlurKernelSize = 32;
  84761. /**
  84762. * The default texture size ratio used for the glow.
  84763. */
  84764. GlowLayer.DefaultTextureRatio = 0.5;
  84765. return GlowLayer;
  84766. }(BABYLON.EffectLayer));
  84767. BABYLON.GlowLayer = GlowLayer;
  84768. })(BABYLON || (BABYLON = {}));
  84769. //# sourceMappingURL=babylon.glowLayer.js.map
  84770. var BABYLON;
  84771. (function (BABYLON) {
  84772. /**
  84773. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  84774. */
  84775. var AssetTaskState;
  84776. (function (AssetTaskState) {
  84777. /**
  84778. * Initialization
  84779. */
  84780. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  84781. /**
  84782. * Running
  84783. */
  84784. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  84785. /**
  84786. * Done
  84787. */
  84788. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  84789. /**
  84790. * Error
  84791. */
  84792. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  84793. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  84794. /**
  84795. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  84796. */
  84797. var AbstractAssetTask = /** @class */ (function () {
  84798. /**
  84799. * Creates a new {BABYLON.AssetsManager}
  84800. * @param name defines the name of the task
  84801. */
  84802. function AbstractAssetTask(
  84803. /**
  84804. * Task name
  84805. */ name) {
  84806. this.name = name;
  84807. this._isCompleted = false;
  84808. this._taskState = AssetTaskState.INIT;
  84809. }
  84810. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  84811. /**
  84812. * Get if the task is completed
  84813. */
  84814. get: function () {
  84815. return this._isCompleted;
  84816. },
  84817. enumerable: true,
  84818. configurable: true
  84819. });
  84820. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  84821. /**
  84822. * Gets the current state of the task
  84823. */
  84824. get: function () {
  84825. return this._taskState;
  84826. },
  84827. enumerable: true,
  84828. configurable: true
  84829. });
  84830. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  84831. /**
  84832. * Gets the current error object (if task is in error)
  84833. */
  84834. get: function () {
  84835. return this._errorObject;
  84836. },
  84837. enumerable: true,
  84838. configurable: true
  84839. });
  84840. /**
  84841. * Internal only
  84842. * @ignore
  84843. */
  84844. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  84845. if (this._errorObject) {
  84846. return;
  84847. }
  84848. this._errorObject = {
  84849. message: message,
  84850. exception: exception
  84851. };
  84852. };
  84853. /**
  84854. * Execute the current task
  84855. * @param scene defines the scene where you want your assets to be loaded
  84856. * @param onSuccess is a callback called when the task is successfully executed
  84857. * @param onError is a callback called if an error occurs
  84858. */
  84859. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  84860. var _this = this;
  84861. this._taskState = AssetTaskState.RUNNING;
  84862. this.runTask(scene, function () {
  84863. _this.onDoneCallback(onSuccess, onError);
  84864. }, function (msg, exception) {
  84865. _this.onErrorCallback(onError, msg, exception);
  84866. });
  84867. };
  84868. /**
  84869. * Execute the current task
  84870. * @param scene defines the scene where you want your assets to be loaded
  84871. * @param onSuccess is a callback called when the task is successfully executed
  84872. * @param onError is a callback called if an error occurs
  84873. */
  84874. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84875. throw new Error("runTask is not implemented");
  84876. };
  84877. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  84878. this._taskState = AssetTaskState.ERROR;
  84879. this._errorObject = {
  84880. message: message,
  84881. exception: exception
  84882. };
  84883. if (this.onError) {
  84884. this.onError(this, message, exception);
  84885. }
  84886. onError();
  84887. };
  84888. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  84889. try {
  84890. this._taskState = AssetTaskState.DONE;
  84891. this._isCompleted = true;
  84892. if (this.onSuccess) {
  84893. this.onSuccess(this);
  84894. }
  84895. onSuccess();
  84896. }
  84897. catch (e) {
  84898. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  84899. }
  84900. };
  84901. return AbstractAssetTask;
  84902. }());
  84903. BABYLON.AbstractAssetTask = AbstractAssetTask;
  84904. /**
  84905. * Class used to share progress information about assets loading
  84906. */
  84907. var AssetsProgressEvent = /** @class */ (function () {
  84908. /**
  84909. * Creates a {BABYLON.AssetsProgressEvent}
  84910. * @param remainingCount defines the number of remaining tasks to process
  84911. * @param totalCount defines the total number of tasks
  84912. * @param task defines the task that was just processed
  84913. */
  84914. function AssetsProgressEvent(remainingCount, totalCount, task) {
  84915. this.remainingCount = remainingCount;
  84916. this.totalCount = totalCount;
  84917. this.task = task;
  84918. }
  84919. return AssetsProgressEvent;
  84920. }());
  84921. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  84922. /**
  84923. * Define a task used by {BABYLON.AssetsManager} to load meshes
  84924. */
  84925. var MeshAssetTask = /** @class */ (function (_super) {
  84926. __extends(MeshAssetTask, _super);
  84927. /**
  84928. * Creates a new {BABYLON.MeshAssetTask}
  84929. * @param name defines the name of the task
  84930. * @param meshesNames defines the list of mesh's names you want to load
  84931. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  84932. * @param sceneFilename defines the filename of the scene to load from
  84933. */
  84934. function MeshAssetTask(
  84935. /**
  84936. * Defines the name of the task
  84937. */
  84938. name,
  84939. /**
  84940. * Defines the list of mesh's names you want to load
  84941. */
  84942. meshesNames,
  84943. /**
  84944. * Defines the root url to use as a base to load your meshes and associated resources
  84945. */
  84946. rootUrl,
  84947. /**
  84948. * Defines the filename of the scene to load from
  84949. */
  84950. sceneFilename) {
  84951. var _this = _super.call(this, name) || this;
  84952. _this.name = name;
  84953. _this.meshesNames = meshesNames;
  84954. _this.rootUrl = rootUrl;
  84955. _this.sceneFilename = sceneFilename;
  84956. return _this;
  84957. }
  84958. /**
  84959. * Execute the current task
  84960. * @param scene defines the scene where you want your assets to be loaded
  84961. * @param onSuccess is a callback called when the task is successfully executed
  84962. * @param onError is a callback called if an error occurs
  84963. */
  84964. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  84965. var _this = this;
  84966. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  84967. _this.loadedMeshes = meshes;
  84968. _this.loadedParticleSystems = particleSystems;
  84969. _this.loadedSkeletons = skeletons;
  84970. onSuccess();
  84971. }, null, function (scene, message, exception) {
  84972. onError(message, exception);
  84973. });
  84974. };
  84975. return MeshAssetTask;
  84976. }(AbstractAssetTask));
  84977. BABYLON.MeshAssetTask = MeshAssetTask;
  84978. /**
  84979. * Define a task used by {BABYLON.AssetsManager} to load text content
  84980. */
  84981. var TextFileAssetTask = /** @class */ (function (_super) {
  84982. __extends(TextFileAssetTask, _super);
  84983. /**
  84984. * Creates a new TextFileAssetTask object
  84985. * @param name defines the name of the task
  84986. * @param url defines the location of the file to load
  84987. */
  84988. function TextFileAssetTask(
  84989. /**
  84990. * Defines the name of the task
  84991. */
  84992. name,
  84993. /**
  84994. * Defines the location of the file to load
  84995. */
  84996. url) {
  84997. var _this = _super.call(this, name) || this;
  84998. _this.name = name;
  84999. _this.url = url;
  85000. return _this;
  85001. }
  85002. /**
  85003. * Execute the current task
  85004. * @param scene defines the scene where you want your assets to be loaded
  85005. * @param onSuccess is a callback called when the task is successfully executed
  85006. * @param onError is a callback called if an error occurs
  85007. */
  85008. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85009. var _this = this;
  85010. scene._loadFile(this.url, function (data) {
  85011. _this.text = data;
  85012. onSuccess();
  85013. }, undefined, false, false, function (request, exception) {
  85014. if (request) {
  85015. onError(request.status + " " + request.statusText, exception);
  85016. }
  85017. });
  85018. };
  85019. return TextFileAssetTask;
  85020. }(AbstractAssetTask));
  85021. BABYLON.TextFileAssetTask = TextFileAssetTask;
  85022. /**
  85023. * Define a task used by {BABYLON.AssetsManager} to load binary data
  85024. */
  85025. var BinaryFileAssetTask = /** @class */ (function (_super) {
  85026. __extends(BinaryFileAssetTask, _super);
  85027. /**
  85028. * Creates a new BinaryFileAssetTask object
  85029. * @param name defines the name of the new task
  85030. * @param url defines the location of the file to load
  85031. */
  85032. function BinaryFileAssetTask(
  85033. /**
  85034. * Defines the name of the task
  85035. */
  85036. name,
  85037. /**
  85038. * Defines the location of the file to load
  85039. */
  85040. url) {
  85041. var _this = _super.call(this, name) || this;
  85042. _this.name = name;
  85043. _this.url = url;
  85044. return _this;
  85045. }
  85046. /**
  85047. * Execute the current task
  85048. * @param scene defines the scene where you want your assets to be loaded
  85049. * @param onSuccess is a callback called when the task is successfully executed
  85050. * @param onError is a callback called if an error occurs
  85051. */
  85052. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85053. var _this = this;
  85054. scene._loadFile(this.url, function (data) {
  85055. _this.data = data;
  85056. onSuccess();
  85057. }, undefined, true, true, function (request, exception) {
  85058. if (request) {
  85059. onError(request.status + " " + request.statusText, exception);
  85060. }
  85061. });
  85062. };
  85063. return BinaryFileAssetTask;
  85064. }(AbstractAssetTask));
  85065. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  85066. /**
  85067. * Define a task used by {BABYLON.AssetsManager} to load images
  85068. */
  85069. var ImageAssetTask = /** @class */ (function (_super) {
  85070. __extends(ImageAssetTask, _super);
  85071. /**
  85072. * Creates a new ImageAssetTask
  85073. * @param name defines the name of the task
  85074. * @param url defines the location of the image to load
  85075. */
  85076. function ImageAssetTask(
  85077. /**
  85078. * Defines the name of the task
  85079. */
  85080. name,
  85081. /**
  85082. * Defines the location of the image to load
  85083. */
  85084. url) {
  85085. var _this = _super.call(this, name) || this;
  85086. _this.name = name;
  85087. _this.url = url;
  85088. return _this;
  85089. }
  85090. /**
  85091. * Execute the current task
  85092. * @param scene defines the scene where you want your assets to be loaded
  85093. * @param onSuccess is a callback called when the task is successfully executed
  85094. * @param onError is a callback called if an error occurs
  85095. */
  85096. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85097. var _this = this;
  85098. var img = new Image();
  85099. BABYLON.Tools.SetCorsBehavior(this.url, img);
  85100. img.onload = function () {
  85101. _this.image = img;
  85102. onSuccess();
  85103. };
  85104. img.onerror = function (err) {
  85105. onError("Error loading image", err);
  85106. };
  85107. img.src = this.url;
  85108. };
  85109. return ImageAssetTask;
  85110. }(AbstractAssetTask));
  85111. BABYLON.ImageAssetTask = ImageAssetTask;
  85112. /**
  85113. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  85114. */
  85115. var TextureAssetTask = /** @class */ (function (_super) {
  85116. __extends(TextureAssetTask, _super);
  85117. /**
  85118. * Creates a new TextureAssetTask object
  85119. * @param name defines the name of the task
  85120. * @param url defines the location of the file to load
  85121. * @param noMipmap defines if mipmap should not be generated (default is false)
  85122. * @param invertY defines if texture must be inverted on Y axis (default is false)
  85123. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85124. */
  85125. function TextureAssetTask(
  85126. /**
  85127. * Defines the name of the task
  85128. */
  85129. name,
  85130. /**
  85131. * Defines the location of the file to load
  85132. */
  85133. url,
  85134. /**
  85135. * Defines if mipmap should not be generated (default is false)
  85136. */
  85137. noMipmap,
  85138. /**
  85139. * Defines if texture must be inverted on Y axis (default is false)
  85140. */
  85141. invertY,
  85142. /**
  85143. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  85144. */
  85145. samplingMode) {
  85146. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  85147. var _this = _super.call(this, name) || this;
  85148. _this.name = name;
  85149. _this.url = url;
  85150. _this.noMipmap = noMipmap;
  85151. _this.invertY = invertY;
  85152. _this.samplingMode = samplingMode;
  85153. return _this;
  85154. }
  85155. /**
  85156. * Execute the current task
  85157. * @param scene defines the scene where you want your assets to be loaded
  85158. * @param onSuccess is a callback called when the task is successfully executed
  85159. * @param onError is a callback called if an error occurs
  85160. */
  85161. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85162. var onload = function () {
  85163. onSuccess();
  85164. };
  85165. var onerror = function (message, exception) {
  85166. onError(message, exception);
  85167. };
  85168. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  85169. };
  85170. return TextureAssetTask;
  85171. }(AbstractAssetTask));
  85172. BABYLON.TextureAssetTask = TextureAssetTask;
  85173. /**
  85174. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  85175. */
  85176. var CubeTextureAssetTask = /** @class */ (function (_super) {
  85177. __extends(CubeTextureAssetTask, _super);
  85178. /**
  85179. * Creates a new CubeTextureAssetTask
  85180. * @param name defines the name of the task
  85181. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85182. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85183. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85184. * @param files defines the explicit list of files (undefined by default)
  85185. */
  85186. function CubeTextureAssetTask(
  85187. /**
  85188. * Defines the name of the task
  85189. */
  85190. name,
  85191. /**
  85192. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  85193. */
  85194. url,
  85195. /**
  85196. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  85197. */
  85198. extensions,
  85199. /**
  85200. * Defines if mipmaps should not be generated (default is false)
  85201. */
  85202. noMipmap,
  85203. /**
  85204. * Defines the explicit list of files (undefined by default)
  85205. */
  85206. files) {
  85207. var _this = _super.call(this, name) || this;
  85208. _this.name = name;
  85209. _this.url = url;
  85210. _this.extensions = extensions;
  85211. _this.noMipmap = noMipmap;
  85212. _this.files = files;
  85213. return _this;
  85214. }
  85215. /**
  85216. * Execute the current task
  85217. * @param scene defines the scene where you want your assets to be loaded
  85218. * @param onSuccess is a callback called when the task is successfully executed
  85219. * @param onError is a callback called if an error occurs
  85220. */
  85221. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  85222. var onload = function () {
  85223. onSuccess();
  85224. };
  85225. var onerror = function (message, exception) {
  85226. onError(message, exception);
  85227. };
  85228. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  85229. };
  85230. return CubeTextureAssetTask;
  85231. }(AbstractAssetTask));
  85232. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  85233. /**
  85234. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  85235. */
  85236. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  85237. __extends(HDRCubeTextureAssetTask, _super);
  85238. /**
  85239. * Creates a new HDRCubeTextureAssetTask object
  85240. * @param name defines the name of the task
  85241. * @param url defines the location of the file to load
  85242. * @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.
  85243. * @param noMipmap defines if mipmaps should not be generated (default is false)
  85244. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85245. * @param useInGammaSpace 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)
  85246. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85247. */
  85248. function HDRCubeTextureAssetTask(
  85249. /**
  85250. * Defines the name of the task
  85251. */
  85252. name,
  85253. /**
  85254. * Defines the location of the file to load
  85255. */
  85256. url,
  85257. /**
  85258. * 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.
  85259. */
  85260. size,
  85261. /**
  85262. * Defines if mipmaps should not be generated (default is false)
  85263. */
  85264. noMipmap,
  85265. /**
  85266. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  85267. */
  85268. generateHarmonics,
  85269. /**
  85270. * 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)
  85271. */
  85272. useInGammaSpace,
  85273. /**
  85274. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  85275. */
  85276. usePMREMGenerator) {
  85277. if (noMipmap === void 0) { noMipmap = false; }
  85278. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85279. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  85280. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  85281. var _this = _super.call(this, name) || this;
  85282. _this.name = name;
  85283. _this.url = url;
  85284. _this.size = size;
  85285. _this.noMipmap = noMipmap;
  85286. _this.generateHarmonics = generateHarmonics;
  85287. _this.useInGammaSpace = useInGammaSpace;
  85288. _this.usePMREMGenerator = usePMREMGenerator;
  85289. return _this;
  85290. }
  85291. /**
  85292. * Execute the current task
  85293. * @param scene defines the scene where you want your assets to be loaded
  85294. * @param onSuccess is a callback called when the task is successfully executed
  85295. * @param onError is a callback called if an error occurs
  85296. */
  85297. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  85298. var onload = function () {
  85299. onSuccess();
  85300. };
  85301. var onerror = function (message, exception) {
  85302. onError(message, exception);
  85303. };
  85304. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  85305. };
  85306. return HDRCubeTextureAssetTask;
  85307. }(AbstractAssetTask));
  85308. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  85309. /**
  85310. * This class can be used to easily import assets into a scene
  85311. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  85312. */
  85313. var AssetsManager = /** @class */ (function () {
  85314. /**
  85315. * Creates a new AssetsManager
  85316. * @param scene defines the scene to work on
  85317. */
  85318. function AssetsManager(scene) {
  85319. this._isLoading = false;
  85320. this._tasks = new Array();
  85321. this._waitingTasksCount = 0;
  85322. this._totalTasksCount = 0;
  85323. /**
  85324. * Observable called when all tasks are processed
  85325. */
  85326. this.onTaskSuccessObservable = new BABYLON.Observable();
  85327. /**
  85328. * Observable called when a task had an error
  85329. */
  85330. this.onTaskErrorObservable = new BABYLON.Observable();
  85331. /**
  85332. * Observable called when a task is successful
  85333. */
  85334. this.onTasksDoneObservable = new BABYLON.Observable();
  85335. /**
  85336. * Observable called when a task is done (whatever the result is)
  85337. */
  85338. this.onProgressObservable = new BABYLON.Observable();
  85339. /**
  85340. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  85341. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  85342. */
  85343. this.useDefaultLoadingScreen = true;
  85344. this._scene = scene;
  85345. }
  85346. /**
  85347. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  85348. * @param taskName defines the name of the new task
  85349. * @param meshesNames defines the name of meshes to load
  85350. * @param rootUrl defines the root url to use to locate files
  85351. * @param sceneFilename defines the filename of the scene file
  85352. * @returns a new {BABYLON.MeshAssetTask} object
  85353. */
  85354. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  85355. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  85356. this._tasks.push(task);
  85357. return task;
  85358. };
  85359. /**
  85360. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  85361. * @param taskName defines the name of the new task
  85362. * @param url defines the url of the file to load
  85363. * @returns a new {BABYLON.TextFileAssetTask} object
  85364. */
  85365. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  85366. var task = new TextFileAssetTask(taskName, url);
  85367. this._tasks.push(task);
  85368. return task;
  85369. };
  85370. /**
  85371. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  85372. * @param taskName defines the name of the new task
  85373. * @param url defines the url of the file to load
  85374. * @returns a new {BABYLON.BinaryFileAssetTask} object
  85375. */
  85376. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  85377. var task = new BinaryFileAssetTask(taskName, url);
  85378. this._tasks.push(task);
  85379. return task;
  85380. };
  85381. /**
  85382. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  85383. * @param taskName defines the name of the new task
  85384. * @param url defines the url of the file to load
  85385. * @returns a new {BABYLON.ImageAssetTask} object
  85386. */
  85387. AssetsManager.prototype.addImageTask = function (taskName, url) {
  85388. var task = new ImageAssetTask(taskName, url);
  85389. this._tasks.push(task);
  85390. return task;
  85391. };
  85392. /**
  85393. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  85394. * @param taskName defines the name of the new task
  85395. * @param url defines the url of the file to load
  85396. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85397. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  85398. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  85399. * @returns a new {BABYLON.TextureAssetTask} object
  85400. */
  85401. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  85402. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  85403. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  85404. this._tasks.push(task);
  85405. return task;
  85406. };
  85407. /**
  85408. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  85409. * @param taskName defines the name of the new task
  85410. * @param url defines the url of the file to load
  85411. * @param extensions defines the extension to use to load the cube map (can be null)
  85412. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85413. * @param files defines the list of files to load (can be null)
  85414. * @returns a new {BABYLON.CubeTextureAssetTask} object
  85415. */
  85416. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  85417. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  85418. this._tasks.push(task);
  85419. return task;
  85420. };
  85421. /**
  85422. *
  85423. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  85424. * @param taskName defines the name of the new task
  85425. * @param url defines the url of the file to load
  85426. * @param size defines the size you want for the cubemap (can be null)
  85427. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  85428. * @param generateHarmonics defines if you want to automatically generate (true by default)
  85429. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  85430. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  85431. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  85432. */
  85433. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  85434. if (noMipmap === void 0) { noMipmap = false; }
  85435. if (generateHarmonics === void 0) { generateHarmonics = true; }
  85436. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  85437. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  85438. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  85439. this._tasks.push(task);
  85440. return task;
  85441. };
  85442. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  85443. var _this = this;
  85444. this._waitingTasksCount--;
  85445. try {
  85446. if (task.taskState === AssetTaskState.DONE) {
  85447. // Let's remove successfull tasks
  85448. BABYLON.Tools.SetImmediate(function () {
  85449. var index = _this._tasks.indexOf(task);
  85450. if (index > -1) {
  85451. _this._tasks.splice(index, 1);
  85452. }
  85453. });
  85454. }
  85455. if (this.onProgress) {
  85456. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  85457. }
  85458. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  85459. }
  85460. catch (e) {
  85461. BABYLON.Tools.Error("Error running progress callbacks.");
  85462. console.log(e);
  85463. }
  85464. if (this._waitingTasksCount === 0) {
  85465. try {
  85466. if (this.onFinish) {
  85467. this.onFinish(this._tasks);
  85468. }
  85469. this.onTasksDoneObservable.notifyObservers(this._tasks);
  85470. }
  85471. catch (e) {
  85472. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  85473. console.log(e);
  85474. }
  85475. this._isLoading = false;
  85476. this._scene.getEngine().hideLoadingUI();
  85477. }
  85478. };
  85479. AssetsManager.prototype._runTask = function (task) {
  85480. var _this = this;
  85481. var done = function () {
  85482. try {
  85483. if (_this.onTaskSuccess) {
  85484. _this.onTaskSuccess(task);
  85485. }
  85486. _this.onTaskSuccessObservable.notifyObservers(task);
  85487. _this._decreaseWaitingTasksCount(task);
  85488. }
  85489. catch (e) {
  85490. error("Error executing task success callbacks", e);
  85491. }
  85492. };
  85493. var error = function (message, exception) {
  85494. task._setErrorObject(message, exception);
  85495. if (_this.onTaskError) {
  85496. _this.onTaskError(task);
  85497. }
  85498. _this.onTaskErrorObservable.notifyObservers(task);
  85499. _this._decreaseWaitingTasksCount(task);
  85500. };
  85501. task.run(this._scene, done, error);
  85502. };
  85503. /**
  85504. * Reset the {BABYLON.AssetsManager} and remove all tasks
  85505. * @return the current instance of the {BABYLON.AssetsManager}
  85506. */
  85507. AssetsManager.prototype.reset = function () {
  85508. this._isLoading = false;
  85509. this._tasks = new Array();
  85510. return this;
  85511. };
  85512. /**
  85513. * Start the loading process
  85514. * @return the current instance of the {BABYLON.AssetsManager}
  85515. */
  85516. AssetsManager.prototype.load = function () {
  85517. if (this._isLoading) {
  85518. return this;
  85519. }
  85520. this._isLoading = true;
  85521. this._waitingTasksCount = this._tasks.length;
  85522. this._totalTasksCount = this._tasks.length;
  85523. if (this._waitingTasksCount === 0) {
  85524. this._isLoading = false;
  85525. if (this.onFinish) {
  85526. this.onFinish(this._tasks);
  85527. }
  85528. this.onTasksDoneObservable.notifyObservers(this._tasks);
  85529. return this;
  85530. }
  85531. if (this.useDefaultLoadingScreen) {
  85532. this._scene.getEngine().displayLoadingUI();
  85533. }
  85534. for (var index = 0; index < this._tasks.length; index++) {
  85535. var task = this._tasks[index];
  85536. this._runTask(task);
  85537. }
  85538. return this;
  85539. };
  85540. return AssetsManager;
  85541. }());
  85542. BABYLON.AssetsManager = AssetsManager;
  85543. })(BABYLON || (BABYLON = {}));
  85544. //# sourceMappingURL=babylon.assetsManager.js.map
  85545. var BABYLON;
  85546. (function (BABYLON) {
  85547. var serializedGeometries = [];
  85548. var serializeGeometry = function (geometry, serializationGeometries) {
  85549. if (serializedGeometries[geometry.id]) {
  85550. return;
  85551. }
  85552. if (geometry.doNotSerialize) {
  85553. return;
  85554. }
  85555. if (geometry instanceof BABYLON.BoxGeometry) {
  85556. serializationGeometries.boxes.push(geometry.serialize());
  85557. }
  85558. else if (geometry instanceof BABYLON.SphereGeometry) {
  85559. serializationGeometries.spheres.push(geometry.serialize());
  85560. }
  85561. else if (geometry instanceof BABYLON.CylinderGeometry) {
  85562. serializationGeometries.cylinders.push(geometry.serialize());
  85563. }
  85564. else if (geometry instanceof BABYLON.TorusGeometry) {
  85565. serializationGeometries.toruses.push(geometry.serialize());
  85566. }
  85567. else if (geometry instanceof BABYLON.GroundGeometry) {
  85568. serializationGeometries.grounds.push(geometry.serialize());
  85569. }
  85570. else if (geometry instanceof BABYLON.Plane) {
  85571. serializationGeometries.planes.push(geometry.serialize());
  85572. }
  85573. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  85574. serializationGeometries.torusKnots.push(geometry.serialize());
  85575. }
  85576. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  85577. throw new Error("Unknown primitive type");
  85578. }
  85579. else {
  85580. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  85581. }
  85582. serializedGeometries[geometry.id] = true;
  85583. };
  85584. var serializeMesh = function (mesh, serializationScene) {
  85585. var serializationObject = {};
  85586. // Geometry
  85587. var geometry = mesh._geometry;
  85588. if (geometry) {
  85589. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  85590. // 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
  85591. serializeGeometry(geometry, serializationScene.geometries);
  85592. }
  85593. }
  85594. // Custom
  85595. if (mesh.serialize) {
  85596. mesh.serialize(serializationObject);
  85597. }
  85598. return serializationObject;
  85599. };
  85600. var finalizeSingleMesh = function (mesh, serializationObject) {
  85601. //only works if the mesh is already loaded
  85602. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  85603. //serialize material
  85604. if (mesh.material) {
  85605. if (mesh.material instanceof BABYLON.StandardMaterial) {
  85606. serializationObject.materials = serializationObject.materials || [];
  85607. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  85608. serializationObject.materials.push(mesh.material.serialize());
  85609. }
  85610. }
  85611. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  85612. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  85613. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  85614. serializationObject.multiMaterials.push(mesh.material.serialize());
  85615. }
  85616. }
  85617. }
  85618. //serialize geometry
  85619. var geometry = mesh._geometry;
  85620. if (geometry) {
  85621. if (!serializationObject.geometries) {
  85622. serializationObject.geometries = {};
  85623. serializationObject.geometries.boxes = [];
  85624. serializationObject.geometries.spheres = [];
  85625. serializationObject.geometries.cylinders = [];
  85626. serializationObject.geometries.toruses = [];
  85627. serializationObject.geometries.grounds = [];
  85628. serializationObject.geometries.planes = [];
  85629. serializationObject.geometries.torusKnots = [];
  85630. serializationObject.geometries.vertexData = [];
  85631. }
  85632. serializeGeometry(geometry, serializationObject.geometries);
  85633. }
  85634. // Skeletons
  85635. if (mesh.skeleton) {
  85636. serializationObject.skeletons = serializationObject.skeletons || [];
  85637. serializationObject.skeletons.push(mesh.skeleton.serialize());
  85638. }
  85639. //serialize the actual mesh
  85640. serializationObject.meshes = serializationObject.meshes || [];
  85641. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  85642. }
  85643. };
  85644. var SceneSerializer = /** @class */ (function () {
  85645. function SceneSerializer() {
  85646. }
  85647. SceneSerializer.ClearCache = function () {
  85648. serializedGeometries = [];
  85649. };
  85650. SceneSerializer.Serialize = function (scene) {
  85651. var serializationObject = {};
  85652. SceneSerializer.ClearCache();
  85653. // Scene
  85654. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  85655. serializationObject.autoClear = scene.autoClear;
  85656. serializationObject.clearColor = scene.clearColor.asArray();
  85657. serializationObject.ambientColor = scene.ambientColor.asArray();
  85658. serializationObject.gravity = scene.gravity.asArray();
  85659. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  85660. serializationObject.workerCollisions = scene.workerCollisions;
  85661. // Fog
  85662. if (scene.fogMode && scene.fogMode !== 0) {
  85663. serializationObject.fogMode = scene.fogMode;
  85664. serializationObject.fogColor = scene.fogColor.asArray();
  85665. serializationObject.fogStart = scene.fogStart;
  85666. serializationObject.fogEnd = scene.fogEnd;
  85667. serializationObject.fogDensity = scene.fogDensity;
  85668. }
  85669. //Physics
  85670. if (scene.isPhysicsEnabled()) {
  85671. var physicEngine = scene.getPhysicsEngine();
  85672. if (physicEngine) {
  85673. serializationObject.physicsEnabled = true;
  85674. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  85675. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  85676. }
  85677. }
  85678. // Metadata
  85679. if (scene.metadata) {
  85680. serializationObject.metadata = scene.metadata;
  85681. }
  85682. // Morph targets
  85683. serializationObject.morphTargetManagers = [];
  85684. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  85685. var abstractMesh = _a[_i];
  85686. var manager = abstractMesh.morphTargetManager;
  85687. if (manager) {
  85688. serializationObject.morphTargetManagers.push(manager.serialize());
  85689. }
  85690. }
  85691. // Lights
  85692. serializationObject.lights = [];
  85693. var index;
  85694. var light;
  85695. for (index = 0; index < scene.lights.length; index++) {
  85696. light = scene.lights[index];
  85697. if (!light.doNotSerialize) {
  85698. serializationObject.lights.push(light.serialize());
  85699. }
  85700. }
  85701. // Cameras
  85702. serializationObject.cameras = [];
  85703. for (index = 0; index < scene.cameras.length; index++) {
  85704. var camera = scene.cameras[index];
  85705. if (!camera.doNotSerialize) {
  85706. serializationObject.cameras.push(camera.serialize());
  85707. }
  85708. }
  85709. if (scene.activeCamera) {
  85710. serializationObject.activeCameraID = scene.activeCamera.id;
  85711. }
  85712. // Animations
  85713. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  85714. // Materials
  85715. serializationObject.materials = [];
  85716. serializationObject.multiMaterials = [];
  85717. var material;
  85718. for (index = 0; index < scene.materials.length; index++) {
  85719. material = scene.materials[index];
  85720. if (!material.doNotSerialize) {
  85721. serializationObject.materials.push(material.serialize());
  85722. }
  85723. }
  85724. // MultiMaterials
  85725. serializationObject.multiMaterials = [];
  85726. for (index = 0; index < scene.multiMaterials.length; index++) {
  85727. var multiMaterial = scene.multiMaterials[index];
  85728. serializationObject.multiMaterials.push(multiMaterial.serialize());
  85729. }
  85730. // Environment texture
  85731. if (scene.environmentTexture) {
  85732. serializationObject.environmentTexture = scene.environmentTexture.name;
  85733. }
  85734. // Skeletons
  85735. serializationObject.skeletons = [];
  85736. for (index = 0; index < scene.skeletons.length; index++) {
  85737. var skeleton = scene.skeletons[index];
  85738. if (!skeleton.doNotSerialize) {
  85739. serializationObject.skeletons.push(skeleton.serialize());
  85740. }
  85741. }
  85742. // Transform nodes
  85743. serializationObject.transformNodes = [];
  85744. for (index = 0; index < scene.transformNodes.length; index++) {
  85745. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  85746. }
  85747. // Geometries
  85748. serializationObject.geometries = {};
  85749. serializationObject.geometries.boxes = [];
  85750. serializationObject.geometries.spheres = [];
  85751. serializationObject.geometries.cylinders = [];
  85752. serializationObject.geometries.toruses = [];
  85753. serializationObject.geometries.grounds = [];
  85754. serializationObject.geometries.planes = [];
  85755. serializationObject.geometries.torusKnots = [];
  85756. serializationObject.geometries.vertexData = [];
  85757. serializedGeometries = [];
  85758. var geometries = scene.getGeometries();
  85759. for (index = 0; index < geometries.length; index++) {
  85760. var geometry = geometries[index];
  85761. if (geometry.isReady()) {
  85762. serializeGeometry(geometry, serializationObject.geometries);
  85763. }
  85764. }
  85765. // Meshes
  85766. serializationObject.meshes = [];
  85767. for (index = 0; index < scene.meshes.length; index++) {
  85768. var abstractMesh = scene.meshes[index];
  85769. if (abstractMesh instanceof BABYLON.Mesh) {
  85770. var mesh = abstractMesh;
  85771. if (!mesh.doNotSerialize) {
  85772. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  85773. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  85774. }
  85775. }
  85776. }
  85777. }
  85778. // Particles Systems
  85779. serializationObject.particleSystems = [];
  85780. for (index = 0; index < scene.particleSystems.length; index++) {
  85781. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  85782. }
  85783. // Lens flares
  85784. serializationObject.lensFlareSystems = [];
  85785. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  85786. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  85787. }
  85788. // Shadows
  85789. serializationObject.shadowGenerators = [];
  85790. for (index = 0; index < scene.lights.length; index++) {
  85791. light = scene.lights[index];
  85792. var shadowGenerator = light.getShadowGenerator();
  85793. if (shadowGenerator) {
  85794. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  85795. }
  85796. }
  85797. // Action Manager
  85798. if (scene.actionManager) {
  85799. serializationObject.actions = scene.actionManager.serialize("scene");
  85800. }
  85801. // Audio
  85802. serializationObject.sounds = [];
  85803. for (index = 0; index < scene.soundTracks.length; index++) {
  85804. var soundtrack = scene.soundTracks[index];
  85805. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  85806. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  85807. }
  85808. }
  85809. return serializationObject;
  85810. };
  85811. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  85812. if (withParents === void 0) { withParents = false; }
  85813. if (withChildren === void 0) { withChildren = false; }
  85814. var serializationObject = {};
  85815. SceneSerializer.ClearCache();
  85816. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  85817. if (withParents || withChildren) {
  85818. //deliberate for loop! not for each, appended should be processed as well.
  85819. for (var i = 0; i < toSerialize.length; ++i) {
  85820. if (withChildren) {
  85821. toSerialize[i].getDescendants().forEach(function (node) {
  85822. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  85823. toSerialize.push(node);
  85824. }
  85825. });
  85826. }
  85827. //make sure the array doesn't contain the object already
  85828. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  85829. toSerialize.push(toSerialize[i].parent);
  85830. }
  85831. }
  85832. }
  85833. toSerialize.forEach(function (mesh) {
  85834. finalizeSingleMesh(mesh, serializationObject);
  85835. });
  85836. return serializationObject;
  85837. };
  85838. return SceneSerializer;
  85839. }());
  85840. BABYLON.SceneSerializer = SceneSerializer;
  85841. })(BABYLON || (BABYLON = {}));
  85842. //# sourceMappingURL=babylon.sceneSerializer.js.map
  85843. var BABYLON;
  85844. (function (BABYLON) {
  85845. var ReflectionProbe = /** @class */ (function () {
  85846. function ReflectionProbe(name, size, scene, generateMipMaps) {
  85847. if (generateMipMaps === void 0) { generateMipMaps = true; }
  85848. var _this = this;
  85849. this.name = name;
  85850. this._viewMatrix = BABYLON.Matrix.Identity();
  85851. this._target = BABYLON.Vector3.Zero();
  85852. this._add = BABYLON.Vector3.Zero();
  85853. this.invertYAxis = false;
  85854. this.position = BABYLON.Vector3.Zero();
  85855. this._scene = scene;
  85856. this._scene.reflectionProbes.push(this);
  85857. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  85858. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  85859. switch (faceIndex) {
  85860. case 0:
  85861. _this._add.copyFromFloats(1, 0, 0);
  85862. break;
  85863. case 1:
  85864. _this._add.copyFromFloats(-1, 0, 0);
  85865. break;
  85866. case 2:
  85867. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  85868. break;
  85869. case 3:
  85870. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  85871. break;
  85872. case 4:
  85873. _this._add.copyFromFloats(0, 0, 1);
  85874. break;
  85875. case 5:
  85876. _this._add.copyFromFloats(0, 0, -1);
  85877. break;
  85878. }
  85879. if (_this._attachedMesh) {
  85880. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  85881. }
  85882. _this.position.addToRef(_this._add, _this._target);
  85883. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  85884. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  85885. scene._forcedViewPosition = _this.position;
  85886. });
  85887. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  85888. scene._forcedViewPosition = null;
  85889. scene.updateTransformMatrix(true);
  85890. });
  85891. if (scene.activeCamera) {
  85892. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  85893. }
  85894. }
  85895. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  85896. get: function () {
  85897. return this._renderTargetTexture.samples;
  85898. },
  85899. set: function (value) {
  85900. this._renderTargetTexture.samples = value;
  85901. },
  85902. enumerable: true,
  85903. configurable: true
  85904. });
  85905. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  85906. get: function () {
  85907. return this._renderTargetTexture.refreshRate;
  85908. },
  85909. set: function (value) {
  85910. this._renderTargetTexture.refreshRate = value;
  85911. },
  85912. enumerable: true,
  85913. configurable: true
  85914. });
  85915. ReflectionProbe.prototype.getScene = function () {
  85916. return this._scene;
  85917. };
  85918. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  85919. get: function () {
  85920. return this._renderTargetTexture;
  85921. },
  85922. enumerable: true,
  85923. configurable: true
  85924. });
  85925. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  85926. get: function () {
  85927. return this._renderTargetTexture.renderList;
  85928. },
  85929. enumerable: true,
  85930. configurable: true
  85931. });
  85932. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  85933. this._attachedMesh = mesh;
  85934. };
  85935. /**
  85936. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  85937. *
  85938. * @param renderingGroupId The rendering group id corresponding to its index
  85939. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  85940. */
  85941. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  85942. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  85943. };
  85944. ReflectionProbe.prototype.dispose = function () {
  85945. var index = this._scene.reflectionProbes.indexOf(this);
  85946. if (index !== -1) {
  85947. // Remove from the scene if found
  85948. this._scene.reflectionProbes.splice(index, 1);
  85949. }
  85950. if (this._renderTargetTexture) {
  85951. this._renderTargetTexture.dispose();
  85952. this._renderTargetTexture = null;
  85953. }
  85954. };
  85955. return ReflectionProbe;
  85956. }());
  85957. BABYLON.ReflectionProbe = ReflectionProbe;
  85958. })(BABYLON || (BABYLON = {}));
  85959. //# sourceMappingURL=babylon.reflectionProbe.js.map
  85960. var BABYLON;
  85961. (function (BABYLON) {
  85962. var Layer = /** @class */ (function () {
  85963. function Layer(name, imgUrl, scene, isBackground, color) {
  85964. this.name = name;
  85965. this.scale = new BABYLON.Vector2(1, 1);
  85966. this.offset = new BABYLON.Vector2(0, 0);
  85967. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  85968. this.layerMask = 0x0FFFFFFF;
  85969. this._vertexBuffers = {};
  85970. // Events
  85971. /**
  85972. * An event triggered when the layer is disposed.
  85973. * @type {BABYLON.Observable}
  85974. */
  85975. this.onDisposeObservable = new BABYLON.Observable();
  85976. /**
  85977. * An event triggered before rendering the scene
  85978. * @type {BABYLON.Observable}
  85979. */
  85980. this.onBeforeRenderObservable = new BABYLON.Observable();
  85981. /**
  85982. * An event triggered after rendering the scene
  85983. * @type {BABYLON.Observable}
  85984. */
  85985. this.onAfterRenderObservable = new BABYLON.Observable();
  85986. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  85987. this.isBackground = isBackground === undefined ? true : isBackground;
  85988. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  85989. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  85990. this._scene.layers.push(this);
  85991. var engine = this._scene.getEngine();
  85992. // VBO
  85993. var vertices = [];
  85994. vertices.push(1, 1);
  85995. vertices.push(-1, 1);
  85996. vertices.push(-1, -1);
  85997. vertices.push(1, -1);
  85998. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  85999. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86000. this._createIndexBuffer();
  86001. // Effects
  86002. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  86003. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  86004. }
  86005. Object.defineProperty(Layer.prototype, "onDispose", {
  86006. set: function (callback) {
  86007. if (this._onDisposeObserver) {
  86008. this.onDisposeObservable.remove(this._onDisposeObserver);
  86009. }
  86010. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  86011. },
  86012. enumerable: true,
  86013. configurable: true
  86014. });
  86015. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  86016. set: function (callback) {
  86017. if (this._onBeforeRenderObserver) {
  86018. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  86019. }
  86020. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  86021. },
  86022. enumerable: true,
  86023. configurable: true
  86024. });
  86025. Object.defineProperty(Layer.prototype, "onAfterRender", {
  86026. set: function (callback) {
  86027. if (this._onAfterRenderObserver) {
  86028. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  86029. }
  86030. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  86031. },
  86032. enumerable: true,
  86033. configurable: true
  86034. });
  86035. Layer.prototype._createIndexBuffer = function () {
  86036. var engine = this._scene.getEngine();
  86037. // Indices
  86038. var indices = [];
  86039. indices.push(0);
  86040. indices.push(1);
  86041. indices.push(2);
  86042. indices.push(0);
  86043. indices.push(2);
  86044. indices.push(3);
  86045. this._indexBuffer = engine.createIndexBuffer(indices);
  86046. };
  86047. Layer.prototype._rebuild = function () {
  86048. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86049. if (vb) {
  86050. vb._rebuild();
  86051. }
  86052. this._createIndexBuffer();
  86053. };
  86054. Layer.prototype.render = function () {
  86055. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  86056. // Check
  86057. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  86058. return;
  86059. var engine = this._scene.getEngine();
  86060. this.onBeforeRenderObservable.notifyObservers(this);
  86061. // Render
  86062. engine.enableEffect(currentEffect);
  86063. engine.setState(false);
  86064. // Texture
  86065. currentEffect.setTexture("textureSampler", this.texture);
  86066. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  86067. // Color
  86068. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  86069. // Scale / offset
  86070. currentEffect.setVector2("offset", this.offset);
  86071. currentEffect.setVector2("scale", this.scale);
  86072. // VBOs
  86073. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86074. // Draw order
  86075. if (!this.alphaTest) {
  86076. engine.setAlphaMode(this.alphaBlendingMode);
  86077. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86078. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  86079. }
  86080. else {
  86081. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86082. }
  86083. this.onAfterRenderObservable.notifyObservers(this);
  86084. };
  86085. Layer.prototype.dispose = function () {
  86086. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86087. if (vertexBuffer) {
  86088. vertexBuffer.dispose();
  86089. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86090. }
  86091. if (this._indexBuffer) {
  86092. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86093. this._indexBuffer = null;
  86094. }
  86095. if (this.texture) {
  86096. this.texture.dispose();
  86097. this.texture = null;
  86098. }
  86099. // Remove from scene
  86100. var index = this._scene.layers.indexOf(this);
  86101. this._scene.layers.splice(index, 1);
  86102. // Callback
  86103. this.onDisposeObservable.notifyObservers(this);
  86104. this.onDisposeObservable.clear();
  86105. this.onAfterRenderObservable.clear();
  86106. this.onBeforeRenderObservable.clear();
  86107. };
  86108. return Layer;
  86109. }());
  86110. BABYLON.Layer = Layer;
  86111. })(BABYLON || (BABYLON = {}));
  86112. //# sourceMappingURL=babylon.layer.js.map
  86113. var BABYLON;
  86114. (function (BABYLON) {
  86115. var TextureTools = /** @class */ (function () {
  86116. function TextureTools() {
  86117. }
  86118. /**
  86119. * Uses the GPU to create a copy texture rescaled at a given size
  86120. * @param texture Texture to copy from
  86121. * @param width Desired width
  86122. * @param height Desired height
  86123. * @return Generated texture
  86124. */
  86125. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  86126. if (useBilinearMode === void 0) { useBilinearMode = true; }
  86127. var scene = texture.getScene();
  86128. var engine = scene.getEngine();
  86129. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  86130. rtt.wrapU = texture.wrapU;
  86131. rtt.wrapV = texture.wrapV;
  86132. rtt.uOffset = texture.uOffset;
  86133. rtt.vOffset = texture.vOffset;
  86134. rtt.uScale = texture.uScale;
  86135. rtt.vScale = texture.vScale;
  86136. rtt.uAng = texture.uAng;
  86137. rtt.vAng = texture.vAng;
  86138. rtt.wAng = texture.wAng;
  86139. rtt.coordinatesIndex = texture.coordinatesIndex;
  86140. rtt.level = texture.level;
  86141. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  86142. rtt._texture.isReady = false;
  86143. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86144. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86145. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86146. passPostProcess.getEffect().executeWhenCompiled(function () {
  86147. passPostProcess.onApply = function (effect) {
  86148. effect.setTexture("textureSampler", texture);
  86149. };
  86150. var internalTexture = rtt.getInternalTexture();
  86151. if (internalTexture) {
  86152. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  86153. engine.unBindFramebuffer(internalTexture);
  86154. rtt.disposeFramebufferObjects();
  86155. passPostProcess.dispose();
  86156. internalTexture.isReady = true;
  86157. }
  86158. });
  86159. return rtt;
  86160. };
  86161. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  86162. if (!scene._environmentBRDFTexture) {
  86163. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86164. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86165. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86166. scene._environmentBRDFTexture = texture;
  86167. }
  86168. return scene._environmentBRDFTexture;
  86169. };
  86170. 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=";
  86171. return TextureTools;
  86172. }());
  86173. BABYLON.TextureTools = TextureTools;
  86174. })(BABYLON || (BABYLON = {}));
  86175. //# sourceMappingURL=babylon.textureTools.js.map
  86176. var BABYLON;
  86177. (function (BABYLON) {
  86178. var FramingBehavior = /** @class */ (function () {
  86179. function FramingBehavior() {
  86180. this._mode = FramingBehavior.FitFrustumSidesMode;
  86181. this._radiusScale = 1.0;
  86182. this._positionScale = 0.5;
  86183. this._defaultElevation = 0.3;
  86184. this._elevationReturnTime = 1500;
  86185. this._elevationReturnWaitTime = 1000;
  86186. this._zoomStopsAnimation = false;
  86187. this._framingTime = 1500;
  86188. this._isPointerDown = false;
  86189. this._lastInteractionTime = -Infinity;
  86190. // Framing control
  86191. this._animatables = new Array();
  86192. this._betaIsAnimating = false;
  86193. }
  86194. Object.defineProperty(FramingBehavior.prototype, "name", {
  86195. get: function () {
  86196. return "Framing";
  86197. },
  86198. enumerable: true,
  86199. configurable: true
  86200. });
  86201. Object.defineProperty(FramingBehavior.prototype, "mode", {
  86202. /**
  86203. * Gets current mode used by the behavior.
  86204. */
  86205. get: function () {
  86206. return this._mode;
  86207. },
  86208. /**
  86209. * Sets the current mode used by the behavior
  86210. */
  86211. set: function (mode) {
  86212. this._mode = mode;
  86213. },
  86214. enumerable: true,
  86215. configurable: true
  86216. });
  86217. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  86218. /**
  86219. * Gets the scale applied to the radius
  86220. */
  86221. get: function () {
  86222. return this._radiusScale;
  86223. },
  86224. /**
  86225. * Sets the scale applied to the radius (1 by default)
  86226. */
  86227. set: function (radius) {
  86228. this._radiusScale = radius;
  86229. },
  86230. enumerable: true,
  86231. configurable: true
  86232. });
  86233. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  86234. /**
  86235. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86236. */
  86237. get: function () {
  86238. return this._positionScale;
  86239. },
  86240. /**
  86241. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  86242. */
  86243. set: function (scale) {
  86244. this._positionScale = scale;
  86245. },
  86246. enumerable: true,
  86247. configurable: true
  86248. });
  86249. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  86250. /**
  86251. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86252. * behaviour is triggered, in radians.
  86253. */
  86254. get: function () {
  86255. return this._defaultElevation;
  86256. },
  86257. /**
  86258. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  86259. * behaviour is triggered, in radians.
  86260. */
  86261. set: function (elevation) {
  86262. this._defaultElevation = elevation;
  86263. },
  86264. enumerable: true,
  86265. configurable: true
  86266. });
  86267. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  86268. /**
  86269. * Gets the time (in milliseconds) taken to return to the default beta position.
  86270. * Negative value indicates camera should not return to default.
  86271. */
  86272. get: function () {
  86273. return this._elevationReturnTime;
  86274. },
  86275. /**
  86276. * Sets the time (in milliseconds) taken to return to the default beta position.
  86277. * Negative value indicates camera should not return to default.
  86278. */
  86279. set: function (speed) {
  86280. this._elevationReturnTime = speed;
  86281. },
  86282. enumerable: true,
  86283. configurable: true
  86284. });
  86285. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  86286. /**
  86287. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86288. */
  86289. get: function () {
  86290. return this._elevationReturnWaitTime;
  86291. },
  86292. /**
  86293. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  86294. */
  86295. set: function (time) {
  86296. this._elevationReturnWaitTime = time;
  86297. },
  86298. enumerable: true,
  86299. configurable: true
  86300. });
  86301. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  86302. /**
  86303. * Gets the flag that indicates if user zooming should stop animation.
  86304. */
  86305. get: function () {
  86306. return this._zoomStopsAnimation;
  86307. },
  86308. /**
  86309. * Sets the flag that indicates if user zooming should stop animation.
  86310. */
  86311. set: function (flag) {
  86312. this._zoomStopsAnimation = flag;
  86313. },
  86314. enumerable: true,
  86315. configurable: true
  86316. });
  86317. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  86318. /**
  86319. * Gets the transition time when framing the mesh, in milliseconds
  86320. */
  86321. get: function () {
  86322. return this._framingTime;
  86323. },
  86324. /**
  86325. * Sets the transition time when framing the mesh, in milliseconds
  86326. */
  86327. set: function (time) {
  86328. this._framingTime = time;
  86329. },
  86330. enumerable: true,
  86331. configurable: true
  86332. });
  86333. FramingBehavior.prototype.init = function () {
  86334. // Do notihng
  86335. };
  86336. FramingBehavior.prototype.attach = function (camera) {
  86337. var _this = this;
  86338. this._attachedCamera = camera;
  86339. var scene = this._attachedCamera.getScene();
  86340. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  86341. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  86342. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  86343. _this._isPointerDown = true;
  86344. return;
  86345. }
  86346. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  86347. _this._isPointerDown = false;
  86348. }
  86349. });
  86350. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  86351. if (mesh) {
  86352. _this.zoomOnMesh(mesh);
  86353. }
  86354. });
  86355. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  86356. // Stop the animation if there is user interaction and the animation should stop for this interaction
  86357. _this._applyUserInteraction();
  86358. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  86359. // back to the default position after a given timeout
  86360. _this._maintainCameraAboveGround();
  86361. });
  86362. };
  86363. FramingBehavior.prototype.detach = function () {
  86364. if (!this._attachedCamera) {
  86365. return;
  86366. }
  86367. var scene = this._attachedCamera.getScene();
  86368. if (this._onPrePointerObservableObserver) {
  86369. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  86370. }
  86371. if (this._onAfterCheckInputsObserver) {
  86372. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  86373. }
  86374. if (this._onMeshTargetChangedObserver) {
  86375. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86376. }
  86377. this._attachedCamera = null;
  86378. };
  86379. /**
  86380. * Targets the given mesh and updates zoom level accordingly.
  86381. * @param mesh The mesh to target.
  86382. * @param radius Optional. If a cached radius position already exists, overrides default.
  86383. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86384. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86385. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86386. */
  86387. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  86388. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86389. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86390. mesh.computeWorldMatrix(true);
  86391. var boundingBox = mesh.getBoundingInfo().boundingBox;
  86392. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  86393. };
  86394. /**
  86395. * Targets the given mesh with its children and updates zoom level accordingly.
  86396. * @param mesh The mesh to target.
  86397. * @param radius Optional. If a cached radius position already exists, overrides default.
  86398. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86399. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86400. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86401. */
  86402. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  86403. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86404. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86405. mesh.computeWorldMatrix(true);
  86406. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  86407. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  86408. };
  86409. /**
  86410. * Targets the given meshes with their children and updates zoom level accordingly.
  86411. * @param meshes The mesh to target.
  86412. * @param radius Optional. If a cached radius position already exists, overrides default.
  86413. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86414. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86415. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86416. */
  86417. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  86418. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86419. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86420. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  86421. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  86422. for (var i = 0; i < meshes.length; i++) {
  86423. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  86424. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  86425. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  86426. }
  86427. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  86428. };
  86429. /**
  86430. * Targets the given mesh and updates zoom level accordingly.
  86431. * @param mesh The mesh to target.
  86432. * @param radius Optional. If a cached radius position already exists, overrides default.
  86433. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  86434. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  86435. * @param onAnimationEnd Callback triggered at the end of the framing animation
  86436. */
  86437. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  86438. var _this = this;
  86439. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  86440. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  86441. var zoomTarget;
  86442. if (!this._attachedCamera) {
  86443. return;
  86444. }
  86445. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  86446. var bottom = minimumWorld.y;
  86447. var top = maximumWorld.y;
  86448. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  86449. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  86450. if (focusOnOriginXZ) {
  86451. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  86452. }
  86453. else {
  86454. var centerWorld = minimumWorld.add(radiusWorld);
  86455. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  86456. }
  86457. if (!this._vectorTransition) {
  86458. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  86459. }
  86460. this._betaIsAnimating = true;
  86461. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  86462. if (animatable) {
  86463. this._animatables.push(animatable);
  86464. }
  86465. // sets the radius and lower radius bounds
  86466. // Small delta ensures camera is not always at lower zoom limit.
  86467. var radius = 0;
  86468. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  86469. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  86470. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  86471. radius = position;
  86472. }
  86473. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  86474. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  86475. if (this._attachedCamera.lowerRadiusLimit === null) {
  86476. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  86477. }
  86478. }
  86479. // Set sensibilities
  86480. var extend = maximumWorld.subtract(minimumWorld).length();
  86481. this._attachedCamera.panningSensibility = 5000 / extend;
  86482. this._attachedCamera.wheelPrecision = 100 / radius;
  86483. // transition to new radius
  86484. if (!this._radiusTransition) {
  86485. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  86486. }
  86487. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  86488. if (onAnimationEnd) {
  86489. onAnimationEnd();
  86490. }
  86491. if (_this._attachedCamera) {
  86492. _this._attachedCamera.storeState();
  86493. }
  86494. });
  86495. if (animatable) {
  86496. this._animatables.push(animatable);
  86497. }
  86498. };
  86499. /**
  86500. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  86501. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  86502. * frustum width.
  86503. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  86504. * to fully enclose the mesh in the viewing frustum.
  86505. */
  86506. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  86507. var size = maximumWorld.subtract(minimumWorld);
  86508. var boxVectorGlobalDiagonal = size.length();
  86509. var frustumSlope = this._getFrustumSlope();
  86510. // Formula for setting distance
  86511. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  86512. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  86513. // Horizon distance
  86514. var radius = radiusWithoutFraming * this._radiusScale;
  86515. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  86516. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  86517. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  86518. var camera = this._attachedCamera;
  86519. if (!camera) {
  86520. return 0;
  86521. }
  86522. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  86523. // Don't exceed the requested limit
  86524. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  86525. }
  86526. // Don't exceed the upper radius limit
  86527. if (camera.upperRadiusLimit) {
  86528. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  86529. }
  86530. return distance;
  86531. };
  86532. /**
  86533. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  86534. * is automatically returned to its default position (expected to be above ground plane).
  86535. */
  86536. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  86537. var _this = this;
  86538. if (this._elevationReturnTime < 0) {
  86539. return;
  86540. }
  86541. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  86542. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  86543. var limitBeta = Math.PI * 0.5;
  86544. // Bring the camera back up if below the ground plane
  86545. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  86546. this._betaIsAnimating = true;
  86547. //Transition to new position
  86548. this.stopAllAnimations();
  86549. if (!this._betaTransition) {
  86550. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  86551. }
  86552. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  86553. _this._clearAnimationLocks();
  86554. _this.stopAllAnimations();
  86555. });
  86556. if (animatabe) {
  86557. this._animatables.push(animatabe);
  86558. }
  86559. }
  86560. };
  86561. /**
  86562. * Returns the frustum slope based on the canvas ratio and camera FOV
  86563. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  86564. */
  86565. FramingBehavior.prototype._getFrustumSlope = function () {
  86566. // Calculate the viewport ratio
  86567. // Aspect Ratio is Height/Width.
  86568. var camera = this._attachedCamera;
  86569. if (!camera) {
  86570. return BABYLON.Vector2.Zero();
  86571. }
  86572. var engine = camera.getScene().getEngine();
  86573. var aspectRatio = engine.getAspectRatio(camera);
  86574. // Camera FOV is the vertical field of view (top-bottom) in radians.
  86575. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  86576. var frustumSlopeY = Math.tan(camera.fov / 2);
  86577. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  86578. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  86579. // along the forward vector.
  86580. var frustumSlopeX = frustumSlopeY * aspectRatio;
  86581. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  86582. };
  86583. /**
  86584. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  86585. */
  86586. FramingBehavior.prototype._clearAnimationLocks = function () {
  86587. this._betaIsAnimating = false;
  86588. };
  86589. /**
  86590. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  86591. */
  86592. FramingBehavior.prototype._applyUserInteraction = function () {
  86593. if (this.isUserIsMoving) {
  86594. this._lastInteractionTime = BABYLON.Tools.Now;
  86595. this.stopAllAnimations();
  86596. this._clearAnimationLocks();
  86597. }
  86598. };
  86599. /**
  86600. * Stops and removes all animations that have been applied to the camera
  86601. */
  86602. FramingBehavior.prototype.stopAllAnimations = function () {
  86603. if (this._attachedCamera) {
  86604. this._attachedCamera.animations = [];
  86605. }
  86606. while (this._animatables.length) {
  86607. if (this._animatables[0]) {
  86608. this._animatables[0].onAnimationEnd = null;
  86609. this._animatables[0].stop();
  86610. }
  86611. this._animatables.shift();
  86612. }
  86613. };
  86614. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  86615. /**
  86616. * Gets a value indicating if the user is moving the camera
  86617. */
  86618. get: function () {
  86619. if (!this._attachedCamera) {
  86620. return false;
  86621. }
  86622. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  86623. this._attachedCamera.inertialBetaOffset !== 0 ||
  86624. this._attachedCamera.inertialRadiusOffset !== 0 ||
  86625. this._attachedCamera.inertialPanningX !== 0 ||
  86626. this._attachedCamera.inertialPanningY !== 0 ||
  86627. this._isPointerDown;
  86628. },
  86629. enumerable: true,
  86630. configurable: true
  86631. });
  86632. /**
  86633. * The easing function used by animations
  86634. */
  86635. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  86636. /**
  86637. * The easing mode used by animations
  86638. */
  86639. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  86640. // Statics
  86641. /**
  86642. * The camera can move all the way towards the mesh.
  86643. */
  86644. FramingBehavior.IgnoreBoundsSizeMode = 0;
  86645. /**
  86646. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  86647. */
  86648. FramingBehavior.FitFrustumSidesMode = 1;
  86649. return FramingBehavior;
  86650. }());
  86651. BABYLON.FramingBehavior = FramingBehavior;
  86652. })(BABYLON || (BABYLON = {}));
  86653. //# sourceMappingURL=babylon.framingBehavior.js.map
  86654. var BABYLON;
  86655. (function (BABYLON) {
  86656. /**
  86657. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  86658. */
  86659. var BouncingBehavior = /** @class */ (function () {
  86660. function BouncingBehavior() {
  86661. /**
  86662. * The duration of the animation, in milliseconds
  86663. */
  86664. this.transitionDuration = 450;
  86665. /**
  86666. * Length of the distance animated by the transition when lower radius is reached
  86667. */
  86668. this.lowerRadiusTransitionRange = 2;
  86669. /**
  86670. * Length of the distance animated by the transition when upper radius is reached
  86671. */
  86672. this.upperRadiusTransitionRange = -2;
  86673. this._autoTransitionRange = false;
  86674. // Animations
  86675. this._radiusIsAnimating = false;
  86676. this._radiusBounceTransition = null;
  86677. this._animatables = new Array();
  86678. }
  86679. Object.defineProperty(BouncingBehavior.prototype, "name", {
  86680. get: function () {
  86681. return "Bouncing";
  86682. },
  86683. enumerable: true,
  86684. configurable: true
  86685. });
  86686. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  86687. /**
  86688. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  86689. */
  86690. get: function () {
  86691. return this._autoTransitionRange;
  86692. },
  86693. /**
  86694. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  86695. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  86696. */
  86697. set: function (value) {
  86698. var _this = this;
  86699. if (this._autoTransitionRange === value) {
  86700. return;
  86701. }
  86702. this._autoTransitionRange = value;
  86703. var camera = this._attachedCamera;
  86704. if (!camera) {
  86705. return;
  86706. }
  86707. if (value) {
  86708. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  86709. if (!mesh) {
  86710. return;
  86711. }
  86712. mesh.computeWorldMatrix(true);
  86713. var diagonal = mesh.getBoundingInfo().diagonalLength;
  86714. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  86715. _this.upperRadiusTransitionRange = diagonal * 0.05;
  86716. });
  86717. }
  86718. else if (this._onMeshTargetChangedObserver) {
  86719. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86720. }
  86721. },
  86722. enumerable: true,
  86723. configurable: true
  86724. });
  86725. BouncingBehavior.prototype.init = function () {
  86726. // Do notihng
  86727. };
  86728. BouncingBehavior.prototype.attach = function (camera) {
  86729. var _this = this;
  86730. this._attachedCamera = camera;
  86731. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  86732. if (!_this._attachedCamera) {
  86733. return;
  86734. }
  86735. // Add the bounce animation to the lower radius limit
  86736. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  86737. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  86738. }
  86739. // Add the bounce animation to the upper radius limit
  86740. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  86741. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  86742. }
  86743. });
  86744. };
  86745. BouncingBehavior.prototype.detach = function () {
  86746. if (!this._attachedCamera) {
  86747. return;
  86748. }
  86749. if (this._onAfterCheckInputsObserver) {
  86750. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  86751. }
  86752. if (this._onMeshTargetChangedObserver) {
  86753. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  86754. }
  86755. this._attachedCamera = null;
  86756. };
  86757. /**
  86758. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  86759. * @param radiusLimit The limit to check against.
  86760. * @return Bool to indicate if at limit.
  86761. */
  86762. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  86763. if (!this._attachedCamera) {
  86764. return false;
  86765. }
  86766. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  86767. return true;
  86768. }
  86769. return false;
  86770. };
  86771. /**
  86772. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  86773. * @param radiusDelta The delta by which to animate to. Can be negative.
  86774. */
  86775. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  86776. var _this = this;
  86777. if (!this._attachedCamera) {
  86778. return;
  86779. }
  86780. if (!this._radiusBounceTransition) {
  86781. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  86782. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  86783. }
  86784. // Prevent zoom until bounce has completed
  86785. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  86786. this._attachedCamera.wheelPrecision = Infinity;
  86787. this._attachedCamera.inertialRadiusOffset = 0;
  86788. // Animate to the radius limit
  86789. this.stopAllAnimations();
  86790. this._radiusIsAnimating = true;
  86791. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  86792. if (animatable) {
  86793. this._animatables.push(animatable);
  86794. }
  86795. };
  86796. /**
  86797. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  86798. */
  86799. BouncingBehavior.prototype._clearAnimationLocks = function () {
  86800. this._radiusIsAnimating = false;
  86801. if (this._attachedCamera) {
  86802. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  86803. }
  86804. };
  86805. /**
  86806. * Stops and removes all animations that have been applied to the camera
  86807. */
  86808. BouncingBehavior.prototype.stopAllAnimations = function () {
  86809. if (this._attachedCamera) {
  86810. this._attachedCamera.animations = [];
  86811. }
  86812. while (this._animatables.length) {
  86813. this._animatables[0].onAnimationEnd = null;
  86814. this._animatables[0].stop();
  86815. this._animatables.shift();
  86816. }
  86817. };
  86818. /**
  86819. * The easing function used by animations
  86820. */
  86821. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  86822. /**
  86823. * The easing mode used by animations
  86824. */
  86825. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  86826. return BouncingBehavior;
  86827. }());
  86828. BABYLON.BouncingBehavior = BouncingBehavior;
  86829. })(BABYLON || (BABYLON = {}));
  86830. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  86831. var BABYLON;
  86832. (function (BABYLON) {
  86833. var AutoRotationBehavior = /** @class */ (function () {
  86834. function AutoRotationBehavior() {
  86835. this._zoomStopsAnimation = false;
  86836. this._idleRotationSpeed = 0.05;
  86837. this._idleRotationWaitTime = 2000;
  86838. this._idleRotationSpinupTime = 2000;
  86839. this._isPointerDown = false;
  86840. this._lastFrameTime = null;
  86841. this._lastInteractionTime = -Infinity;
  86842. this._cameraRotationSpeed = 0;
  86843. this._lastFrameRadius = 0;
  86844. }
  86845. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  86846. get: function () {
  86847. return "AutoRotation";
  86848. },
  86849. enumerable: true,
  86850. configurable: true
  86851. });
  86852. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  86853. /**
  86854. * Gets the flag that indicates if user zooming should stop animation.
  86855. */
  86856. get: function () {
  86857. return this._zoomStopsAnimation;
  86858. },
  86859. /**
  86860. * Sets the flag that indicates if user zooming should stop animation.
  86861. */
  86862. set: function (flag) {
  86863. this._zoomStopsAnimation = flag;
  86864. },
  86865. enumerable: true,
  86866. configurable: true
  86867. });
  86868. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  86869. /**
  86870. * Gets the default speed at which the camera rotates around the model.
  86871. */
  86872. get: function () {
  86873. return this._idleRotationSpeed;
  86874. },
  86875. /**
  86876. * Sets the default speed at which the camera rotates around the model.
  86877. */
  86878. set: function (speed) {
  86879. this._idleRotationSpeed = speed;
  86880. },
  86881. enumerable: true,
  86882. configurable: true
  86883. });
  86884. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  86885. /**
  86886. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  86887. */
  86888. get: function () {
  86889. return this._idleRotationWaitTime;
  86890. },
  86891. /**
  86892. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  86893. */
  86894. set: function (time) {
  86895. this._idleRotationWaitTime = time;
  86896. },
  86897. enumerable: true,
  86898. configurable: true
  86899. });
  86900. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  86901. /**
  86902. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  86903. */
  86904. get: function () {
  86905. return this._idleRotationSpinupTime;
  86906. },
  86907. /**
  86908. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  86909. */
  86910. set: function (time) {
  86911. this._idleRotationSpinupTime = time;
  86912. },
  86913. enumerable: true,
  86914. configurable: true
  86915. });
  86916. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  86917. /**
  86918. * Gets a value indicating if the camera is currently rotating because of this behavior
  86919. */
  86920. get: function () {
  86921. return Math.abs(this._cameraRotationSpeed) > 0;
  86922. },
  86923. enumerable: true,
  86924. configurable: true
  86925. });
  86926. AutoRotationBehavior.prototype.init = function () {
  86927. // Do notihng
  86928. };
  86929. AutoRotationBehavior.prototype.attach = function (camera) {
  86930. var _this = this;
  86931. this._attachedCamera = camera;
  86932. var scene = this._attachedCamera.getScene();
  86933. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  86934. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  86935. _this._isPointerDown = true;
  86936. return;
  86937. }
  86938. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  86939. _this._isPointerDown = false;
  86940. }
  86941. });
  86942. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  86943. var now = BABYLON.Tools.Now;
  86944. var dt = 0;
  86945. if (_this._lastFrameTime != null) {
  86946. dt = now - _this._lastFrameTime;
  86947. }
  86948. _this._lastFrameTime = now;
  86949. // Stop the animation if there is user interaction and the animation should stop for this interaction
  86950. _this._applyUserInteraction();
  86951. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  86952. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  86953. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  86954. // Step camera rotation by rotation speed
  86955. if (_this._attachedCamera) {
  86956. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  86957. }
  86958. });
  86959. };
  86960. AutoRotationBehavior.prototype.detach = function () {
  86961. if (!this._attachedCamera) {
  86962. return;
  86963. }
  86964. var scene = this._attachedCamera.getScene();
  86965. if (this._onPrePointerObservableObserver) {
  86966. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  86967. }
  86968. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  86969. this._attachedCamera = null;
  86970. };
  86971. /**
  86972. * Returns true if user is scrolling.
  86973. * @return true if user is scrolling.
  86974. */
  86975. AutoRotationBehavior.prototype._userIsZooming = function () {
  86976. if (!this._attachedCamera) {
  86977. return false;
  86978. }
  86979. return this._attachedCamera.inertialRadiusOffset !== 0;
  86980. };
  86981. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  86982. if (!this._attachedCamera) {
  86983. return false;
  86984. }
  86985. var zoomHasHitLimit = false;
  86986. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  86987. zoomHasHitLimit = true;
  86988. }
  86989. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  86990. this._lastFrameRadius = this._attachedCamera.radius;
  86991. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  86992. };
  86993. /**
  86994. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  86995. */
  86996. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  86997. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  86998. this._lastInteractionTime = BABYLON.Tools.Now;
  86999. }
  87000. };
  87001. // Tools
  87002. AutoRotationBehavior.prototype._userIsMoving = function () {
  87003. if (!this._attachedCamera) {
  87004. return false;
  87005. }
  87006. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  87007. this._attachedCamera.inertialBetaOffset !== 0 ||
  87008. this._attachedCamera.inertialRadiusOffset !== 0 ||
  87009. this._attachedCamera.inertialPanningX !== 0 ||
  87010. this._attachedCamera.inertialPanningY !== 0 ||
  87011. this._isPointerDown;
  87012. };
  87013. return AutoRotationBehavior;
  87014. }());
  87015. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  87016. })(BABYLON || (BABYLON = {}));
  87017. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  87018. var BABYLON;
  87019. (function (BABYLON) {
  87020. var NullEngineOptions = /** @class */ (function () {
  87021. function NullEngineOptions() {
  87022. this.renderWidth = 512;
  87023. this.renderHeight = 256;
  87024. this.textureSize = 512;
  87025. this.deterministicLockstep = false;
  87026. this.lockstepMaxSteps = 4;
  87027. }
  87028. return NullEngineOptions;
  87029. }());
  87030. BABYLON.NullEngineOptions = NullEngineOptions;
  87031. /**
  87032. * The null engine class provides support for headless version of babylon.js.
  87033. * This can be used in server side scenario or for testing purposes
  87034. */
  87035. var NullEngine = /** @class */ (function (_super) {
  87036. __extends(NullEngine, _super);
  87037. function NullEngine(options) {
  87038. if (options === void 0) { options = new NullEngineOptions(); }
  87039. var _this = _super.call(this, null) || this;
  87040. if (options.deterministicLockstep === undefined) {
  87041. options.deterministicLockstep = false;
  87042. }
  87043. if (options.lockstepMaxSteps === undefined) {
  87044. options.lockstepMaxSteps = 4;
  87045. }
  87046. _this._options = options;
  87047. // Init caps
  87048. // We consider we are on a webgl1 capable device
  87049. _this._caps = new BABYLON.EngineCapabilities();
  87050. _this._caps.maxTexturesImageUnits = 16;
  87051. _this._caps.maxVertexTextureImageUnits = 16;
  87052. _this._caps.maxTextureSize = 512;
  87053. _this._caps.maxCubemapTextureSize = 512;
  87054. _this._caps.maxRenderTextureSize = 512;
  87055. _this._caps.maxVertexAttribs = 16;
  87056. _this._caps.maxVaryingVectors = 16;
  87057. _this._caps.maxFragmentUniformVectors = 16;
  87058. _this._caps.maxVertexUniformVectors = 16;
  87059. // Extensions
  87060. _this._caps.standardDerivatives = false;
  87061. _this._caps.astc = null;
  87062. _this._caps.s3tc = null;
  87063. _this._caps.pvrtc = null;
  87064. _this._caps.etc1 = null;
  87065. _this._caps.etc2 = null;
  87066. _this._caps.textureAnisotropicFilterExtension = null;
  87067. _this._caps.maxAnisotropy = 0;
  87068. _this._caps.uintIndices = false;
  87069. _this._caps.fragmentDepthSupported = false;
  87070. _this._caps.highPrecisionShaderSupported = true;
  87071. _this._caps.colorBufferFloat = false;
  87072. _this._caps.textureFloat = false;
  87073. _this._caps.textureFloatLinearFiltering = false;
  87074. _this._caps.textureFloatRender = false;
  87075. _this._caps.textureHalfFloat = false;
  87076. _this._caps.textureHalfFloatLinearFiltering = false;
  87077. _this._caps.textureHalfFloatRender = false;
  87078. _this._caps.textureLOD = false;
  87079. _this._caps.drawBuffersExtension = false;
  87080. _this._caps.depthTextureExtension = false;
  87081. _this._caps.vertexArrayObject = false;
  87082. _this._caps.instancedArrays = false;
  87083. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  87084. // Wrappers
  87085. if (typeof URL === "undefined") {
  87086. URL = {
  87087. createObjectURL: function () { },
  87088. revokeObjectURL: function () { }
  87089. };
  87090. }
  87091. if (typeof Blob === "undefined") {
  87092. Blob = function () { };
  87093. }
  87094. return _this;
  87095. }
  87096. NullEngine.prototype.isDeterministicLockStep = function () {
  87097. return this._options.deterministicLockstep;
  87098. };
  87099. NullEngine.prototype.getLockstepMaxSteps = function () {
  87100. return this._options.lockstepMaxSteps;
  87101. };
  87102. NullEngine.prototype.getHardwareScalingLevel = function () {
  87103. return 1.0;
  87104. };
  87105. NullEngine.prototype.createVertexBuffer = function (vertices) {
  87106. return {
  87107. capacity: 0,
  87108. references: 1,
  87109. is32Bits: false
  87110. };
  87111. };
  87112. NullEngine.prototype.createIndexBuffer = function (indices) {
  87113. return {
  87114. capacity: 0,
  87115. references: 1,
  87116. is32Bits: false
  87117. };
  87118. };
  87119. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  87120. if (stencil === void 0) { stencil = false; }
  87121. };
  87122. NullEngine.prototype.getRenderWidth = function (useScreen) {
  87123. if (useScreen === void 0) { useScreen = false; }
  87124. if (!useScreen && this._currentRenderTarget) {
  87125. return this._currentRenderTarget.width;
  87126. }
  87127. return this._options.renderWidth;
  87128. };
  87129. NullEngine.prototype.getRenderHeight = function (useScreen) {
  87130. if (useScreen === void 0) { useScreen = false; }
  87131. if (!useScreen && this._currentRenderTarget) {
  87132. return this._currentRenderTarget.height;
  87133. }
  87134. return this._options.renderHeight;
  87135. };
  87136. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  87137. this._cachedViewport = viewport;
  87138. };
  87139. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  87140. return {
  87141. transformFeedback: null,
  87142. __SPECTOR_rebuildProgram: null
  87143. };
  87144. };
  87145. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  87146. return [];
  87147. };
  87148. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  87149. return [];
  87150. };
  87151. NullEngine.prototype.bindSamplers = function (effect) {
  87152. this._currentEffect = null;
  87153. };
  87154. NullEngine.prototype.enableEffect = function (effect) {
  87155. this._currentEffect = effect;
  87156. if (effect.onBind) {
  87157. effect.onBind(effect);
  87158. }
  87159. effect.onBindObservable.notifyObservers(effect);
  87160. };
  87161. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  87162. if (zOffset === void 0) { zOffset = 0; }
  87163. if (reverseSide === void 0) { reverseSide = false; }
  87164. };
  87165. NullEngine.prototype.setIntArray = function (uniform, array) {
  87166. };
  87167. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  87168. };
  87169. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  87170. };
  87171. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  87172. };
  87173. NullEngine.prototype.setFloatArray = function (uniform, array) {
  87174. };
  87175. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  87176. };
  87177. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  87178. };
  87179. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  87180. };
  87181. NullEngine.prototype.setArray = function (uniform, array) {
  87182. };
  87183. NullEngine.prototype.setArray2 = function (uniform, array) {
  87184. };
  87185. NullEngine.prototype.setArray3 = function (uniform, array) {
  87186. };
  87187. NullEngine.prototype.setArray4 = function (uniform, array) {
  87188. };
  87189. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  87190. };
  87191. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  87192. };
  87193. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  87194. };
  87195. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  87196. };
  87197. NullEngine.prototype.setFloat = function (uniform, value) {
  87198. };
  87199. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  87200. };
  87201. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  87202. };
  87203. NullEngine.prototype.setBool = function (uniform, bool) {
  87204. };
  87205. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  87206. };
  87207. NullEngine.prototype.setColor3 = function (uniform, color3) {
  87208. };
  87209. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  87210. };
  87211. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  87212. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  87213. if (this._alphaMode === mode) {
  87214. return;
  87215. }
  87216. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  87217. if (!noDepthWriteChange) {
  87218. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  87219. }
  87220. this._alphaMode = mode;
  87221. };
  87222. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  87223. };
  87224. NullEngine.prototype.wipeCaches = function (bruteForce) {
  87225. if (this.preventCacheWipeBetweenFrames) {
  87226. return;
  87227. }
  87228. this.resetTextureCache();
  87229. this._currentEffect = null;
  87230. if (bruteForce) {
  87231. this._currentProgram = null;
  87232. this._stencilState.reset();
  87233. this._depthCullingState.reset();
  87234. this._alphaState.reset();
  87235. }
  87236. this._cachedVertexBuffers = null;
  87237. this._cachedIndexBuffer = null;
  87238. this._cachedEffectForVertexBuffers = null;
  87239. };
  87240. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  87241. };
  87242. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  87243. };
  87244. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  87245. };
  87246. NullEngine.prototype._createTexture = function () {
  87247. return {};
  87248. };
  87249. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  87250. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87251. if (onLoad === void 0) { onLoad = null; }
  87252. if (onError === void 0) { onError = null; }
  87253. if (buffer === void 0) { buffer = null; }
  87254. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  87255. var url = String(urlArg);
  87256. texture.url = url;
  87257. texture.generateMipMaps = !noMipmap;
  87258. texture.samplingMode = samplingMode;
  87259. texture.invertY = invertY;
  87260. texture.baseWidth = this._options.textureSize;
  87261. texture.baseHeight = this._options.textureSize;
  87262. texture.width = this._options.textureSize;
  87263. texture.height = this._options.textureSize;
  87264. if (format) {
  87265. texture.format = format;
  87266. }
  87267. texture.isReady = true;
  87268. if (onLoad) {
  87269. onLoad();
  87270. }
  87271. return texture;
  87272. };
  87273. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  87274. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  87275. if (options !== undefined && typeof options === "object") {
  87276. fullOptions.generateMipMaps = options.generateMipMaps;
  87277. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  87278. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  87279. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  87280. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  87281. }
  87282. else {
  87283. fullOptions.generateMipMaps = options;
  87284. fullOptions.generateDepthBuffer = true;
  87285. fullOptions.generateStencilBuffer = false;
  87286. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87287. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  87288. }
  87289. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  87290. var width = size.width || size;
  87291. var height = size.height || size;
  87292. texture._depthStencilBuffer = {};
  87293. texture._framebuffer = {};
  87294. texture.baseWidth = width;
  87295. texture.baseHeight = height;
  87296. texture.width = width;
  87297. texture.height = height;
  87298. texture.isReady = true;
  87299. texture.samples = 1;
  87300. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  87301. texture.samplingMode = fullOptions.samplingMode;
  87302. texture.type = fullOptions.type;
  87303. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  87304. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  87305. return texture;
  87306. };
  87307. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  87308. texture.samplingMode = samplingMode;
  87309. };
  87310. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  87311. if (this._currentRenderTarget) {
  87312. this.unBindFramebuffer(this._currentRenderTarget);
  87313. }
  87314. this._currentRenderTarget = texture;
  87315. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  87316. if (this._cachedViewport && !forceFullscreenViewport) {
  87317. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  87318. }
  87319. };
  87320. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  87321. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  87322. this._currentRenderTarget = null;
  87323. if (onBeforeUnbind) {
  87324. if (texture._MSAAFramebuffer) {
  87325. this._currentFramebuffer = texture._framebuffer;
  87326. }
  87327. onBeforeUnbind();
  87328. }
  87329. this._currentFramebuffer = null;
  87330. };
  87331. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  87332. var vbo = {
  87333. capacity: 1,
  87334. references: 1,
  87335. is32Bits: false
  87336. };
  87337. return vbo;
  87338. };
  87339. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  87340. if (offset === void 0) { offset = 0; }
  87341. };
  87342. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  87343. };
  87344. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  87345. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  87346. this._boundTexturesCache[this._activeChannel] = texture;
  87347. }
  87348. };
  87349. NullEngine.prototype._bindTexture = function (channel, texture) {
  87350. if (channel < 0) {
  87351. return;
  87352. }
  87353. this._bindTextureDirectly(0, texture);
  87354. };
  87355. NullEngine.prototype._releaseBuffer = function (buffer) {
  87356. buffer.references--;
  87357. if (buffer.references === 0) {
  87358. return true;
  87359. }
  87360. return false;
  87361. };
  87362. return NullEngine;
  87363. }(BABYLON.Engine));
  87364. BABYLON.NullEngine = NullEngine;
  87365. })(BABYLON || (BABYLON = {}));
  87366. //# sourceMappingURL=babylon.nullEngine.js.map
  87367. var BABYLON;
  87368. (function (BABYLON) {
  87369. /**
  87370. * This class can be used to get instrumentation data from a Babylon engine
  87371. */
  87372. var EngineInstrumentation = /** @class */ (function () {
  87373. function EngineInstrumentation(engine) {
  87374. this.engine = engine;
  87375. this._captureGPUFrameTime = false;
  87376. this._gpuFrameTime = new BABYLON.PerfCounter();
  87377. this._captureShaderCompilationTime = false;
  87378. this._shaderCompilationTime = new BABYLON.PerfCounter();
  87379. // Observers
  87380. this._onBeginFrameObserver = null;
  87381. this._onEndFrameObserver = null;
  87382. this._onBeforeShaderCompilationObserver = null;
  87383. this._onAfterShaderCompilationObserver = null;
  87384. }
  87385. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  87386. // Properties
  87387. /**
  87388. * Gets the perf counter used for GPU frame time
  87389. */
  87390. get: function () {
  87391. return this._gpuFrameTime;
  87392. },
  87393. enumerable: true,
  87394. configurable: true
  87395. });
  87396. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  87397. /**
  87398. * Gets the GPU frame time capture status
  87399. */
  87400. get: function () {
  87401. return this._captureGPUFrameTime;
  87402. },
  87403. /**
  87404. * Enable or disable the GPU frame time capture
  87405. */
  87406. set: function (value) {
  87407. var _this = this;
  87408. if (value === this._captureGPUFrameTime) {
  87409. return;
  87410. }
  87411. this._captureGPUFrameTime = value;
  87412. if (value) {
  87413. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  87414. if (!_this._gpuFrameTimeToken) {
  87415. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  87416. }
  87417. });
  87418. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  87419. if (!_this._gpuFrameTimeToken) {
  87420. return;
  87421. }
  87422. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  87423. if (time > -1) {
  87424. _this._gpuFrameTimeToken = null;
  87425. _this._gpuFrameTime.fetchNewFrame();
  87426. _this._gpuFrameTime.addCount(time, true);
  87427. }
  87428. });
  87429. }
  87430. else {
  87431. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  87432. this._onBeginFrameObserver = null;
  87433. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  87434. this._onEndFrameObserver = null;
  87435. }
  87436. },
  87437. enumerable: true,
  87438. configurable: true
  87439. });
  87440. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  87441. /**
  87442. * Gets the perf counter used for shader compilation time
  87443. */
  87444. get: function () {
  87445. return this._shaderCompilationTime;
  87446. },
  87447. enumerable: true,
  87448. configurable: true
  87449. });
  87450. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  87451. /**
  87452. * Gets the shader compilation time capture status
  87453. */
  87454. get: function () {
  87455. return this._captureShaderCompilationTime;
  87456. },
  87457. /**
  87458. * Enable or disable the shader compilation time capture
  87459. */
  87460. set: function (value) {
  87461. var _this = this;
  87462. if (value === this._captureShaderCompilationTime) {
  87463. return;
  87464. }
  87465. this._captureShaderCompilationTime = value;
  87466. if (value) {
  87467. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  87468. _this._shaderCompilationTime.fetchNewFrame();
  87469. _this._shaderCompilationTime.beginMonitoring();
  87470. });
  87471. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  87472. _this._shaderCompilationTime.endMonitoring();
  87473. });
  87474. }
  87475. else {
  87476. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  87477. this._onBeforeShaderCompilationObserver = null;
  87478. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  87479. this._onAfterShaderCompilationObserver = null;
  87480. }
  87481. },
  87482. enumerable: true,
  87483. configurable: true
  87484. });
  87485. EngineInstrumentation.prototype.dispose = function () {
  87486. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  87487. this._onBeginFrameObserver = null;
  87488. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  87489. this._onEndFrameObserver = null;
  87490. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  87491. this._onBeforeShaderCompilationObserver = null;
  87492. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  87493. this._onAfterShaderCompilationObserver = null;
  87494. this.engine = null;
  87495. };
  87496. return EngineInstrumentation;
  87497. }());
  87498. BABYLON.EngineInstrumentation = EngineInstrumentation;
  87499. })(BABYLON || (BABYLON = {}));
  87500. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  87501. var BABYLON;
  87502. (function (BABYLON) {
  87503. /**
  87504. * This class can be used to get instrumentation data from a Babylon engine
  87505. */
  87506. var SceneInstrumentation = /** @class */ (function () {
  87507. function SceneInstrumentation(scene) {
  87508. var _this = this;
  87509. this.scene = scene;
  87510. this._captureActiveMeshesEvaluationTime = false;
  87511. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  87512. this._captureRenderTargetsRenderTime = false;
  87513. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  87514. this._captureFrameTime = false;
  87515. this._frameTime = new BABYLON.PerfCounter();
  87516. this._captureRenderTime = false;
  87517. this._renderTime = new BABYLON.PerfCounter();
  87518. this._captureInterFrameTime = false;
  87519. this._interFrameTime = new BABYLON.PerfCounter();
  87520. this._captureParticlesRenderTime = false;
  87521. this._particlesRenderTime = new BABYLON.PerfCounter();
  87522. this._captureSpritesRenderTime = false;
  87523. this._spritesRenderTime = new BABYLON.PerfCounter();
  87524. this._capturePhysicsTime = false;
  87525. this._physicsTime = new BABYLON.PerfCounter();
  87526. this._captureAnimationsTime = false;
  87527. this._animationsTime = new BABYLON.PerfCounter();
  87528. // Observers
  87529. this._onBeforeActiveMeshesEvaluationObserver = null;
  87530. this._onAfterActiveMeshesEvaluationObserver = null;
  87531. this._onBeforeRenderTargetsRenderObserver = null;
  87532. this._onAfterRenderTargetsRenderObserver = null;
  87533. this._onAfterRenderObserver = null;
  87534. this._onBeforeDrawPhaseObserver = null;
  87535. this._onAfterDrawPhaseObserver = null;
  87536. this._onBeforeAnimationsObserver = null;
  87537. this._onBeforeParticlesRenderingObserver = null;
  87538. this._onAfterParticlesRenderingObserver = null;
  87539. this._onBeforeSpritesRenderingObserver = null;
  87540. this._onAfterSpritesRenderingObserver = null;
  87541. this._onBeforePhysicsObserver = null;
  87542. this._onAfterPhysicsObserver = null;
  87543. this._onAfterAnimationsObserver = null;
  87544. // Before render
  87545. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  87546. if (_this._captureActiveMeshesEvaluationTime) {
  87547. _this._activeMeshesEvaluationTime.fetchNewFrame();
  87548. }
  87549. if (_this._captureRenderTargetsRenderTime) {
  87550. _this._renderTargetsRenderTime.fetchNewFrame();
  87551. }
  87552. if (_this._captureFrameTime) {
  87553. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  87554. _this._frameTime.beginMonitoring();
  87555. }
  87556. if (_this._captureInterFrameTime) {
  87557. _this._interFrameTime.endMonitoring();
  87558. }
  87559. if (_this._captureParticlesRenderTime) {
  87560. _this._particlesRenderTime.fetchNewFrame();
  87561. }
  87562. if (_this._captureSpritesRenderTime) {
  87563. _this._spritesRenderTime.fetchNewFrame();
  87564. }
  87565. if (_this._captureAnimationsTime) {
  87566. _this._animationsTime.beginMonitoring();
  87567. }
  87568. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  87569. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  87570. });
  87571. // After render
  87572. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  87573. if (_this._captureFrameTime) {
  87574. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  87575. _this._frameTime.endMonitoring();
  87576. }
  87577. if (_this._captureRenderTime) {
  87578. _this._renderTime.endMonitoring(false);
  87579. }
  87580. if (_this._captureInterFrameTime) {
  87581. _this._interFrameTime.beginMonitoring();
  87582. }
  87583. });
  87584. }
  87585. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  87586. // Properties
  87587. /**
  87588. * Gets the perf counter used for active meshes evaluation time
  87589. */
  87590. get: function () {
  87591. return this._activeMeshesEvaluationTime;
  87592. },
  87593. enumerable: true,
  87594. configurable: true
  87595. });
  87596. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  87597. /**
  87598. * Gets the active meshes evaluation time capture status
  87599. */
  87600. get: function () {
  87601. return this._captureActiveMeshesEvaluationTime;
  87602. },
  87603. /**
  87604. * Enable or disable the active meshes evaluation time capture
  87605. */
  87606. set: function (value) {
  87607. var _this = this;
  87608. if (value === this._captureActiveMeshesEvaluationTime) {
  87609. return;
  87610. }
  87611. this._captureActiveMeshesEvaluationTime = value;
  87612. if (value) {
  87613. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  87614. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  87615. _this._activeMeshesEvaluationTime.beginMonitoring();
  87616. });
  87617. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  87618. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  87619. _this._activeMeshesEvaluationTime.endMonitoring();
  87620. });
  87621. }
  87622. else {
  87623. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  87624. this._onBeforeActiveMeshesEvaluationObserver = null;
  87625. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  87626. this._onAfterActiveMeshesEvaluationObserver = null;
  87627. }
  87628. },
  87629. enumerable: true,
  87630. configurable: true
  87631. });
  87632. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  87633. /**
  87634. * Gets the perf counter used for render targets render time
  87635. */
  87636. get: function () {
  87637. return this._renderTargetsRenderTime;
  87638. },
  87639. enumerable: true,
  87640. configurable: true
  87641. });
  87642. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  87643. /**
  87644. * Gets the render targets render time capture status
  87645. */
  87646. get: function () {
  87647. return this._captureRenderTargetsRenderTime;
  87648. },
  87649. /**
  87650. * Enable or disable the render targets render time capture
  87651. */
  87652. set: function (value) {
  87653. var _this = this;
  87654. if (value === this._captureRenderTargetsRenderTime) {
  87655. return;
  87656. }
  87657. this._captureRenderTargetsRenderTime = value;
  87658. if (value) {
  87659. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  87660. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  87661. _this._renderTargetsRenderTime.beginMonitoring();
  87662. });
  87663. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  87664. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  87665. _this._renderTargetsRenderTime.endMonitoring(false);
  87666. });
  87667. }
  87668. else {
  87669. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  87670. this._onBeforeRenderTargetsRenderObserver = null;
  87671. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  87672. this._onAfterRenderTargetsRenderObserver = null;
  87673. }
  87674. },
  87675. enumerable: true,
  87676. configurable: true
  87677. });
  87678. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  87679. /**
  87680. * Gets the perf counter used for particles render time
  87681. */
  87682. get: function () {
  87683. return this._particlesRenderTime;
  87684. },
  87685. enumerable: true,
  87686. configurable: true
  87687. });
  87688. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  87689. /**
  87690. * Gets the particles render time capture status
  87691. */
  87692. get: function () {
  87693. return this._captureParticlesRenderTime;
  87694. },
  87695. /**
  87696. * Enable or disable the particles render time capture
  87697. */
  87698. set: function (value) {
  87699. var _this = this;
  87700. if (value === this._captureParticlesRenderTime) {
  87701. return;
  87702. }
  87703. this._captureParticlesRenderTime = value;
  87704. if (value) {
  87705. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  87706. BABYLON.Tools.StartPerformanceCounter("Particles");
  87707. _this._particlesRenderTime.beginMonitoring();
  87708. });
  87709. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  87710. BABYLON.Tools.EndPerformanceCounter("Particles");
  87711. _this._particlesRenderTime.endMonitoring(false);
  87712. });
  87713. }
  87714. else {
  87715. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  87716. this._onBeforeParticlesRenderingObserver = null;
  87717. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  87718. this._onAfterParticlesRenderingObserver = null;
  87719. }
  87720. },
  87721. enumerable: true,
  87722. configurable: true
  87723. });
  87724. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  87725. /**
  87726. * Gets the perf counter used for sprites render time
  87727. */
  87728. get: function () {
  87729. return this._spritesRenderTime;
  87730. },
  87731. enumerable: true,
  87732. configurable: true
  87733. });
  87734. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  87735. /**
  87736. * Gets the sprites render time capture status
  87737. */
  87738. get: function () {
  87739. return this._captureSpritesRenderTime;
  87740. },
  87741. /**
  87742. * Enable or disable the sprites render time capture
  87743. */
  87744. set: function (value) {
  87745. var _this = this;
  87746. if (value === this._captureSpritesRenderTime) {
  87747. return;
  87748. }
  87749. this._captureSpritesRenderTime = value;
  87750. if (value) {
  87751. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  87752. BABYLON.Tools.StartPerformanceCounter("Sprites");
  87753. _this._spritesRenderTime.beginMonitoring();
  87754. });
  87755. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  87756. BABYLON.Tools.EndPerformanceCounter("Sprites");
  87757. _this._spritesRenderTime.endMonitoring(false);
  87758. });
  87759. }
  87760. else {
  87761. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  87762. this._onBeforeSpritesRenderingObserver = null;
  87763. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  87764. this._onAfterSpritesRenderingObserver = null;
  87765. }
  87766. },
  87767. enumerable: true,
  87768. configurable: true
  87769. });
  87770. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  87771. /**
  87772. * Gets the perf counter used for physics time
  87773. */
  87774. get: function () {
  87775. return this._physicsTime;
  87776. },
  87777. enumerable: true,
  87778. configurable: true
  87779. });
  87780. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  87781. /**
  87782. * Gets the physics time capture status
  87783. */
  87784. get: function () {
  87785. return this._capturePhysicsTime;
  87786. },
  87787. /**
  87788. * Enable or disable the physics time capture
  87789. */
  87790. set: function (value) {
  87791. var _this = this;
  87792. if (value === this._capturePhysicsTime) {
  87793. return;
  87794. }
  87795. this._capturePhysicsTime = value;
  87796. if (value) {
  87797. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  87798. BABYLON.Tools.StartPerformanceCounter("Physics");
  87799. _this._physicsTime.beginMonitoring();
  87800. });
  87801. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  87802. BABYLON.Tools.EndPerformanceCounter("Physics");
  87803. _this._physicsTime.endMonitoring();
  87804. });
  87805. }
  87806. else {
  87807. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  87808. this._onBeforePhysicsObserver = null;
  87809. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  87810. this._onAfterPhysicsObserver = null;
  87811. }
  87812. },
  87813. enumerable: true,
  87814. configurable: true
  87815. });
  87816. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  87817. /**
  87818. * Gets the perf counter used for animations time
  87819. */
  87820. get: function () {
  87821. return this._animationsTime;
  87822. },
  87823. enumerable: true,
  87824. configurable: true
  87825. });
  87826. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  87827. /**
  87828. * Gets the animations time capture status
  87829. */
  87830. get: function () {
  87831. return this._captureAnimationsTime;
  87832. },
  87833. /**
  87834. * Enable or disable the animations time capture
  87835. */
  87836. set: function (value) {
  87837. var _this = this;
  87838. if (value === this._captureAnimationsTime) {
  87839. return;
  87840. }
  87841. this._captureAnimationsTime = value;
  87842. if (value) {
  87843. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  87844. _this._animationsTime.endMonitoring();
  87845. });
  87846. }
  87847. else {
  87848. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  87849. this._onAfterAnimationsObserver = null;
  87850. }
  87851. },
  87852. enumerable: true,
  87853. configurable: true
  87854. });
  87855. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  87856. /**
  87857. * Gets the perf counter used for frame time capture
  87858. */
  87859. get: function () {
  87860. return this._frameTime;
  87861. },
  87862. enumerable: true,
  87863. configurable: true
  87864. });
  87865. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  87866. /**
  87867. * Gets the frame time capture status
  87868. */
  87869. get: function () {
  87870. return this._captureFrameTime;
  87871. },
  87872. /**
  87873. * Enable or disable the frame time capture
  87874. */
  87875. set: function (value) {
  87876. this._captureFrameTime = value;
  87877. },
  87878. enumerable: true,
  87879. configurable: true
  87880. });
  87881. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  87882. /**
  87883. * Gets the perf counter used for inter-frames time capture
  87884. */
  87885. get: function () {
  87886. return this._interFrameTime;
  87887. },
  87888. enumerable: true,
  87889. configurable: true
  87890. });
  87891. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  87892. /**
  87893. * Gets the inter-frames time capture status
  87894. */
  87895. get: function () {
  87896. return this._captureInterFrameTime;
  87897. },
  87898. /**
  87899. * Enable or disable the inter-frames time capture
  87900. */
  87901. set: function (value) {
  87902. this._captureInterFrameTime = value;
  87903. },
  87904. enumerable: true,
  87905. configurable: true
  87906. });
  87907. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  87908. /**
  87909. * Gets the perf counter used for render time capture
  87910. */
  87911. get: function () {
  87912. return this._renderTime;
  87913. },
  87914. enumerable: true,
  87915. configurable: true
  87916. });
  87917. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  87918. /**
  87919. * Gets the render time capture status
  87920. */
  87921. get: function () {
  87922. return this._captureRenderTime;
  87923. },
  87924. /**
  87925. * Enable or disable the render time capture
  87926. */
  87927. set: function (value) {
  87928. var _this = this;
  87929. if (value === this._captureRenderTime) {
  87930. return;
  87931. }
  87932. this._captureRenderTime = value;
  87933. if (value) {
  87934. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  87935. _this._renderTime.beginMonitoring();
  87936. BABYLON.Tools.StartPerformanceCounter("Main render");
  87937. });
  87938. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  87939. _this._renderTime.endMonitoring(false);
  87940. BABYLON.Tools.EndPerformanceCounter("Main render");
  87941. });
  87942. }
  87943. else {
  87944. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  87945. this._onBeforeDrawPhaseObserver = null;
  87946. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  87947. this._onAfterDrawPhaseObserver = null;
  87948. }
  87949. },
  87950. enumerable: true,
  87951. configurable: true
  87952. });
  87953. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  87954. /**
  87955. * Gets the perf counter used for draw calls
  87956. */
  87957. get: function () {
  87958. return this.scene.getEngine()._drawCalls;
  87959. },
  87960. enumerable: true,
  87961. configurable: true
  87962. });
  87963. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  87964. /**
  87965. * Gets the perf counter used for texture collisions
  87966. */
  87967. get: function () {
  87968. return this.scene.getEngine()._textureCollisions;
  87969. },
  87970. enumerable: true,
  87971. configurable: true
  87972. });
  87973. SceneInstrumentation.prototype.dispose = function () {
  87974. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  87975. this._onAfterRenderObserver = null;
  87976. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  87977. this._onBeforeActiveMeshesEvaluationObserver = null;
  87978. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  87979. this._onAfterActiveMeshesEvaluationObserver = null;
  87980. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  87981. this._onBeforeRenderTargetsRenderObserver = null;
  87982. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  87983. this._onAfterRenderTargetsRenderObserver = null;
  87984. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  87985. this._onBeforeAnimationsObserver = null;
  87986. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  87987. this._onBeforeParticlesRenderingObserver = null;
  87988. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  87989. this._onAfterParticlesRenderingObserver = null;
  87990. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  87991. this._onBeforeSpritesRenderingObserver = null;
  87992. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  87993. this._onAfterSpritesRenderingObserver = null;
  87994. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  87995. this._onBeforeDrawPhaseObserver = null;
  87996. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  87997. this._onAfterDrawPhaseObserver = null;
  87998. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  87999. this._onBeforePhysicsObserver = null;
  88000. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  88001. this._onAfterPhysicsObserver = null;
  88002. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  88003. this._onAfterAnimationsObserver = null;
  88004. this.scene = null;
  88005. };
  88006. return SceneInstrumentation;
  88007. }());
  88008. BABYLON.SceneInstrumentation = SceneInstrumentation;
  88009. })(BABYLON || (BABYLON = {}));
  88010. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  88011. var BABYLON;
  88012. (function (BABYLON) {
  88013. var _TimeToken = /** @class */ (function () {
  88014. function _TimeToken() {
  88015. this._timeElapsedQueryEnded = false;
  88016. }
  88017. return _TimeToken;
  88018. }());
  88019. BABYLON._TimeToken = _TimeToken;
  88020. })(BABYLON || (BABYLON = {}));
  88021. //# sourceMappingURL=babylon.timeToken.js.map
  88022. var BABYLON;
  88023. (function (BABYLON) {
  88024. /**
  88025. * Background material defines definition.
  88026. * @ignore Mainly internal Use
  88027. */
  88028. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  88029. __extends(BackgroundMaterialDefines, _super);
  88030. /**
  88031. * Constructor of the defines.
  88032. */
  88033. function BackgroundMaterialDefines() {
  88034. var _this = _super.call(this) || this;
  88035. /**
  88036. * True if the diffuse texture is in use.
  88037. */
  88038. _this.DIFFUSE = false;
  88039. /**
  88040. * The direct UV channel to use.
  88041. */
  88042. _this.DIFFUSEDIRECTUV = 0;
  88043. /**
  88044. * True if the diffuse texture is in gamma space.
  88045. */
  88046. _this.GAMMADIFFUSE = false;
  88047. /**
  88048. * True if the diffuse texture has opacity in the alpha channel.
  88049. */
  88050. _this.DIFFUSEHASALPHA = false;
  88051. /**
  88052. * True if you want the material to fade to transparent at grazing angle.
  88053. */
  88054. _this.OPACITYFRESNEL = false;
  88055. /**
  88056. * True if an extra blur needs to be added in the reflection.
  88057. */
  88058. _this.REFLECTIONBLUR = false;
  88059. /**
  88060. * True if you want the material to fade to reflection at grazing angle.
  88061. */
  88062. _this.REFLECTIONFRESNEL = false;
  88063. /**
  88064. * True if you want the material to falloff as far as you move away from the scene center.
  88065. */
  88066. _this.REFLECTIONFALLOFF = false;
  88067. /**
  88068. * False if the current Webgl implementation does not support the texture lod extension.
  88069. */
  88070. _this.TEXTURELODSUPPORT = false;
  88071. /**
  88072. * True to ensure the data are premultiplied.
  88073. */
  88074. _this.PREMULTIPLYALPHA = false;
  88075. /**
  88076. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  88077. */
  88078. _this.USERGBCOLOR = false;
  88079. /**
  88080. * True to add noise in order to reduce the banding effect.
  88081. */
  88082. _this.NOISE = false;
  88083. // Image Processing Configuration.
  88084. _this.IMAGEPROCESSING = false;
  88085. _this.VIGNETTE = false;
  88086. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  88087. _this.VIGNETTEBLENDMODEOPAQUE = false;
  88088. _this.TONEMAPPING = false;
  88089. _this.CONTRAST = false;
  88090. _this.COLORCURVES = false;
  88091. _this.COLORGRADING = false;
  88092. _this.COLORGRADING3D = false;
  88093. _this.SAMPLER3DGREENDEPTH = false;
  88094. _this.SAMPLER3DBGRMAP = false;
  88095. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  88096. _this.EXPOSURE = false;
  88097. // Reflection.
  88098. _this.REFLECTION = false;
  88099. _this.REFLECTIONMAP_3D = false;
  88100. _this.REFLECTIONMAP_SPHERICAL = false;
  88101. _this.REFLECTIONMAP_PLANAR = false;
  88102. _this.REFLECTIONMAP_CUBIC = false;
  88103. _this.REFLECTIONMAP_PROJECTION = false;
  88104. _this.REFLECTIONMAP_SKYBOX = false;
  88105. _this.REFLECTIONMAP_EXPLICIT = false;
  88106. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88107. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88108. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88109. _this.INVERTCUBICMAP = false;
  88110. _this.REFLECTIONMAP_OPPOSITEZ = false;
  88111. _this.LODINREFLECTIONALPHA = false;
  88112. _this.GAMMAREFLECTION = false;
  88113. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  88114. // Default BJS.
  88115. _this.MAINUV1 = false;
  88116. _this.MAINUV2 = false;
  88117. _this.UV1 = false;
  88118. _this.UV2 = false;
  88119. _this.CLIPPLANE = false;
  88120. _this.POINTSIZE = false;
  88121. _this.FOG = false;
  88122. _this.NORMAL = false;
  88123. _this.NUM_BONE_INFLUENCERS = 0;
  88124. _this.BonesPerMesh = 0;
  88125. _this.INSTANCES = false;
  88126. _this.SHADOWFLOAT = false;
  88127. _this.rebuild();
  88128. return _this;
  88129. }
  88130. return BackgroundMaterialDefines;
  88131. }(BABYLON.MaterialDefines));
  88132. /**
  88133. * Background material used to create an efficient environement around your scene.
  88134. */
  88135. var BackgroundMaterial = /** @class */ (function (_super) {
  88136. __extends(BackgroundMaterial, _super);
  88137. /**
  88138. * Instantiates a Background Material in the given scene
  88139. * @param name The friendly name of the material
  88140. * @param scene The scene to add the material to
  88141. */
  88142. function BackgroundMaterial(name, scene) {
  88143. var _this = _super.call(this, name, scene) || this;
  88144. /**
  88145. * Key light Color (multiply against the R channel of the environement texture)
  88146. */
  88147. _this.primaryColor = BABYLON.Color3.White();
  88148. /**
  88149. * Key light Level (allowing HDR output of the background)
  88150. */
  88151. _this.primaryLevel = 1;
  88152. /**
  88153. * Secondary light Color (multiply against the G channel of the environement texture)
  88154. */
  88155. _this.secondaryColor = BABYLON.Color3.Gray();
  88156. /**
  88157. * Secondary light Level (allowing HDR output of the background)
  88158. */
  88159. _this.secondaryLevel = 1;
  88160. /**
  88161. * Tertiary light Color (multiply against the B channel of the environement texture)
  88162. */
  88163. _this.tertiaryColor = BABYLON.Color3.Black();
  88164. /**
  88165. * Tertiary light Level (allowing HDR output of the background)
  88166. */
  88167. _this.tertiaryLevel = 1;
  88168. /**
  88169. * Reflection Texture used in the material.
  88170. * Should be author in a specific way for the best result (refer to the documentation).
  88171. */
  88172. _this.reflectionTexture = null;
  88173. /**
  88174. * Reflection Texture level of blur.
  88175. *
  88176. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  88177. * texture twice.
  88178. */
  88179. _this.reflectionBlur = 0;
  88180. /**
  88181. * Diffuse Texture used in the material.
  88182. * Should be author in a specific way for the best result (refer to the documentation).
  88183. */
  88184. _this.diffuseTexture = null;
  88185. _this._shadowLights = null;
  88186. /**
  88187. * Specify the list of lights casting shadow on the material.
  88188. * All scene shadow lights will be included if null.
  88189. */
  88190. _this.shadowLights = null;
  88191. /**
  88192. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  88193. * soft lighting on the background.
  88194. */
  88195. _this.shadowBlurScale = 1;
  88196. /**
  88197. * Helps adjusting the shadow to a softer level if required.
  88198. * 0 means black shadows and 1 means no shadows.
  88199. */
  88200. _this.shadowLevel = 0;
  88201. /**
  88202. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  88203. * It is usually zero but might be interesting to modify according to your setup.
  88204. */
  88205. _this.sceneCenter = BABYLON.Vector3.Zero();
  88206. /**
  88207. * This helps specifying that the material is falling off to the sky box at grazing angle.
  88208. * This helps ensuring a nice transition when the camera goes under the ground.
  88209. */
  88210. _this.opacityFresnel = true;
  88211. /**
  88212. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  88213. * This helps adding a mirror texture on the ground.
  88214. */
  88215. _this.reflectionFresnel = false;
  88216. /**
  88217. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  88218. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  88219. */
  88220. _this.reflectionFalloffDistance = 0.0;
  88221. /**
  88222. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  88223. */
  88224. _this.reflectionAmount = 1.0;
  88225. /**
  88226. * This specifies the weight of the reflection at grazing angle.
  88227. */
  88228. _this.reflectionReflectance0 = 0.05;
  88229. /**
  88230. * This specifies the weight of the reflection at a perpendicular point of view.
  88231. */
  88232. _this.reflectionReflectance90 = 0.5;
  88233. /**
  88234. * Helps to directly use the maps channels instead of their level.
  88235. */
  88236. _this.useRGBColor = true;
  88237. /**
  88238. * This helps reducing the banding effect that could occur on the background.
  88239. */
  88240. _this.enableNoise = false;
  88241. _this._fovMultiplier = 1.0;
  88242. /**
  88243. * Enable the FOV adjustment feature controlled by fovMultiplier.
  88244. * @type {boolean}
  88245. */
  88246. _this.useEquirectangularFOV = false;
  88247. _this._maxSimultaneousLights = 4;
  88248. /**
  88249. * Number of Simultaneous lights allowed on the material.
  88250. */
  88251. _this.maxSimultaneousLights = 4;
  88252. /**
  88253. * Keep track of the image processing observer to allow dispose and replace.
  88254. */
  88255. _this._imageProcessingObserver = null;
  88256. // Temp values kept as cache in the material.
  88257. _this._renderTargets = new BABYLON.SmartArray(16);
  88258. _this._reflectionControls = BABYLON.Vector4.Zero();
  88259. // Setup the default processing configuration to the scene.
  88260. _this._attachImageProcessingConfiguration(null);
  88261. _this.getRenderTargetTextures = function () {
  88262. _this._renderTargets.reset();
  88263. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  88264. _this._renderTargets.push(_this._diffuseTexture);
  88265. }
  88266. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  88267. _this._renderTargets.push(_this._reflectionTexture);
  88268. }
  88269. return _this._renderTargets;
  88270. };
  88271. return _this;
  88272. }
  88273. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  88274. /**
  88275. * Sets the reflection reflectance fresnel values according to the default standard
  88276. * empirically know to work well :-)
  88277. */
  88278. set: function (value) {
  88279. var reflectionWeight = value;
  88280. if (reflectionWeight < 0.5) {
  88281. reflectionWeight = reflectionWeight * 2.0;
  88282. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  88283. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  88284. }
  88285. else {
  88286. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  88287. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  88288. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  88289. }
  88290. },
  88291. enumerable: true,
  88292. configurable: true
  88293. });
  88294. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  88295. /**
  88296. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  88297. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  88298. * Recommended to be keep at 1.0 except for special cases.
  88299. */
  88300. get: function () {
  88301. return this._fovMultiplier;
  88302. },
  88303. set: function (value) {
  88304. if (isNaN(value)) {
  88305. value = 1.0;
  88306. }
  88307. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  88308. },
  88309. enumerable: true,
  88310. configurable: true
  88311. });
  88312. /**
  88313. * Attaches a new image processing configuration to the PBR Material.
  88314. * @param configuration (if null the scene configuration will be use)
  88315. */
  88316. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  88317. var _this = this;
  88318. if (configuration === this._imageProcessingConfiguration) {
  88319. return;
  88320. }
  88321. // Detaches observer.
  88322. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88323. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88324. }
  88325. // Pick the scene configuration if needed.
  88326. if (!configuration) {
  88327. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  88328. }
  88329. else {
  88330. this._imageProcessingConfiguration = configuration;
  88331. }
  88332. // Attaches observer.
  88333. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  88334. _this._markAllSubMeshesAsImageProcessingDirty();
  88335. });
  88336. };
  88337. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  88338. /**
  88339. * Gets the image processing configuration used either in this material.
  88340. */
  88341. get: function () {
  88342. return this._imageProcessingConfiguration;
  88343. },
  88344. /**
  88345. * Sets the Default image processing configuration used either in the this material.
  88346. *
  88347. * If sets to null, the scene one is in use.
  88348. */
  88349. set: function (value) {
  88350. this._attachImageProcessingConfiguration(value);
  88351. // Ensure the effect will be rebuilt.
  88352. this._markAllSubMeshesAsTexturesDirty();
  88353. },
  88354. enumerable: true,
  88355. configurable: true
  88356. });
  88357. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  88358. /**
  88359. * Gets wether the color curves effect is enabled.
  88360. */
  88361. get: function () {
  88362. return this.imageProcessingConfiguration.colorCurvesEnabled;
  88363. },
  88364. /**
  88365. * Sets wether the color curves effect is enabled.
  88366. */
  88367. set: function (value) {
  88368. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  88369. },
  88370. enumerable: true,
  88371. configurable: true
  88372. });
  88373. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  88374. /**
  88375. * Gets wether the color grading effect is enabled.
  88376. */
  88377. get: function () {
  88378. return this.imageProcessingConfiguration.colorGradingEnabled;
  88379. },
  88380. /**
  88381. * Gets wether the color grading effect is enabled.
  88382. */
  88383. set: function (value) {
  88384. this.imageProcessingConfiguration.colorGradingEnabled = value;
  88385. },
  88386. enumerable: true,
  88387. configurable: true
  88388. });
  88389. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  88390. /**
  88391. * Gets wether tonemapping is enabled or not.
  88392. */
  88393. get: function () {
  88394. return this._imageProcessingConfiguration.toneMappingEnabled;
  88395. },
  88396. /**
  88397. * Sets wether tonemapping is enabled or not
  88398. */
  88399. set: function (value) {
  88400. this._imageProcessingConfiguration.toneMappingEnabled = value;
  88401. },
  88402. enumerable: true,
  88403. configurable: true
  88404. });
  88405. ;
  88406. ;
  88407. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  88408. /**
  88409. * The camera exposure used on this material.
  88410. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88411. * This corresponds to a photographic exposure.
  88412. */
  88413. get: function () {
  88414. return this._imageProcessingConfiguration.exposure;
  88415. },
  88416. /**
  88417. * The camera exposure used on this material.
  88418. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  88419. * This corresponds to a photographic exposure.
  88420. */
  88421. set: function (value) {
  88422. this._imageProcessingConfiguration.exposure = value;
  88423. },
  88424. enumerable: true,
  88425. configurable: true
  88426. });
  88427. ;
  88428. ;
  88429. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  88430. /**
  88431. * Gets The camera contrast used on this material.
  88432. */
  88433. get: function () {
  88434. return this._imageProcessingConfiguration.contrast;
  88435. },
  88436. /**
  88437. * Sets The camera contrast used on this material.
  88438. */
  88439. set: function (value) {
  88440. this._imageProcessingConfiguration.contrast = value;
  88441. },
  88442. enumerable: true,
  88443. configurable: true
  88444. });
  88445. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  88446. /**
  88447. * Gets the Color Grading 2D Lookup Texture.
  88448. */
  88449. get: function () {
  88450. return this._imageProcessingConfiguration.colorGradingTexture;
  88451. },
  88452. /**
  88453. * Sets the Color Grading 2D Lookup Texture.
  88454. */
  88455. set: function (value) {
  88456. this.imageProcessingConfiguration.colorGradingTexture = value;
  88457. },
  88458. enumerable: true,
  88459. configurable: true
  88460. });
  88461. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  88462. /**
  88463. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88464. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88465. * 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;
  88466. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88467. */
  88468. get: function () {
  88469. return this.imageProcessingConfiguration.colorCurves;
  88470. },
  88471. /**
  88472. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88473. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88474. * 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;
  88475. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88476. */
  88477. set: function (value) {
  88478. this.imageProcessingConfiguration.colorCurves = value;
  88479. },
  88480. enumerable: true,
  88481. configurable: true
  88482. });
  88483. /**
  88484. * The entire material has been created in order to prevent overdraw.
  88485. * @returns false
  88486. */
  88487. BackgroundMaterial.prototype.needAlphaTesting = function () {
  88488. return true;
  88489. };
  88490. /**
  88491. * The entire material has been created in order to prevent overdraw.
  88492. * @returns true if blending is enable
  88493. */
  88494. BackgroundMaterial.prototype.needAlphaBlending = function () {
  88495. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  88496. };
  88497. /**
  88498. * Checks wether the material is ready to be rendered for a given mesh.
  88499. * @param mesh The mesh to render
  88500. * @param subMesh The submesh to check against
  88501. * @param useInstances Specify wether or not the material is used with instances
  88502. * @returns true if all the dependencies are ready (Textures, Effects...)
  88503. */
  88504. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  88505. var _this = this;
  88506. if (useInstances === void 0) { useInstances = false; }
  88507. if (subMesh.effect && this.isFrozen) {
  88508. if (this._wasPreviouslyReady) {
  88509. return true;
  88510. }
  88511. }
  88512. if (!subMesh._materialDefines) {
  88513. subMesh._materialDefines = new BackgroundMaterialDefines();
  88514. }
  88515. var scene = this.getScene();
  88516. var defines = subMesh._materialDefines;
  88517. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  88518. if (defines._renderId === scene.getRenderId()) {
  88519. return true;
  88520. }
  88521. }
  88522. var engine = scene.getEngine();
  88523. // Lights
  88524. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  88525. defines._needNormals = true;
  88526. // Textures
  88527. if (defines._areTexturesDirty) {
  88528. defines._needUVs = false;
  88529. if (scene.texturesEnabled) {
  88530. if (scene.getEngine().getCaps().textureLOD) {
  88531. defines.TEXTURELODSUPPORT = true;
  88532. }
  88533. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88534. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  88535. return false;
  88536. }
  88537. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  88538. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  88539. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  88540. defines.OPACITYFRESNEL = this._opacityFresnel;
  88541. }
  88542. else {
  88543. defines.DIFFUSE = false;
  88544. defines.DIFFUSEHASALPHA = false;
  88545. defines.GAMMADIFFUSE = false;
  88546. defines.OPACITYFRESNEL = false;
  88547. }
  88548. var reflectionTexture = this._reflectionTexture;
  88549. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88550. if (!reflectionTexture.isReadyOrNotBlocking()) {
  88551. return false;
  88552. }
  88553. defines.REFLECTION = true;
  88554. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  88555. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  88556. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  88557. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  88558. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  88559. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  88560. defines.INVERTCUBICMAP = true;
  88561. }
  88562. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  88563. switch (reflectionTexture.coordinatesMode) {
  88564. case BABYLON.Texture.CUBIC_MODE:
  88565. case BABYLON.Texture.INVCUBIC_MODE:
  88566. defines.REFLECTIONMAP_CUBIC = true;
  88567. break;
  88568. case BABYLON.Texture.EXPLICIT_MODE:
  88569. defines.REFLECTIONMAP_EXPLICIT = true;
  88570. break;
  88571. case BABYLON.Texture.PLANAR_MODE:
  88572. defines.REFLECTIONMAP_PLANAR = true;
  88573. break;
  88574. case BABYLON.Texture.PROJECTION_MODE:
  88575. defines.REFLECTIONMAP_PROJECTION = true;
  88576. break;
  88577. case BABYLON.Texture.SKYBOX_MODE:
  88578. defines.REFLECTIONMAP_SKYBOX = true;
  88579. break;
  88580. case BABYLON.Texture.SPHERICAL_MODE:
  88581. defines.REFLECTIONMAP_SPHERICAL = true;
  88582. break;
  88583. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  88584. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  88585. break;
  88586. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  88587. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  88588. break;
  88589. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  88590. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  88591. break;
  88592. }
  88593. if (this.reflectionFresnel) {
  88594. defines.REFLECTIONFRESNEL = true;
  88595. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  88596. this._reflectionControls.x = this.reflectionAmount;
  88597. this._reflectionControls.y = this.reflectionReflectance0;
  88598. this._reflectionControls.z = this.reflectionReflectance90;
  88599. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  88600. }
  88601. else {
  88602. defines.REFLECTIONFRESNEL = false;
  88603. defines.REFLECTIONFALLOFF = false;
  88604. }
  88605. }
  88606. else {
  88607. defines.REFLECTION = false;
  88608. defines.REFLECTIONFALLOFF = false;
  88609. defines.REFLECTIONBLUR = false;
  88610. defines.REFLECTIONMAP_3D = false;
  88611. defines.REFLECTIONMAP_SPHERICAL = false;
  88612. defines.REFLECTIONMAP_PLANAR = false;
  88613. defines.REFLECTIONMAP_CUBIC = false;
  88614. defines.REFLECTIONMAP_PROJECTION = false;
  88615. defines.REFLECTIONMAP_SKYBOX = false;
  88616. defines.REFLECTIONMAP_EXPLICIT = false;
  88617. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  88618. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  88619. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  88620. defines.INVERTCUBICMAP = false;
  88621. defines.REFLECTIONMAP_OPPOSITEZ = false;
  88622. defines.LODINREFLECTIONALPHA = false;
  88623. defines.GAMMAREFLECTION = false;
  88624. }
  88625. }
  88626. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  88627. defines.USERGBCOLOR = this._useRGBColor;
  88628. defines.NOISE = this._enableNoise;
  88629. }
  88630. if (defines._areImageProcessingDirty) {
  88631. if (!this._imageProcessingConfiguration.isReady()) {
  88632. return false;
  88633. }
  88634. this._imageProcessingConfiguration.prepareDefines(defines);
  88635. }
  88636. // Misc.
  88637. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  88638. // Values that need to be evaluated on every frame
  88639. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  88640. // Attribs
  88641. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  88642. if (mesh) {
  88643. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  88644. mesh.createNormals(true);
  88645. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  88646. }
  88647. }
  88648. }
  88649. // Get correct effect
  88650. if (defines.isDirty) {
  88651. defines.markAsProcessed();
  88652. scene.resetCachedMaterial();
  88653. // Fallbacks
  88654. var fallbacks = new BABYLON.EffectFallbacks();
  88655. if (defines.FOG) {
  88656. fallbacks.addFallback(0, "FOG");
  88657. }
  88658. if (defines.POINTSIZE) {
  88659. fallbacks.addFallback(1, "POINTSIZE");
  88660. }
  88661. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  88662. if (defines.NUM_BONE_INFLUENCERS > 0) {
  88663. fallbacks.addCPUSkinningFallback(0, mesh);
  88664. }
  88665. //Attributes
  88666. var attribs = [BABYLON.VertexBuffer.PositionKind];
  88667. if (defines.NORMAL) {
  88668. attribs.push(BABYLON.VertexBuffer.NormalKind);
  88669. }
  88670. if (defines.UV1) {
  88671. attribs.push(BABYLON.VertexBuffer.UVKind);
  88672. }
  88673. if (defines.UV2) {
  88674. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  88675. }
  88676. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  88677. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  88678. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  88679. "vFogInfos", "vFogColor", "pointSize",
  88680. "vClipPlane", "mBones",
  88681. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  88682. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  88683. "shadowLevel", "alpha",
  88684. "vBackgroundCenter", "vReflectionControl",
  88685. "vDiffuseInfos", "diffuseMatrix",
  88686. ];
  88687. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  88688. var uniformBuffers = ["Material", "Scene"];
  88689. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  88690. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  88691. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  88692. uniformsNames: uniforms,
  88693. uniformBuffersNames: uniformBuffers,
  88694. samplers: samplers,
  88695. defines: defines,
  88696. maxSimultaneousLights: this._maxSimultaneousLights
  88697. });
  88698. var onCompiled = function (effect) {
  88699. if (_this.onCompiled) {
  88700. _this.onCompiled(effect);
  88701. }
  88702. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  88703. };
  88704. var join = defines.toString();
  88705. subMesh.setEffect(scene.getEngine().createEffect("background", {
  88706. attributes: attribs,
  88707. uniformsNames: uniforms,
  88708. uniformBuffersNames: uniformBuffers,
  88709. samplers: samplers,
  88710. defines: join,
  88711. fallbacks: fallbacks,
  88712. onCompiled: onCompiled,
  88713. onError: this.onError,
  88714. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  88715. }, engine), defines);
  88716. this.buildUniformLayout();
  88717. }
  88718. if (!subMesh.effect || !subMesh.effect.isReady()) {
  88719. return false;
  88720. }
  88721. defines._renderId = scene.getRenderId();
  88722. this._wasPreviouslyReady = true;
  88723. return true;
  88724. };
  88725. /**
  88726. * Build the uniform buffer used in the material.
  88727. */
  88728. BackgroundMaterial.prototype.buildUniformLayout = function () {
  88729. // Order is important !
  88730. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  88731. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  88732. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  88733. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  88734. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  88735. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  88736. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  88737. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  88738. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  88739. this._uniformBuffer.addUniform("pointSize", 1);
  88740. this._uniformBuffer.addUniform("shadowLevel", 1);
  88741. this._uniformBuffer.addUniform("alpha", 1);
  88742. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  88743. this._uniformBuffer.addUniform("vReflectionControl", 4);
  88744. this._uniformBuffer.create();
  88745. };
  88746. /**
  88747. * Unbind the material.
  88748. */
  88749. BackgroundMaterial.prototype.unbind = function () {
  88750. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  88751. this._uniformBuffer.setTexture("diffuseSampler", null);
  88752. }
  88753. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  88754. this._uniformBuffer.setTexture("reflectionSampler", null);
  88755. }
  88756. _super.prototype.unbind.call(this);
  88757. };
  88758. /**
  88759. * Bind only the world matrix to the material.
  88760. * @param world The world matrix to bind.
  88761. */
  88762. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  88763. this._activeEffect.setMatrix("world", world);
  88764. };
  88765. /**
  88766. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  88767. * @param world The world matrix to bind.
  88768. * @param subMesh The submesh to bind for.
  88769. */
  88770. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  88771. var scene = this.getScene();
  88772. var defines = subMesh._materialDefines;
  88773. if (!defines) {
  88774. return;
  88775. }
  88776. var effect = subMesh.effect;
  88777. if (!effect) {
  88778. return;
  88779. }
  88780. this._activeEffect = effect;
  88781. // Matrices
  88782. this.bindOnlyWorldMatrix(world);
  88783. // Bones
  88784. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  88785. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  88786. if (mustRebind) {
  88787. this._uniformBuffer.bindToEffect(effect, "Material");
  88788. this.bindViewProjection(effect);
  88789. var reflectionTexture = this._reflectionTexture;
  88790. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  88791. // Texture uniforms
  88792. if (scene.texturesEnabled) {
  88793. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88794. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  88795. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  88796. }
  88797. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88798. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  88799. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  88800. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  88801. }
  88802. }
  88803. if (this.shadowLevel > 0) {
  88804. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  88805. }
  88806. this._uniformBuffer.updateFloat("alpha", this.alpha);
  88807. // Point size
  88808. if (this.pointsCloud) {
  88809. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  88810. }
  88811. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  88812. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  88813. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  88814. }
  88815. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  88816. // Textures
  88817. if (scene.texturesEnabled) {
  88818. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  88819. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  88820. }
  88821. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  88822. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  88823. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  88824. }
  88825. else if (!defines.REFLECTIONBLUR) {
  88826. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  88827. }
  88828. else {
  88829. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  88830. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  88831. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  88832. }
  88833. if (defines.REFLECTIONFRESNEL) {
  88834. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  88835. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  88836. }
  88837. }
  88838. }
  88839. // Clip plane
  88840. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  88841. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  88842. }
  88843. if (mustRebind || !this.isFrozen) {
  88844. if (scene.lightsEnabled) {
  88845. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  88846. }
  88847. // View
  88848. this.bindView(effect);
  88849. // Fog
  88850. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  88851. // image processing
  88852. this._imageProcessingConfiguration.bind(this._activeEffect);
  88853. }
  88854. this._uniformBuffer.update();
  88855. this._afterBind(mesh);
  88856. };
  88857. /**
  88858. * Dispose the material.
  88859. * @param forceDisposeEffect Force disposal of the associated effect.
  88860. * @param forceDisposeTextures Force disposal of the associated textures.
  88861. */
  88862. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  88863. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  88864. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  88865. if (forceDisposeTextures) {
  88866. if (this.diffuseTexture) {
  88867. this.diffuseTexture.dispose();
  88868. }
  88869. if (this.reflectionTexture) {
  88870. this.reflectionTexture.dispose();
  88871. }
  88872. }
  88873. this._renderTargets.dispose();
  88874. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  88875. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  88876. }
  88877. _super.prototype.dispose.call(this, forceDisposeEffect);
  88878. };
  88879. /**
  88880. * Clones the material.
  88881. * @param name The cloned name.
  88882. * @returns The cloned material.
  88883. */
  88884. BackgroundMaterial.prototype.clone = function (name) {
  88885. var _this = this;
  88886. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  88887. };
  88888. /**
  88889. * Serializes the current material to its JSON representation.
  88890. * @returns The JSON representation.
  88891. */
  88892. BackgroundMaterial.prototype.serialize = function () {
  88893. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  88894. serializationObject.customType = "BABYLON.BackgroundMaterial";
  88895. return serializationObject;
  88896. };
  88897. /**
  88898. * Gets the class name of the material
  88899. * @returns "BackgroundMaterial"
  88900. */
  88901. BackgroundMaterial.prototype.getClassName = function () {
  88902. return "BackgroundMaterial";
  88903. };
  88904. /**
  88905. * Parse a JSON input to create back a background material.
  88906. * @param source The JSON data to parse
  88907. * @param scene The scene to create the parsed material in
  88908. * @param rootUrl The root url of the assets the material depends upon
  88909. * @returns the instantiated BackgroundMaterial.
  88910. */
  88911. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  88912. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  88913. };
  88914. /**
  88915. * Standard reflectance value at parallel view angle.
  88916. */
  88917. BackgroundMaterial.StandardReflectance0 = 0.05;
  88918. /**
  88919. * Standard reflectance value at grazing angle.
  88920. */
  88921. BackgroundMaterial.StandardReflectance90 = 0.5;
  88922. __decorate([
  88923. BABYLON.serializeAsColor3()
  88924. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  88925. __decorate([
  88926. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88927. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  88928. __decorate([
  88929. BABYLON.serialize()
  88930. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  88931. __decorate([
  88932. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88933. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  88934. __decorate([
  88935. BABYLON.serializeAsColor3()
  88936. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  88937. __decorate([
  88938. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88939. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  88940. __decorate([
  88941. BABYLON.serialize()
  88942. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  88943. __decorate([
  88944. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88945. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  88946. __decorate([
  88947. BABYLON.serializeAsColor3()
  88948. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  88949. __decorate([
  88950. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88951. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  88952. __decorate([
  88953. BABYLON.serialize()
  88954. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  88955. __decorate([
  88956. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  88957. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  88958. __decorate([
  88959. BABYLON.serializeAsTexture()
  88960. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  88961. __decorate([
  88962. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88963. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  88964. __decorate([
  88965. BABYLON.serialize()
  88966. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  88967. __decorate([
  88968. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88969. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  88970. __decorate([
  88971. BABYLON.serializeAsTexture()
  88972. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  88973. __decorate([
  88974. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88975. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  88976. __decorate([
  88977. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88978. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  88979. __decorate([
  88980. BABYLON.serialize()
  88981. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  88982. __decorate([
  88983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88984. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  88985. __decorate([
  88986. BABYLON.serialize()
  88987. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  88988. __decorate([
  88989. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88990. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  88991. __decorate([
  88992. BABYLON.serializeAsVector3()
  88993. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  88994. __decorate([
  88995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  88996. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  88997. __decorate([
  88998. BABYLON.serialize()
  88999. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  89000. __decorate([
  89001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89002. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  89003. __decorate([
  89004. BABYLON.serialize()
  89005. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  89006. __decorate([
  89007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89008. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  89009. __decorate([
  89010. BABYLON.serialize()
  89011. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  89012. __decorate([
  89013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89014. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  89015. __decorate([
  89016. BABYLON.serialize()
  89017. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  89018. __decorate([
  89019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89020. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  89021. __decorate([
  89022. BABYLON.serialize()
  89023. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  89024. __decorate([
  89025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89026. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  89027. __decorate([
  89028. BABYLON.serialize()
  89029. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  89030. __decorate([
  89031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89032. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  89033. __decorate([
  89034. BABYLON.serialize()
  89035. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  89036. __decorate([
  89037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89038. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  89039. __decorate([
  89040. BABYLON.serialize()
  89041. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  89042. __decorate([
  89043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89044. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  89045. __decorate([
  89046. BABYLON.serialize()
  89047. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  89048. __decorate([
  89049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  89050. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  89051. __decorate([
  89052. BABYLON.serializeAsImageProcessingConfiguration()
  89053. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  89054. return BackgroundMaterial;
  89055. }(BABYLON.PushMaterial));
  89056. BABYLON.BackgroundMaterial = BackgroundMaterial;
  89057. })(BABYLON || (BABYLON = {}));
  89058. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  89059. var __assign = (this && this.__assign) || Object.assign || function(t) {
  89060. for (var s, i = 1, n = arguments.length; i < n; i++) {
  89061. s = arguments[i];
  89062. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  89063. t[p] = s[p];
  89064. }
  89065. return t;
  89066. };
  89067. var BABYLON;
  89068. (function (BABYLON) {
  89069. /**
  89070. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  89071. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  89072. * It also helps with the default setup of your imageProcessing configuration.
  89073. */
  89074. var EnvironmentHelper = /** @class */ (function () {
  89075. /**
  89076. * constructor
  89077. * @param options
  89078. * @param scene The scene to add the material to
  89079. */
  89080. function EnvironmentHelper(options, scene) {
  89081. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  89082. this._scene = scene;
  89083. this._setupBackground();
  89084. this._setupImageProcessing();
  89085. }
  89086. /**
  89087. * Creates the default options for the helper.
  89088. */
  89089. EnvironmentHelper._getDefaultOptions = function () {
  89090. return {
  89091. createGround: true,
  89092. groundSize: 15,
  89093. groundTexture: this._groundTextureCDNUrl,
  89094. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89095. groundOpacity: 0.9,
  89096. enableGroundShadow: true,
  89097. groundShadowLevel: 0.5,
  89098. enableGroundMirror: false,
  89099. groundMirrorSizeRatio: 0.3,
  89100. groundMirrorBlurKernel: 64,
  89101. groundMirrorAmount: 1,
  89102. groundMirrorFresnelWeight: 1,
  89103. groundMirrorFallOffDistance: 0,
  89104. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  89105. groundYBias: 0.00001,
  89106. createSkybox: true,
  89107. skyboxSize: 20,
  89108. skyboxTexture: this._skyboxTextureCDNUrl,
  89109. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  89110. backgroundYRotation: 0,
  89111. sizeAuto: true,
  89112. rootPosition: BABYLON.Vector3.Zero(),
  89113. setupImageProcessing: true,
  89114. environmentTexture: this._environmentTextureCDNUrl,
  89115. cameraExposure: 0.8,
  89116. cameraContrast: 1.2,
  89117. toneMappingEnabled: true,
  89118. };
  89119. };
  89120. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  89121. /**
  89122. * Gets the root mesh created by the helper.
  89123. */
  89124. get: function () {
  89125. return this._rootMesh;
  89126. },
  89127. enumerable: true,
  89128. configurable: true
  89129. });
  89130. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  89131. /**
  89132. * Gets the skybox created by the helper.
  89133. */
  89134. get: function () {
  89135. return this._skybox;
  89136. },
  89137. enumerable: true,
  89138. configurable: true
  89139. });
  89140. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  89141. /**
  89142. * Gets the skybox texture created by the helper.
  89143. */
  89144. get: function () {
  89145. return this._skyboxTexture;
  89146. },
  89147. enumerable: true,
  89148. configurable: true
  89149. });
  89150. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  89151. /**
  89152. * Gets the skybox material created by the helper.
  89153. */
  89154. get: function () {
  89155. return this._skyboxMaterial;
  89156. },
  89157. enumerable: true,
  89158. configurable: true
  89159. });
  89160. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  89161. /**
  89162. * Gets the ground mesh created by the helper.
  89163. */
  89164. get: function () {
  89165. return this._ground;
  89166. },
  89167. enumerable: true,
  89168. configurable: true
  89169. });
  89170. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  89171. /**
  89172. * Gets the ground texture created by the helper.
  89173. */
  89174. get: function () {
  89175. return this._groundTexture;
  89176. },
  89177. enumerable: true,
  89178. configurable: true
  89179. });
  89180. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  89181. /**
  89182. * Gets the ground mirror created by the helper.
  89183. */
  89184. get: function () {
  89185. return this._groundMirror;
  89186. },
  89187. enumerable: true,
  89188. configurable: true
  89189. });
  89190. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  89191. /**
  89192. * Gets the ground mirror render list to helps pushing the meshes
  89193. * you wish in the ground reflection.
  89194. */
  89195. get: function () {
  89196. if (this._groundMirror) {
  89197. return this._groundMirror.renderList;
  89198. }
  89199. return null;
  89200. },
  89201. enumerable: true,
  89202. configurable: true
  89203. });
  89204. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  89205. /**
  89206. * Gets the ground material created by the helper.
  89207. */
  89208. get: function () {
  89209. return this._groundMaterial;
  89210. },
  89211. enumerable: true,
  89212. configurable: true
  89213. });
  89214. /**
  89215. * Updates the background according to the new options
  89216. * @param options
  89217. */
  89218. EnvironmentHelper.prototype.updateOptions = function (options) {
  89219. var newOptions = __assign({}, this._options, options);
  89220. if (this._ground && !newOptions.createGround) {
  89221. this._ground.dispose();
  89222. this._ground = null;
  89223. }
  89224. if (this._groundMaterial && !newOptions.createGround) {
  89225. this._groundMaterial.dispose();
  89226. this._groundMaterial = null;
  89227. }
  89228. if (this._groundTexture) {
  89229. if (this._options.groundTexture != newOptions.groundTexture) {
  89230. this._groundTexture.dispose();
  89231. this._groundTexture = null;
  89232. }
  89233. }
  89234. if (this._skybox && !newOptions.createSkybox) {
  89235. this._skybox.dispose();
  89236. this._skybox = null;
  89237. }
  89238. if (this._skyboxMaterial && !newOptions.createSkybox) {
  89239. this._skyboxMaterial.dispose();
  89240. this._skyboxMaterial = null;
  89241. }
  89242. if (this._skyboxTexture) {
  89243. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  89244. this._skyboxTexture.dispose();
  89245. this._skyboxTexture = null;
  89246. }
  89247. }
  89248. if (this._groundMirror && !newOptions.enableGroundMirror) {
  89249. this._groundMirror.dispose();
  89250. this._groundMirror = null;
  89251. }
  89252. if (this._scene.environmentTexture) {
  89253. if (this._options.environmentTexture != newOptions.environmentTexture) {
  89254. this._scene.environmentTexture.dispose();
  89255. }
  89256. }
  89257. this._options = newOptions;
  89258. this._setupBackground();
  89259. this._setupImageProcessing();
  89260. };
  89261. /**
  89262. * Sets the primary color of all the available elements.
  89263. * @param color
  89264. */
  89265. EnvironmentHelper.prototype.setMainColor = function (color) {
  89266. if (this.groundMaterial) {
  89267. this.groundMaterial.primaryColor = color;
  89268. }
  89269. if (this.skyboxMaterial) {
  89270. this.skyboxMaterial.primaryColor = color;
  89271. }
  89272. if (this.groundMirror) {
  89273. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  89274. }
  89275. };
  89276. /**
  89277. * Setup the image processing according to the specified options.
  89278. */
  89279. EnvironmentHelper.prototype._setupImageProcessing = function () {
  89280. if (this._options.setupImageProcessing) {
  89281. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  89282. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  89283. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  89284. this._setupEnvironmentTexture();
  89285. }
  89286. };
  89287. /**
  89288. * Setup the environment texture according to the specified options.
  89289. */
  89290. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  89291. if (this._scene.environmentTexture) {
  89292. return;
  89293. }
  89294. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  89295. this._scene.environmentTexture = this._options.environmentTexture;
  89296. return;
  89297. }
  89298. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  89299. this._scene.environmentTexture = environmentTexture;
  89300. };
  89301. /**
  89302. * Setup the background according to the specified options.
  89303. */
  89304. EnvironmentHelper.prototype._setupBackground = function () {
  89305. if (!this._rootMesh) {
  89306. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  89307. }
  89308. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  89309. var sceneSize = this._getSceneSize();
  89310. if (this._options.createGround) {
  89311. this._setupGround(sceneSize);
  89312. this._setupGroundMaterial();
  89313. this._setupGroundDiffuseTexture();
  89314. if (this._options.enableGroundMirror) {
  89315. this._setupGroundMirrorTexture(sceneSize);
  89316. }
  89317. this._setupMirrorInGroundMaterial();
  89318. }
  89319. if (this._options.createSkybox) {
  89320. this._setupSkybox(sceneSize);
  89321. this._setupSkyboxMaterial();
  89322. this._setupSkyboxReflectionTexture();
  89323. }
  89324. this._rootMesh.position.x = sceneSize.rootPosition.x;
  89325. this._rootMesh.position.z = sceneSize.rootPosition.z;
  89326. this._rootMesh.position.y = sceneSize.rootPosition.y;
  89327. };
  89328. /**
  89329. * Get the scene sizes according to the setup.
  89330. */
  89331. EnvironmentHelper.prototype._getSceneSize = function () {
  89332. var _this = this;
  89333. var groundSize = this._options.groundSize;
  89334. var skyboxSize = this._options.skyboxSize;
  89335. var rootPosition = this._options.rootPosition;
  89336. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  89337. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89338. }
  89339. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  89340. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  89341. });
  89342. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  89343. if (this._options.sizeAuto) {
  89344. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  89345. this._scene.activeCamera.upperRadiusLimit) {
  89346. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  89347. skyboxSize = groundSize;
  89348. }
  89349. var sceneDiagonalLenght = sceneDiagonal.length();
  89350. if (sceneDiagonalLenght > groundSize) {
  89351. groundSize = sceneDiagonalLenght * 2;
  89352. skyboxSize = groundSize;
  89353. }
  89354. // 10 % bigger.
  89355. groundSize *= 1.1;
  89356. skyboxSize *= 1.5;
  89357. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  89358. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  89359. }
  89360. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  89361. };
  89362. /**
  89363. * Setup the ground according to the specified options.
  89364. */
  89365. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  89366. var _this = this;
  89367. if (!this._ground) {
  89368. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  89369. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  89370. this._ground.parent = this._rootMesh;
  89371. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  89372. }
  89373. this._ground.receiveShadows = this._options.enableGroundShadow;
  89374. };
  89375. /**
  89376. * Setup the ground material according to the specified options.
  89377. */
  89378. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  89379. if (!this._groundMaterial) {
  89380. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  89381. }
  89382. this._groundMaterial.alpha = this._options.groundOpacity;
  89383. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  89384. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  89385. this._groundMaterial.primaryLevel = 1;
  89386. this._groundMaterial.primaryColor = this._options.groundColor;
  89387. this._groundMaterial.secondaryLevel = 0;
  89388. this._groundMaterial.tertiaryLevel = 0;
  89389. this._groundMaterial.useRGBColor = false;
  89390. this._groundMaterial.enableNoise = true;
  89391. if (this._ground) {
  89392. this._ground.material = this._groundMaterial;
  89393. }
  89394. };
  89395. /**
  89396. * Setup the ground diffuse texture according to the specified options.
  89397. */
  89398. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  89399. if (!this._groundMaterial) {
  89400. return;
  89401. }
  89402. if (this._groundTexture) {
  89403. return;
  89404. }
  89405. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  89406. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  89407. return;
  89408. }
  89409. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene);
  89410. diffuseTexture.gammaSpace = false;
  89411. diffuseTexture.hasAlpha = true;
  89412. this._groundMaterial.diffuseTexture = diffuseTexture;
  89413. };
  89414. /**
  89415. * Setup the ground mirror texture according to the specified options.
  89416. */
  89417. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  89418. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89419. if (!this._groundMirror) {
  89420. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  89421. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  89422. this._groundMirror.anisotropicFilteringLevel = 1;
  89423. this._groundMirror.wrapU = wrapping;
  89424. this._groundMirror.wrapV = wrapping;
  89425. this._groundMirror.gammaSpace = false;
  89426. if (this._groundMirror.renderList) {
  89427. for (var i = 0; i < this._scene.meshes.length; i++) {
  89428. var mesh = this._scene.meshes[i];
  89429. if (mesh !== this._ground &&
  89430. mesh !== this._skybox &&
  89431. mesh !== this._rootMesh) {
  89432. this._groundMirror.renderList.push(mesh);
  89433. }
  89434. }
  89435. }
  89436. }
  89437. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  89438. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  89439. };
  89440. /**
  89441. * Setup the ground to receive the mirror texture.
  89442. */
  89443. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  89444. if (this._groundMaterial) {
  89445. this._groundMaterial.reflectionTexture = this._groundMirror;
  89446. this._groundMaterial.reflectionFresnel = true;
  89447. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  89448. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  89449. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  89450. }
  89451. };
  89452. /**
  89453. * Setup the skybox according to the specified options.
  89454. */
  89455. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  89456. var _this = this;
  89457. if (!this._skybox) {
  89458. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  89459. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  89460. }
  89461. this._skybox.parent = this._rootMesh;
  89462. };
  89463. /**
  89464. * Setup the skybox material according to the specified options.
  89465. */
  89466. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  89467. if (!this._skybox) {
  89468. return;
  89469. }
  89470. if (!this._skyboxMaterial) {
  89471. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  89472. }
  89473. this._skyboxMaterial.useRGBColor = false;
  89474. this._skyboxMaterial.primaryLevel = 1;
  89475. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  89476. this._skyboxMaterial.secondaryLevel = 0;
  89477. this._skyboxMaterial.tertiaryLevel = 0;
  89478. this._skyboxMaterial.enableNoise = true;
  89479. this._skybox.material = this._skyboxMaterial;
  89480. };
  89481. /**
  89482. * Setup the skybox reflection texture according to the specified options.
  89483. */
  89484. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  89485. if (!this._skyboxMaterial) {
  89486. return;
  89487. }
  89488. if (this._skyboxTexture) {
  89489. return;
  89490. }
  89491. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  89492. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  89493. return;
  89494. }
  89495. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene);
  89496. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  89497. this._skyboxTexture.gammaSpace = false;
  89498. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  89499. };
  89500. /**
  89501. * Dispose all the elements created by the Helper.
  89502. */
  89503. EnvironmentHelper.prototype.dispose = function () {
  89504. if (this._groundMaterial) {
  89505. this._groundMaterial.dispose(true, true);
  89506. }
  89507. if (this._skyboxMaterial) {
  89508. this._skyboxMaterial.dispose(true, true);
  89509. }
  89510. this._rootMesh.dispose(false);
  89511. };
  89512. /**
  89513. * Default ground texture URL.
  89514. */
  89515. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  89516. /**
  89517. * Default skybox texture URL.
  89518. */
  89519. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  89520. /**
  89521. * Default environment texture URL.
  89522. */
  89523. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  89524. return EnvironmentHelper;
  89525. }());
  89526. BABYLON.EnvironmentHelper = EnvironmentHelper;
  89527. })(BABYLON || (BABYLON = {}));
  89528. //# sourceMappingURL=babylon.environmentHelper.js.map
  89529. var BABYLON;
  89530. (function (BABYLON) {
  89531. /**
  89532. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  89533. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  89534. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  89535. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  89536. */
  89537. var VideoDome = /** @class */ (function (_super) {
  89538. __extends(VideoDome, _super);
  89539. /**
  89540. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  89541. * @param name Element's name, child elements will append suffixes for their own names.
  89542. * @param urlsOrVideo
  89543. * @param options An object containing optional or exposed sub element properties:
  89544. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  89545. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  89546. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  89547. * @param options **loop=true** Automatically loop video on end.
  89548. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  89549. */
  89550. function VideoDome(name, urlsOrVideo, options, scene) {
  89551. var _this = _super.call(this, name, scene) || this;
  89552. // set defaults and manage values
  89553. name = name || "videoDome";
  89554. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  89555. options.clickToPlay = Boolean(options.clickToPlay);
  89556. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  89557. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  89558. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  89559. // create
  89560. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  89561. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  89562. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  89563. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  89564. flat: false,
  89565. radius: options.size,
  89566. subdivisions: options.resolution,
  89567. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  89568. }, scene);
  89569. // configure material
  89570. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  89571. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  89572. material.reflectionTexture = _this._videoTexture;
  89573. material.useEquirectangularFOV = true;
  89574. material.fovMultiplier = 1.0;
  89575. // configure mesh
  89576. _this._mesh.material = material;
  89577. _this._mesh.parent = _this;
  89578. // optional configuration
  89579. if (options.clickToPlay) {
  89580. scene.onPointerUp = function () {
  89581. _this._videoTexture.video.play();
  89582. };
  89583. }
  89584. return _this;
  89585. }
  89586. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  89587. /**
  89588. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  89589. * Also see the options.resolution property.
  89590. */
  89591. get: function () {
  89592. return this._material.fovMultiplier;
  89593. },
  89594. set: function (value) {
  89595. this._material.fovMultiplier = value;
  89596. },
  89597. enumerable: true,
  89598. configurable: true
  89599. });
  89600. return VideoDome;
  89601. }(BABYLON.Node));
  89602. BABYLON.VideoDome = VideoDome;
  89603. })(BABYLON || (BABYLON = {}));
  89604. //# sourceMappingURL=babylon.videoDome.js.map
  89605. 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\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<0.4)\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)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\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*vRefractionInfos.x;\n#endif\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*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\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*vReflectionInfos.x;\n#endif\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\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)\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#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\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\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=toLinearSpace(texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb)*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(reflectionCoords,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\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\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\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\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\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\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\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,1.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 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) {\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/height;\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+gravity)*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction;\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#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 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{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\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 vec2 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.y*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","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\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);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/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;\n}\ngl_FragColor=original;\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}","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D originalSampler;\nuniform sampler2D circleOfConfusionSampler;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(originalSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred1=texture2D(textureSampler,vUV);\ngl_FragColor=mix(original,blurred1,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(textureSampler,vUV); \nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred2,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nvec4 blurred3=texture2D(textureSampler,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred1,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred1,blurred2,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred2,blurred3,(coc-0.66)/0.34);\n}\n#endif\n}\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}","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}\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{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\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\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\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\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{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,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\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\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\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,color.rgb);\n#endif\ngl_FragColor=color;\n}\n"};
  89606. 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}\nvec3 dither(vec2 seed,vec3 color) {\nfloat rand=getRand(seed);\ncolor+=mix(-0.5/255.0,0.5/255.0,rand);\ncolor=max(color,0.0);\nreturn color;\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};\nuniform sampler2D shadowSampler{X};\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;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\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};\nuniform sampler2D shadowSampler{X};\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 computeShadowWithPCFCube(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 computeShadowWithPCF(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#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=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef INVERTCUBICMAP\ncoords.y=1.0-coords.y;\n#endif\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition );\n#endif\nreturn vec3(reflectionMatrix*vec4(coords,0));\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,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,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,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#else\n#ifdef 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#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,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#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)\n{\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 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\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,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);\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,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);\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,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);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","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","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\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\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\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};","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;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\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 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  89607. globalObject["BABYLON"] = BABYLON;
  89608. var EffectFallbacks = BABYLON.EffectFallbacks;var EffectCreationOptions = BABYLON.EffectCreationOptions;var Effect = BABYLON.Effect;var KeyboardEventTypes = BABYLON.KeyboardEventTypes;var KeyboardInfo = BABYLON.KeyboardInfo;var KeyboardInfoPre = BABYLON.KeyboardInfoPre;var PointerEventTypes = BABYLON.PointerEventTypes;var PointerInfoBase = BABYLON.PointerInfoBase;var PointerInfoPre = BABYLON.PointerInfoPre;var PointerInfo = BABYLON.PointerInfo;var Color3 = BABYLON.Color3;var Color4 = BABYLON.Color4;var Vector2 = BABYLON.Vector2;var Vector3 = BABYLON.Vector3;var Vector4 = BABYLON.Vector4;var Size = BABYLON.Size;var Quaternion = BABYLON.Quaternion;var Matrix = BABYLON.Matrix;var Plane = BABYLON.Plane;var Viewport = BABYLON.Viewport;var Frustum = BABYLON.Frustum;var Axis = BABYLON.Axis;var BezierCurve = BABYLON.BezierCurve;var Angle = BABYLON.Angle;var Arc2 = BABYLON.Arc2;var Path2 = BABYLON.Path2;var Path3D = BABYLON.Path3D;var Curve3 = BABYLON.Curve3;var PositionNormalVertex = BABYLON.PositionNormalVertex;var PositionNormalTextureVertex = BABYLON.PositionNormalTextureVertex;var Tmp = BABYLON.Tmp;var Scalar = BABYLON.Scalar;var expandToProperty = BABYLON.expandToProperty;var serialize = BABYLON.serialize;var serializeAsTexture = BABYLON.serializeAsTexture;var serializeAsColor3 = BABYLON.serializeAsColor3;var serializeAsFresnelParameters = BABYLON.serializeAsFresnelParameters;var serializeAsVector2 = BABYLON.serializeAsVector2;var serializeAsVector3 = BABYLON.serializeAsVector3;var serializeAsMeshReference = BABYLON.serializeAsMeshReference;var serializeAsColorCurves = BABYLON.serializeAsColorCurves;var serializeAsColor4 = BABYLON.serializeAsColor4;var serializeAsImageProcessingConfiguration = BABYLON.serializeAsImageProcessingConfiguration;var serializeAsQuaternion = BABYLON.serializeAsQuaternion;var SerializationHelper = BABYLON.SerializationHelper;var Deferred = BABYLON.Deferred;var EventState = BABYLON.EventState;var Observer = BABYLON.Observer;var MultiObserver = BABYLON.MultiObserver;var Observable = BABYLON.Observable;var SmartArray = BABYLON.SmartArray;var SmartArrayNoDuplicate = BABYLON.SmartArrayNoDuplicate;var LoadFileError = BABYLON.LoadFileError;var RetryStrategy = BABYLON.RetryStrategy;var Tools = BABYLON.Tools;var PerfCounter = BABYLON.PerfCounter;var className = BABYLON.className;var AsyncLoop = BABYLON.AsyncLoop;var PromisePolyfill = BABYLON.PromisePolyfill;var _AlphaState = BABYLON._AlphaState;var _DepthCullingState = BABYLON._DepthCullingState;var _StencilState = BABYLON._StencilState;var InstancingAttributeInfo = BABYLON.InstancingAttributeInfo;var RenderTargetCreationOptions = BABYLON.RenderTargetCreationOptions;var EngineCapabilities = BABYLON.EngineCapabilities;var Engine = BABYLON.Engine;var Node = BABYLON.Node;var BoundingSphere = BABYLON.BoundingSphere;var BoundingBox = BABYLON.BoundingBox;var BoundingInfo = BABYLON.BoundingInfo;var TransformNode = BABYLON.TransformNode;var AbstractMesh = BABYLON.AbstractMesh;var Light = BABYLON.Light;var Camera = BABYLON.Camera;var RenderingManager = BABYLON.RenderingManager;var RenderingGroup = BABYLON.RenderingGroup;var RenderingGroupInfo = BABYLON.RenderingGroupInfo;var Scene = BABYLON.Scene;var KeepAssets = BABYLON.KeepAssets;var AssetContainer = BABYLON.AssetContainer;var Buffer = BABYLON.Buffer;var VertexBuffer = BABYLON.VertexBuffer;var DummyInternalTextureTracker = BABYLON.DummyInternalTextureTracker;var InternalTexture = BABYLON.InternalTexture;var BaseTexture = BABYLON.BaseTexture;var Texture = BABYLON.Texture;var _InstancesBatch = BABYLON._InstancesBatch;var Mesh = BABYLON.Mesh;var BaseSubMesh = BABYLON.BaseSubMesh;var SubMesh = BABYLON.SubMesh;var MaterialDefines = BABYLON.MaterialDefines;var Material = BABYLON.Material;var UniformBuffer = BABYLON.UniformBuffer;var VertexData = BABYLON.VertexData;var Geometry = BABYLON.Geometry;var _PrimitiveGeometry = BABYLON._PrimitiveGeometry;var RibbonGeometry = BABYLON.RibbonGeometry;var BoxGeometry = BABYLON.BoxGeometry;var SphereGeometry = BABYLON.SphereGeometry;var DiscGeometry = BABYLON.DiscGeometry;var CylinderGeometry = BABYLON.CylinderGeometry;var TorusGeometry = BABYLON.TorusGeometry;var GroundGeometry = BABYLON.GroundGeometry;var TiledGroundGeometry = BABYLON.TiledGroundGeometry;var PlaneGeometry = BABYLON.PlaneGeometry;var TorusKnotGeometry = BABYLON.TorusKnotGeometry;var PostProcessManager = BABYLON.PostProcessManager;var PerformanceMonitor = BABYLON.PerformanceMonitor;var RollingAverage = BABYLON.RollingAverage;var ImageProcessingConfiguration = BABYLON.ImageProcessingConfiguration;var ColorGradingTexture = BABYLON.ColorGradingTexture;var ColorCurves = BABYLON.ColorCurves;var MaterialHelper = BABYLON.MaterialHelper;var PushMaterial = BABYLON.PushMaterial;var StandardMaterialDefines = BABYLON.StandardMaterialDefines;var StandardMaterial = BABYLON.StandardMaterial;var PBRBaseMaterial = BABYLON.PBRBaseMaterial;var PBRBaseSimpleMaterial = BABYLON.PBRBaseSimpleMaterial;var PBRMaterial = BABYLON.PBRMaterial;var PBRMetallicRoughnessMaterial = BABYLON.PBRMetallicRoughnessMaterial;var PBRSpecularGlossinessMaterial = BABYLON.PBRSpecularGlossinessMaterial;var CameraInputsManager = BABYLON.CameraInputsManager;var TargetCamera = BABYLON.TargetCamera;var FreeCameraMouseInput = BABYLON.FreeCameraMouseInput;var FreeCameraKeyboardMoveInput = BABYLON.FreeCameraKeyboardMoveInput;var FreeCameraInputsManager = BABYLON.FreeCameraInputsManager;var FreeCamera = BABYLON.FreeCamera;var ArcRotateCameraKeyboardMoveInput = BABYLON.ArcRotateCameraKeyboardMoveInput;var ArcRotateCameraMouseWheelInput = BABYLON.ArcRotateCameraMouseWheelInput;var ArcRotateCameraPointersInput = BABYLON.ArcRotateCameraPointersInput;var ArcRotateCameraInputsManager = BABYLON.ArcRotateCameraInputsManager;var ArcRotateCamera = BABYLON.ArcRotateCamera;var HemisphericLight = BABYLON.HemisphericLight;var ShadowLight = BABYLON.ShadowLight;var PointLight = BABYLON.PointLight;var DirectionalLight = BABYLON.DirectionalLight;var SpotLight = BABYLON.SpotLight;var AnimationRange = BABYLON.AnimationRange;var AnimationEvent = BABYLON.AnimationEvent;var PathCursor = BABYLON.PathCursor;var Animation = BABYLON.Animation;var TargetedAnimation = BABYLON.TargetedAnimation;var AnimationGroup = BABYLON.AnimationGroup;var RuntimeAnimation = BABYLON.RuntimeAnimation;var Animatable = BABYLON.Animatable;var EasingFunction = BABYLON.EasingFunction;var CircleEase = BABYLON.CircleEase;var BackEase = BABYLON.BackEase;var BounceEase = BABYLON.BounceEase;var CubicEase = BABYLON.CubicEase;var ElasticEase = BABYLON.ElasticEase;var ExponentialEase = BABYLON.ExponentialEase;var PowerEase = BABYLON.PowerEase;var QuadraticEase = BABYLON.QuadraticEase;var QuarticEase = BABYLON.QuarticEase;var QuinticEase = BABYLON.QuinticEase;var SineEase = BABYLON.SineEase;var BezierCurveEase = BABYLON.BezierCurveEase;var Condition = BABYLON.Condition;var ValueCondition = BABYLON.ValueCondition;var PredicateCondition = BABYLON.PredicateCondition;var StateCondition = BABYLON.StateCondition;var Action = BABYLON.Action;var ActionEvent = BABYLON.ActionEvent;var ActionManager = BABYLON.ActionManager;var InterpolateValueAction = BABYLON.InterpolateValueAction;var SwitchBooleanAction = BABYLON.SwitchBooleanAction;var SetStateAction = BABYLON.SetStateAction;var SetValueAction = BABYLON.SetValueAction;var IncrementValueAction = BABYLON.IncrementValueAction;var PlayAnimationAction = BABYLON.PlayAnimationAction;var StopAnimationAction = BABYLON.StopAnimationAction;var DoNothingAction = BABYLON.DoNothingAction;var CombineAction = BABYLON.CombineAction;var ExecuteCodeAction = BABYLON.ExecuteCodeAction;var SetParentAction = BABYLON.SetParentAction;var PlaySoundAction = BABYLON.PlaySoundAction;var StopSoundAction = BABYLON.StopSoundAction;var SpriteManager = BABYLON.SpriteManager;var Sprite = BABYLON.Sprite;var IntersectionInfo = BABYLON.IntersectionInfo;var PickingInfo = BABYLON.PickingInfo;var Ray = BABYLON.Ray;var Collider = BABYLON.Collider;var CollisionCoordinatorWorker = BABYLON.CollisionCoordinatorWorker;var CollisionCoordinatorLegacy = BABYLON.CollisionCoordinatorLegacy;var Particle = BABYLON.Particle;var ParticleSystem = BABYLON.ParticleSystem;var BoxParticleEmitter = BABYLON.BoxParticleEmitter;var ConeParticleEmitter = BABYLON.ConeParticleEmitter;var SphereParticleEmitter = BABYLON.SphereParticleEmitter;var SphereDirectedParticleEmitter = BABYLON.SphereDirectedParticleEmitter;var GPUParticleSystem = BABYLON.GPUParticleSystem;var SolidParticle = BABYLON.SolidParticle;var ModelShape = BABYLON.ModelShape;var DepthSortedParticle = BABYLON.DepthSortedParticle;var SolidParticleSystem = BABYLON.SolidParticleSystem;var ShaderMaterial = BABYLON.ShaderMaterial;var GroundMesh = BABYLON.GroundMesh;var InstancedMesh = BABYLON.InstancedMesh;var LinesMesh = BABYLON.LinesMesh;var MeshBuilder = BABYLON.MeshBuilder;var DracoCompression = BABYLON.DracoCompression;var AudioEngine = BABYLON.AudioEngine;var Sound = BABYLON.Sound;var SoundTrack = BABYLON.SoundTrack;var Analyser = BABYLON.Analyser;var CubeTexture = BABYLON.CubeTexture;var RenderTargetTexture = BABYLON.RenderTargetTexture;var MultiRenderTarget = BABYLON.MultiRenderTarget;var MirrorTexture = BABYLON.MirrorTexture;var RefractionTexture = BABYLON.RefractionTexture;var DynamicTexture = BABYLON.DynamicTexture;var VideoTexture = BABYLON.VideoTexture;var RawTexture = BABYLON.RawTexture;var PostProcess = BABYLON.PostProcess;var PassPostProcess = BABYLON.PassPostProcess;var ShadowGenerator = BABYLON.ShadowGenerator;var DefaultLoadingScreen = BABYLON.DefaultLoadingScreen;var SceneLoaderProgressEvent = BABYLON.SceneLoaderProgressEvent;var SceneLoader = BABYLON.SceneLoader;var FilesInput = BABYLON.FilesInput;var StringDictionary = BABYLON.StringDictionary;var Tags = BABYLON.Tags;var AndOrNotEvaluator = BABYLON.AndOrNotEvaluator;var Database = BABYLON.Database;var FresnelParameters = BABYLON.FresnelParameters;var MultiMaterial = BABYLON.MultiMaterial;var FreeCameraTouchInput = BABYLON.FreeCameraTouchInput;var TouchCamera = BABYLON.TouchCamera;var ProceduralTexture = BABYLON.ProceduralTexture;var CustomProceduralTexture = BABYLON.CustomProceduralTexture;var FreeCameraGamepadInput = BABYLON.FreeCameraGamepadInput;var ArcRotateCameraGamepadInput = BABYLON.ArcRotateCameraGamepadInput;var GamepadManager = BABYLON.GamepadManager;var StickValues = BABYLON.StickValues;var Gamepad = BABYLON.Gamepad;var GenericPad = BABYLON.GenericPad;var Xbox360Pad = BABYLON.Xbox360Pad;var PoseEnabledControllerHelper = BABYLON.PoseEnabledControllerHelper;var PoseEnabledController = BABYLON.PoseEnabledController;var WebVRController = BABYLON.WebVRController;var OculusTouchController = BABYLON.OculusTouchController;var ViveController = BABYLON.ViveController;var GenericController = BABYLON.GenericController;var WindowsMotionController = BABYLON.WindowsMotionController;var GearVRController = BABYLON.GearVRController;var FollowCamera = BABYLON.FollowCamera;var ArcFollowCamera = BABYLON.ArcFollowCamera;var UniversalCamera = BABYLON.UniversalCamera;var GamepadCamera = BABYLON.GamepadCamera;var PostProcessRenderPipelineManager = BABYLON.PostProcessRenderPipelineManager;var PostProcessRenderEffect = BABYLON.PostProcessRenderEffect;var PostProcessRenderPipeline = BABYLON.PostProcessRenderPipeline;var DepthRenderer = BABYLON.DepthRenderer;var SSAORenderingPipeline = BABYLON.SSAORenderingPipeline;var SSAO2RenderingPipeline = BABYLON.SSAO2RenderingPipeline;var LensRenderingPipeline = BABYLON.LensRenderingPipeline;var StandardRenderingPipeline = BABYLON.StandardRenderingPipeline;var FxaaPostProcess = BABYLON.FxaaPostProcess;var CircleOfConfusionPostProcess = BABYLON.CircleOfConfusionPostProcess;var DepthOfFieldMergePostProcess = BABYLON.DepthOfFieldMergePostProcess;var DepthOfFieldEffect = BABYLON.DepthOfFieldEffect;var DefaultRenderingPipeline = BABYLON.DefaultRenderingPipeline;var GeometryBufferRenderer = BABYLON.GeometryBufferRenderer;var RefractionPostProcess = BABYLON.RefractionPostProcess;var BlackAndWhitePostProcess = BABYLON.BlackAndWhitePostProcess;var ConvolutionPostProcess = BABYLON.ConvolutionPostProcess;var FilterPostProcess = BABYLON.FilterPostProcess;var VolumetricLightScatteringPostProcess = BABYLON.VolumetricLightScatteringPostProcess;var ColorCorrectionPostProcess = BABYLON.ColorCorrectionPostProcess;var TonemapPostProcess = BABYLON.TonemapPostProcess;var DisplayPassPostProcess = BABYLON.DisplayPassPostProcess;var HighlightsPostProcess = BABYLON.HighlightsPostProcess;var ImageProcessingPostProcess = BABYLON.ImageProcessingPostProcess;var BlurPostProcess = BABYLON.BlurPostProcess;var DepthOfFieldBlurPostProcess = BABYLON.DepthOfFieldBlurPostProcess;var Bone = BABYLON.Bone;var BoneIKController = BABYLON.BoneIKController;var BoneLookController = BABYLON.BoneLookController;var Skeleton = BABYLON.Skeleton;var SphericalPolynomial = BABYLON.SphericalPolynomial;var SphericalHarmonics = BABYLON.SphericalHarmonics;var CubeMapToSphericalPolynomialTools = BABYLON.CubeMapToSphericalPolynomialTools;var PanoramaToCubeMapTools = BABYLON.PanoramaToCubeMapTools;var HDRTools = BABYLON.HDRTools;var HDRCubeTexture = BABYLON.HDRCubeTexture;var Polygon = BABYLON.Polygon;var PolygonMeshBuilder = BABYLON.PolygonMeshBuilder;var CSG = BABYLON.CSG;var LensFlare = BABYLON.LensFlare;var LensFlareSystem = BABYLON.LensFlareSystem;var PhysicsJoint = BABYLON.PhysicsJoint;var DistanceJoint = BABYLON.DistanceJoint;var MotorEnabledJoint = BABYLON.MotorEnabledJoint;var HingeJoint = BABYLON.HingeJoint;var Hinge2Joint = BABYLON.Hinge2Joint;var PhysicsImpostor = BABYLON.PhysicsImpostor;var PhysicsEngine = BABYLON.PhysicsEngine;var PhysicsHelper = BABYLON.PhysicsHelper;var PhysicsRadialExplosionEvent = BABYLON.PhysicsRadialExplosionEvent;var PhysicsGravitationalFieldEvent = BABYLON.PhysicsGravitationalFieldEvent;var PhysicsUpdraftEvent = BABYLON.PhysicsUpdraftEvent;var PhysicsVortexEvent = BABYLON.PhysicsVortexEvent;var CannonJSPlugin = BABYLON.CannonJSPlugin;var OimoJSPlugin = BABYLON.OimoJSPlugin;var TGATools = BABYLON.TGATools;var DDSTools = BABYLON.DDSTools;var KhronosTextureContainer = BABYLON.KhronosTextureContainer;var Debug = BABYLON.Debug;var RayHelper = BABYLON.RayHelper;var DebugLayer = BABYLON.DebugLayer;var BoundingBoxRenderer = BABYLON.BoundingBoxRenderer;var MorphTarget = BABYLON.MorphTarget;var MorphTargetManager = BABYLON.MorphTargetManager;var Octree = BABYLON.Octree;var OctreeBlock = BABYLON.OctreeBlock;var VRDistortionCorrectionPostProcess = BABYLON.VRDistortionCorrectionPostProcess;var AnaglyphPostProcess = BABYLON.AnaglyphPostProcess;var StereoscopicInterlacePostProcess = BABYLON.StereoscopicInterlacePostProcess;var FreeCameraDeviceOrientationInput = BABYLON.FreeCameraDeviceOrientationInput;var ArcRotateCameraVRDeviceOrientationInput = BABYLON.ArcRotateCameraVRDeviceOrientationInput;var VRCameraMetrics = BABYLON.VRCameraMetrics;var WebVRFreeCamera = BABYLON.WebVRFreeCamera;var DeviceOrientationCamera = BABYLON.DeviceOrientationCamera;var VRDeviceOrientationFreeCamera = BABYLON.VRDeviceOrientationFreeCamera;var VRDeviceOrientationGamepadCamera = BABYLON.VRDeviceOrientationGamepadCamera;var VRDeviceOrientationArcRotateCamera = BABYLON.VRDeviceOrientationArcRotateCamera;var AnaglyphFreeCamera = BABYLON.AnaglyphFreeCamera;var AnaglyphArcRotateCamera = BABYLON.AnaglyphArcRotateCamera;var AnaglyphGamepadCamera = BABYLON.AnaglyphGamepadCamera;var AnaglyphUniversalCamera = BABYLON.AnaglyphUniversalCamera;var StereoscopicFreeCamera = BABYLON.StereoscopicFreeCamera;var StereoscopicArcRotateCamera = BABYLON.StereoscopicArcRotateCamera;var StereoscopicGamepadCamera = BABYLON.StereoscopicGamepadCamera;var StereoscopicUniversalCamera = BABYLON.StereoscopicUniversalCamera;var VRExperienceHelper = BABYLON.VRExperienceHelper;var VirtualJoystick = BABYLON.VirtualJoystick;var VirtualJoysticksCamera = BABYLON.VirtualJoysticksCamera;var FreeCameraVirtualJoystickInput = BABYLON.FreeCameraVirtualJoystickInput;var SimplificationSettings = BABYLON.SimplificationSettings;var SimplificationQueue = BABYLON.SimplificationQueue;var DecimationTriangle = BABYLON.DecimationTriangle;var DecimationVertex = BABYLON.DecimationVertex;var QuadraticMatrix = BABYLON.QuadraticMatrix;var Reference = BABYLON.Reference;var QuadraticErrorSimplification = BABYLON.QuadraticErrorSimplification;var MeshLODLevel = BABYLON.MeshLODLevel;var SceneOptimization = BABYLON.SceneOptimization;var TextureOptimization = BABYLON.TextureOptimization;var HardwareScalingOptimization = BABYLON.HardwareScalingOptimization;var ShadowsOptimization = BABYLON.ShadowsOptimization;var PostProcessesOptimization = BABYLON.PostProcessesOptimization;var LensFlaresOptimization = BABYLON.LensFlaresOptimization;var CustomOptimization = BABYLON.CustomOptimization;var ParticlesOptimization = BABYLON.ParticlesOptimization;var RenderTargetsOptimization = BABYLON.RenderTargetsOptimization;var MergeMeshesOptimization = BABYLON.MergeMeshesOptimization;var SceneOptimizerOptions = BABYLON.SceneOptimizerOptions;var SceneOptimizer = BABYLON.SceneOptimizer;var OutlineRenderer = BABYLON.OutlineRenderer;var EdgesRenderer = BABYLON.EdgesRenderer;var EffectLayer = BABYLON.EffectLayer;var HighlightLayer = BABYLON.HighlightLayer;var GlowLayer = BABYLON.GlowLayer;var AbstractAssetTask = BABYLON.AbstractAssetTask;var AssetsProgressEvent = BABYLON.AssetsProgressEvent;var MeshAssetTask = BABYLON.MeshAssetTask;var TextFileAssetTask = BABYLON.TextFileAssetTask;var BinaryFileAssetTask = BABYLON.BinaryFileAssetTask;var ImageAssetTask = BABYLON.ImageAssetTask;var TextureAssetTask = BABYLON.TextureAssetTask;var CubeTextureAssetTask = BABYLON.CubeTextureAssetTask;var HDRCubeTextureAssetTask = BABYLON.HDRCubeTextureAssetTask;var AssetsManager = BABYLON.AssetsManager;var SceneSerializer = BABYLON.SceneSerializer;var ReflectionProbe = BABYLON.ReflectionProbe;var Layer = BABYLON.Layer;var TextureTools = BABYLON.TextureTools;var FramingBehavior = BABYLON.FramingBehavior;var BouncingBehavior = BABYLON.BouncingBehavior;var AutoRotationBehavior = BABYLON.AutoRotationBehavior;var NullEngineOptions = BABYLON.NullEngineOptions;var NullEngine = BABYLON.NullEngine;var EngineInstrumentation = BABYLON.EngineInstrumentation;var SceneInstrumentation = BABYLON.SceneInstrumentation;var _TimeToken = BABYLON._TimeToken;var BackgroundMaterial = BABYLON.BackgroundMaterial;var EnvironmentHelper = BABYLON.EnvironmentHelper;var VideoDome = BABYLON.VideoDome;
  89609. export { EffectFallbacks,EffectCreationOptions,Effect,KeyboardEventTypes,KeyboardInfo,KeyboardInfoPre,PointerEventTypes,PointerInfoBase,PointerInfoPre,PointerInfo,Color3,Color4,Vector2,Vector3,Vector4,Size,Quaternion,Matrix,Plane,Viewport,Frustum,Axis,BezierCurve,Angle,Arc2,Path2,Path3D,Curve3,PositionNormalVertex,PositionNormalTextureVertex,Tmp,Scalar,expandToProperty,serialize,serializeAsTexture,serializeAsColor3,serializeAsFresnelParameters,serializeAsVector2,serializeAsVector3,serializeAsMeshReference,serializeAsColorCurves,serializeAsColor4,serializeAsImageProcessingConfiguration,serializeAsQuaternion,SerializationHelper,Deferred,EventState,Observer,MultiObserver,Observable,SmartArray,SmartArrayNoDuplicate,LoadFileError,RetryStrategy,Tools,PerfCounter,className,AsyncLoop,PromisePolyfill,_AlphaState,_DepthCullingState,_StencilState,InstancingAttributeInfo,RenderTargetCreationOptions,EngineCapabilities,Engine,Node,BoundingSphere,BoundingBox,BoundingInfo,TransformNode,AbstractMesh,Light,Camera,RenderingManager,RenderingGroup,RenderingGroupInfo,Scene,KeepAssets,AssetContainer,Buffer,VertexBuffer,DummyInternalTextureTracker,InternalTexture,BaseTexture,Texture,_InstancesBatch,Mesh,BaseSubMesh,SubMesh,MaterialDefines,Material,UniformBuffer,VertexData,Geometry,_PrimitiveGeometry,RibbonGeometry,BoxGeometry,SphereGeometry,DiscGeometry,CylinderGeometry,TorusGeometry,GroundGeometry,TiledGroundGeometry,PlaneGeometry,TorusKnotGeometry,PostProcessManager,PerformanceMonitor,RollingAverage,ImageProcessingConfiguration,ColorGradingTexture,ColorCurves,MaterialHelper,PushMaterial,StandardMaterialDefines,StandardMaterial,PBRBaseMaterial,PBRBaseSimpleMaterial,PBRMaterial,PBRMetallicRoughnessMaterial,PBRSpecularGlossinessMaterial,CameraInputsManager,TargetCamera,FreeCameraMouseInput,FreeCameraKeyboardMoveInput,FreeCameraInputsManager,FreeCamera,ArcRotateCameraKeyboardMoveInput,ArcRotateCameraMouseWheelInput,ArcRotateCameraPointersInput,ArcRotateCameraInputsManager,ArcRotateCamera,HemisphericLight,ShadowLight,PointLight,DirectionalLight,SpotLight,AnimationRange,AnimationEvent,PathCursor,Animation,TargetedAnimation,AnimationGroup,RuntimeAnimation,Animatable,EasingFunction,CircleEase,BackEase,BounceEase,CubicEase,ElasticEase,ExponentialEase,PowerEase,QuadraticEase,QuarticEase,QuinticEase,SineEase,BezierCurveEase,Condition,ValueCondition,PredicateCondition,StateCondition,Action,ActionEvent,ActionManager,InterpolateValueAction,SwitchBooleanAction,SetStateAction,SetValueAction,IncrementValueAction,PlayAnimationAction,StopAnimationAction,DoNothingAction,CombineAction,ExecuteCodeAction,SetParentAction,PlaySoundAction,StopSoundAction,SpriteManager,Sprite,IntersectionInfo,PickingInfo,Ray,Collider,CollisionCoordinatorWorker,CollisionCoordinatorLegacy,Particle,ParticleSystem,BoxParticleEmitter,ConeParticleEmitter,SphereParticleEmitter,SphereDirectedParticleEmitter,GPUParticleSystem,SolidParticle,ModelShape,DepthSortedParticle,SolidParticleSystem,ShaderMaterial,GroundMesh,InstancedMesh,LinesMesh,MeshBuilder,DracoCompression,AudioEngine,Sound,SoundTrack,Analyser,CubeTexture,RenderTargetTexture,MultiRenderTarget,MirrorTexture,RefractionTexture,DynamicTexture,VideoTexture,RawTexture,PostProcess,PassPostProcess,ShadowGenerator,DefaultLoadingScreen,SceneLoaderProgressEvent,SceneLoader,FilesInput,StringDictionary,Tags,AndOrNotEvaluator,Database,FresnelParameters,MultiMaterial,FreeCameraTouchInput,TouchCamera,ProceduralTexture,CustomProceduralTexture,FreeCameraGamepadInput,ArcRotateCameraGamepadInput,GamepadManager,StickValues,Gamepad,GenericPad,Xbox360Pad,PoseEnabledControllerHelper,PoseEnabledController,WebVRController,OculusTouchController,ViveController,GenericController,WindowsMotionController,GearVRController,FollowCamera,ArcFollowCamera,UniversalCamera,GamepadCamera,PostProcessRenderPipelineManager,PostProcessRenderEffect,PostProcessRenderPipeline,DepthRenderer,SSAORenderingPipeline,SSAO2RenderingPipeline,LensRenderingPipeline,StandardRenderingPipeline,FxaaPostProcess,CircleOfConfusionPostProcess,DepthOfFieldMergePostProcess,DepthOfFieldEffect,DefaultRenderingPipeline,GeometryBufferRenderer,RefractionPostProcess,BlackAndWhitePostProcess,ConvolutionPostProcess,FilterPostProcess,VolumetricLightScatteringPostProcess,ColorCorrectionPostProcess,TonemapPostProcess,DisplayPassPostProcess,HighlightsPostProcess,ImageProcessingPostProcess,BlurPostProcess,DepthOfFieldBlurPostProcess,Bone,BoneIKController,BoneLookController,Skeleton,SphericalPolynomial,SphericalHarmonics,CubeMapToSphericalPolynomialTools,PanoramaToCubeMapTools,HDRTools,HDRCubeTexture,Polygon,PolygonMeshBuilder,CSG,LensFlare,LensFlareSystem,PhysicsJoint,DistanceJoint,MotorEnabledJoint,HingeJoint,Hinge2Joint,PhysicsImpostor,PhysicsEngine,PhysicsHelper,PhysicsRadialExplosionEvent,PhysicsGravitationalFieldEvent,PhysicsUpdraftEvent,PhysicsVortexEvent,CannonJSPlugin,OimoJSPlugin,TGATools,DDSTools,KhronosTextureContainer,Debug,RayHelper,DebugLayer,BoundingBoxRenderer,MorphTarget,MorphTargetManager,Octree,OctreeBlock,VRDistortionCorrectionPostProcess,AnaglyphPostProcess,StereoscopicInterlacePostProcess,FreeCameraDeviceOrientationInput,ArcRotateCameraVRDeviceOrientationInput,VRCameraMetrics,WebVRFreeCamera,DeviceOrientationCamera,VRDeviceOrientationFreeCamera,VRDeviceOrientationGamepadCamera,VRDeviceOrientationArcRotateCamera,AnaglyphFreeCamera,AnaglyphArcRotateCamera,AnaglyphGamepadCamera,AnaglyphUniversalCamera,StereoscopicFreeCamera,StereoscopicArcRotateCamera,StereoscopicGamepadCamera,StereoscopicUniversalCamera,VRExperienceHelper,VirtualJoystick,VirtualJoysticksCamera,FreeCameraVirtualJoystickInput,SimplificationSettings,SimplificationQueue,DecimationTriangle,DecimationVertex,QuadraticMatrix,Reference,QuadraticErrorSimplification,MeshLODLevel,SceneOptimization,TextureOptimization,HardwareScalingOptimization,ShadowsOptimization,PostProcessesOptimization,LensFlaresOptimization,CustomOptimization,ParticlesOptimization,RenderTargetsOptimization,MergeMeshesOptimization,SceneOptimizerOptions,SceneOptimizer,OutlineRenderer,EdgesRenderer,EffectLayer,HighlightLayer,GlowLayer,AbstractAssetTask,AssetsProgressEvent,MeshAssetTask,TextFileAssetTask,BinaryFileAssetTask,ImageAssetTask,TextureAssetTask,CubeTextureAssetTask,HDRCubeTextureAssetTask,AssetsManager,SceneSerializer,ReflectionProbe,Layer,TextureTools,FramingBehavior,BouncingBehavior,AutoRotationBehavior,NullEngineOptions,NullEngine,EngineInstrumentation,SceneInstrumentation,_TimeToken,BackgroundMaterial,EnvironmentHelper,VideoDome };